@bumail/queue 0.1.0

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.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +243 -0
  3. package/dist/chunks/index-p4k4rjb7.js +15 -0
  4. package/dist/chunks/index-p4k4rjb7.js.map +10 -0
  5. package/dist/chunks/index-xhsw4xcz.js +119 -0
  6. package/dist/chunks/index-xhsw4xcz.js.map +10 -0
  7. package/dist/contract/checks.d.ts +27 -0
  8. package/dist/contract/checks.d.ts.map +1 -0
  9. package/dist/contract/queue-store.d.ts +60 -0
  10. package/dist/contract/queue-store.d.ts.map +1 -0
  11. package/dist/contract/types.d.ts +102 -0
  12. package/dist/contract/types.d.ts.map +1 -0
  13. package/dist/dsn/build.d.ts +35 -0
  14. package/dist/dsn/build.d.ts.map +1 -0
  15. package/dist/dsn/content.d.ts +18 -0
  16. package/dist/dsn/content.d.ts.map +1 -0
  17. package/dist/dsn/fields.d.ts +38 -0
  18. package/dist/dsn/fields.d.ts.map +1 -0
  19. package/dist/errors.d.ts +17 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/index.d.ts +8 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +1089 -0
  24. package/dist/index.js.map +30 -0
  25. package/dist/memory/index.d.ts +2 -0
  26. package/dist/memory/index.d.ts.map +1 -0
  27. package/dist/memory/index.js +121 -0
  28. package/dist/memory/index.js.map +10 -0
  29. package/dist/memory/store.d.ts +21 -0
  30. package/dist/memory/store.d.ts.map +1 -0
  31. package/dist/queue/deliver.d.ts +20 -0
  32. package/dist/queue/deliver.d.ts.map +1 -0
  33. package/dist/queue/envelope.d.ts +26 -0
  34. package/dist/queue/envelope.d.ts.map +1 -0
  35. package/dist/queue/events.d.ts +48 -0
  36. package/dist/queue/events.d.ts.map +1 -0
  37. package/dist/queue/limiter.d.ts +14 -0
  38. package/dist/queue/limiter.d.ts.map +1 -0
  39. package/dist/queue/notify.d.ts +19 -0
  40. package/dist/queue/notify.d.ts.map +1 -0
  41. package/dist/queue/options.d.ts +111 -0
  42. package/dist/queue/options.d.ts.map +1 -0
  43. package/dist/queue/outcome.d.ts +26 -0
  44. package/dist/queue/outcome.d.ts.map +1 -0
  45. package/dist/queue/queue.d.ts +43 -0
  46. package/dist/queue/queue.d.ts.map +1 -0
  47. package/dist/queue/retry.d.ts +16 -0
  48. package/dist/queue/retry.d.ts.map +1 -0
  49. package/dist/queue/route.d.ts +10 -0
  50. package/dist/queue/route.d.ts.map +1 -0
  51. package/dist/queue/settings/dsn.d.ts +8 -0
  52. package/dist/queue/settings/dsn.d.ts.map +1 -0
  53. package/dist/queue/settings/index.d.ts +25 -0
  54. package/dist/queue/settings/index.d.ts.map +1 -0
  55. package/dist/queue/settings/limits.d.ts +18 -0
  56. package/dist/queue/settings/limits.d.ts.map +1 -0
  57. package/dist/queue/settings/numbers.d.ts +7 -0
  58. package/dist/queue/settings/numbers.d.ts.map +1 -0
  59. package/dist/queue/settings/routes.d.ts +3 -0
  60. package/dist/queue/settings/routes.d.ts.map +1 -0
  61. package/dist/queue/settings/sessions.d.ts +5 -0
  62. package/dist/queue/settings/sessions.d.ts.map +1 -0
  63. package/dist/queue/settle.d.ts +21 -0
  64. package/dist/queue/settle.d.ts.map +1 -0
  65. package/dist/queue/worker.d.ts +27 -0
  66. package/dist/queue/worker.d.ts.map +1 -0
  67. package/dist/sqlite/index.d.ts +2 -0
  68. package/dist/sqlite/index.d.ts.map +1 -0
  69. package/dist/sqlite/index.js +288 -0
  70. package/dist/sqlite/index.js.map +13 -0
  71. package/dist/sqlite/open.d.ts +8 -0
  72. package/dist/sqlite/open.d.ts.map +1 -0
  73. package/dist/sqlite/options.d.ts +16 -0
  74. package/dist/sqlite/options.d.ts.map +1 -0
  75. package/dist/sqlite/rows.d.ts +28 -0
  76. package/dist/sqlite/rows.d.ts.map +1 -0
  77. package/dist/sqlite/schema.d.ts +14 -0
  78. package/dist/sqlite/schema.d.ts.map +1 -0
  79. package/dist/sqlite/store.d.ts +30 -0
  80. package/dist/sqlite/store.d.ts.map +1 -0
  81. package/dist/text.d.ts +14 -0
  82. package/dist/text.d.ts.map +1 -0
  83. package/docs/README.md +10 -0
  84. package/docs/guide.md +461 -0
  85. package/docs/roadmap.md +67 -0
  86. package/docs/troubleshooting.md +394 -0
  87. package/package.json +71 -0
@@ -0,0 +1,30 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/queue/envelope.ts", "../src/text.ts", "../src/queue/events.ts", "../src/queue/settings/index.ts", "../src/queue/settings/numbers.ts", "../src/queue/settings/dsn.ts", "../src/queue/settings/limits.ts", "../src/queue/settings/sessions.ts", "../src/queue/settings/routes.ts", "../src/queue/deliver.ts", "../src/dsn/build.ts", "../src/dsn/content.ts", "../src/dsn/fields.ts", "../src/queue/retry.ts", "../src/queue/notify.ts", "../src/queue/outcome.ts", "../src/queue/route.ts", "../src/queue/settle.ts", "../src/queue/limiter.ts", "../src/queue/worker.ts", "../src/queue/queue.ts"],
4
+ "sourcesContent": [
5
+ "import { isMailbox } from '@bumail/smtp/client';\nimport { invalid, QueueError } from '../errors';\nimport { hasControl } from '../text';\n\n/** What `enqueue` takes as the message: its bytes, its text, or a stream of it. */\nexport type MessageSource = Uint8Array | string | ReadableStream<Uint8Array>;\n\n/** The SMTP envelope of a message to send. */\nexport interface QueueEnvelope {\n\t/** The reverse-path, `local@domain`; `''` for the null sender (a bounce of your own). */\n\treadonly from: string;\n\t/** One recipient or more, `local@domain` each. */\n\treadonly to: string | readonly string[];\n}\n\n/**\n * An address as SMTP carries it: a local part, `@`, a domain, 254\n * characters at most (RFC 5321 §4.5.3.1.3's path, less its brackets), with\n * no space, no control character and no angle bracket, so it can never\n * break a command line or a header field — and one `sendMail` takes\n * (`isMailbox`, RFC 5321's grammar), so it is refused here, never at\n * delivery, where it would fail its whole domain's group.\n */\nconst ADDRESS = /^[^\\s<>]{1,64}@[^\\s<>@]{1,253}$/u;\n\nexport function checkAddress(name: string, address: unknown): string {\n\tif (\n\t\ttypeof address !== 'string' ||\n\t\taddress.length > 254 ||\n\t\thasControl(address) ||\n\t\t!ADDRESS.test(address) ||\n\t\t!isMailbox(address)\n\t) {\n\t\tthrow invalid(\n\t\t\t`${name} must be an address, local@domain, not ${JSON.stringify(address)}`,\n\t\t);\n\t}\n\treturn address;\n}\n\n/** The recipient's domain, in lowercase: what deliveries are grouped by. */\nexport const domainOf = (address: string) =>\n\taddress.slice(address.lastIndexOf('@') + 1).toLowerCase();\n\n/** The envelope, checked: the sender, and each recipient once, at most `maxRecipients`. */\nexport function checkEnvelope(\n\tenvelope: QueueEnvelope,\n\tmaxRecipients: number,\n): { from: string; to: string[] } {\n\tif (typeof envelope !== 'object' || envelope === null) {\n\t\tthrow invalid('The envelope is an object: { from, to }');\n\t}\n\tconst from = envelope.from === '' ? '' : checkAddress('from', envelope.from);\n\tconst list = typeof envelope.to === 'string' ? [envelope.to] : envelope.to;\n\tif (!Array.isArray(list) || list.length === 0) {\n\t\tthrow invalid('to must hold one recipient or more');\n\t}\n\tconst seen = new Set<string>();\n\tconst to: string[] = [];\n\tfor (const address of list) {\n\t\tcheckAddress('Each recipient', address);\n\t\tconst key = `${address.slice(0, address.lastIndexOf('@'))}@${domainOf(address)}`;\n\t\tif (seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tto.push(address);\n\t}\n\tif (to.length > maxRecipients) {\n\t\tthrow new QueueError(\n\t\t\t'TOO_MANY_RECIPIENTS',\n\t\t\t`The message has ${to.length} recipients; the limit is ${maxRecipients}`,\n\t\t);\n\t}\n\treturn { from, to };\n}\n\nconst tooBig = (max: number) =>\n\tnew QueueError(\n\t\t'MESSAGE_TOO_BIG',\n\t\t`The message is larger than the limit of ${max} bytes`,\n\t);\n\nconst CR = 0x0d;\nconst LF = 0x0a;\n\n/**\n * Refuses a message with a CR not followed by an LF, or an LF not after a\n * CR: `sendMail` would refuse it at delivery (`BARE_LINE_BREAK`, SMTP\n * smuggling), failing every recipient.\n */\nexport function checkLineEnds(bytes: Uint8Array): void {\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\tconst byte = bytes[i];\n\t\tconst bare =\n\t\t\tbyte === CR\n\t\t\t\t? bytes[i + 1] !== LF\n\t\t\t\t: byte === LF && (i === 0 || bytes[i - 1] !== CR);\n\t\tif (bare) {\n\t\t\tthrow invalid(\n\t\t\t\t`The message has a bare CR or LF at byte ${i}: every line must end in CRLF`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/** The message's bytes, read to its end but never past `max`: past it, `MESSAGE_TOO_BIG`. */\nexport async function readMessage(\n\tsource: MessageSource,\n\tmax: number,\n): Promise<Uint8Array> {\n\tif (typeof source === 'string') source = new TextEncoder().encode(source);\n\tif (source instanceof Uint8Array) {\n\t\tif (source.length > max) throw tooBig(max);\n\t\treturn source.slice();\n\t}\n\tif (!(source instanceof ReadableStream)) {\n\t\tthrow invalid(\n\t\t\t'The message is a Uint8Array, a string or a ReadableStream<Uint8Array>',\n\t\t);\n\t}\n\tconst chunks: Uint8Array[] = [];\n\tlet size = 0;\n\tconst reader = source.getReader();\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tif (!(value instanceof Uint8Array)) {\n\t\t\t\tthrow invalid('The message stream must give Uint8Array chunks');\n\t\t\t}\n\t\t\tsize += value.length;\n\t\t\tif (size > max) throw tooBig(max);\n\t\t\tchunks.push(value);\n\t\t}\n\t} catch (error) {\n\t\tawait reader.cancel().catch(() => {});\n\t\tthrow error;\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\tconst bytes = new Uint8Array(size);\n\tlet at = 0;\n\tfor (const chunk of chunks) {\n\t\tbytes.set(chunk, at);\n\t\tat += chunk.length;\n\t}\n\treturn bytes;\n}\n",
6
+ "/** Text from the other side, made safe to keep and to write in a header field. */\n\n/** C0, DEL and C1: every control character, CR, LF and TAB included. */\nconst isControl = (code: number) =>\n\tcode < 0x20 || (code >= 0x7f && code <= 0x9f);\n\n/** Whether the text holds a control character. */\nexport function hasControl(text: string): boolean {\n\tfor (let i = 0; i < text.length; i++) {\n\t\tif (isControl(text.charCodeAt(i))) return true;\n\t}\n\treturn false;\n}\n\n/** Each control character replaced by `by`. */\nexport function replaceControls(text: string, by: string): string {\n\tlet out = '';\n\tfor (let i = 0; i < text.length; i++) {\n\t\tout += isControl(text.charCodeAt(i)) ? by : (text[i] as string);\n\t}\n\treturn out;\n}\n\n/**\n * Every control character (CR and LF included) as a space, runs of space\n * as one, cut at `max` characters with `...`: what a reply leaves in an\n * item, an event and a DSN.\n */\nexport function cleanText(text: string, max: number): string {\n\tconst clean = replaceControls(text, ' ').replace(/ {2,}/g, ' ').trim();\n\treturn clean.length > max ? `${clean.slice(0, max - 3)}...` : clean;\n}\n\n/** `cleanText`, then anything not printable ASCII as `?`: for a `message/delivery-status` field. */\nexport const asciiText = (text: string, max: number): string =>\n\tcleanText(text, max).replace(/[^ -~]/g, '?');\n",
7
+ "import type { Diagnostic } from '../contract/types';\n\n/** One recipient's outcome. */\nexport interface RecipientEvent {\n\t/** The item's id. */\n\treadonly id: string;\n\treadonly from: string;\n\treadonly recipient: string;\n\t/** What the other side said, or why nobody said anything. */\n\treadonly reply?: Diagnostic;\n\t/** The attempts made so far, this one included. */\n\treadonly attempts: number;\n}\n\nexport interface DeferredEvent extends RecipientEvent {\n\t/** When the recipient is tried again, in milliseconds since the epoch. */\n\treadonly nextAttemptAt: number;\n}\n\n/** A DSN, enqueued back to the sender. */\nexport interface DsnEvent {\n\treadonly kind: 'delayed' | 'failed';\n\t/** The DSN's own item id. */\n\treadonly id: string;\n\t/** The id of the item it reports on. */\n\treadonly of: string;\n\t/** The original's sender, to whom it goes. */\n\treadonly to: string;\n\treadonly recipients: readonly string[];\n}\n\n/** A failure of the queue itself: the store, a DSN that could not be enqueued, a lease lost. */\nexport interface QueueErrorEvent {\n\treadonly error: unknown;\n\t/** The item it happened to, if any. */\n\treadonly id?: string;\n}\n\nexport interface QueueEvents {\n\tdelivered: RecipientEvent;\n\tdeferred: DeferredEvent;\n\tfailed: RecipientEvent;\n\tdsn: DsnEvent;\n\terror: QueueErrorEvent;\n}\n\nexport type QueueListener<E extends keyof QueueEvents> = (\n\tevent: QueueEvents[E],\n) => void;\n\n/** Listeners by event. One that throws is ignored: it never stops a delivery. */\nexport class Events {\n\treadonly #listeners = new Map<keyof QueueEvents, Set<(e: never) => void>>();\n\n\ton<E extends keyof QueueEvents>(\n\t\tevent: E,\n\t\tlistener: QueueListener<E>,\n\t): () => void {\n\t\tlet set = this.#listeners.get(event);\n\t\tif (!set) {\n\t\t\tset = new Set();\n\t\t\tthis.#listeners.set(event, set);\n\t\t}\n\t\tset.add(listener as (e: never) => void);\n\t\treturn () => {\n\t\t\tset.delete(listener as (e: never) => void);\n\t\t};\n\t}\n\n\temit<E extends keyof QueueEvents>(event: E, payload: QueueEvents[E]): void {\n\t\tfor (const listener of this.#listeners.get(event) ?? []) {\n\t\t\ttry {\n\t\t\t\t(listener as QueueListener<E>)(payload);\n\t\t\t} catch {\n\t\t\t\t// A listener's failure is its own.\n\t\t\t}\n\t\t}\n\t}\n}\n",
8
+ "import { sendMail } from '@bumail/smtp/client';\nimport { invalid } from '../../errors';\nimport type { QueueOptions, Route, Sender } from '../options';\nimport { type DsnSettings, dsnOf } from './dsn';\nimport {\n\ttype LimitSettings,\n\tlimitsOf,\n\ttype RetrySettings,\n\tretryOf,\n} from './limits';\nimport { MAX_TIMER, MINUTE, numberOf } from './numbers';\nimport { checkRoutes } from './routes';\nimport { checkSessions } from './sessions';\n\nexport type { DsnSettings, LimitSettings, RetrySettings };\n\n/** Every option checked, with its default. */\nexport interface Settings {\n\treadonly options: QueueOptions;\n\treadonly hostname: string;\n\t/** The routes by domain, in lowercase. */\n\treadonly routes: ReadonlyMap<string, Route>;\n\treadonly retry: RetrySettings;\n\treadonly limits: LimitSettings;\n\treadonly dsn: DsnSettings;\n\treadonly concurrency: number;\n\treadonly perDomain: number;\n\treadonly leaseMs: number;\n\treadonly pollInterval: number;\n\treadonly owner: string;\n\treadonly now: () => number;\n\treadonly send: Sender;\n\treadonly random: () => number;\n}\n\nconst HOSTNAME =\n\t/^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*$/;\n\n/** The options, checked, with their defaults; `INVALID` names the first wrong one. */\nexport function settingsOf(options: QueueOptions): Settings {\n\tif (typeof options !== 'object' || options === null) {\n\t\tthrow invalid('createQueue() takes an options object');\n\t}\n\tif (typeof options.store?.claim !== 'function') {\n\t\tthrow invalid('store must be a QueueStore, such as MemoryQueueStore');\n\t}\n\tconst { hostname } = options;\n\tif (typeof hostname !== 'string' || !HOSTNAME.test(hostname)) {\n\t\tthrow invalid(\n\t\t\t`hostname must be this server's public host name, not ${hostname}`,\n\t\t);\n\t}\n\tcheckRoutes(options);\n\tcheckSessions(options);\n\tconst owner = options.owner ?? crypto.randomUUID();\n\tif (typeof owner !== 'string' || owner === '') {\n\t\tthrow invalid('owner must be a non-empty string');\n\t}\n\tconst clock = options.clock;\n\treturn {\n\t\toptions,\n\t\thostname,\n\t\troutes: new Map(\n\t\t\tObject.entries(options.routes ?? {}).map(([d, r]) => [\n\t\t\t\td.toLowerCase(),\n\t\t\t\tr,\n\t\t\t]),\n\t\t),\n\t\tretry: retryOf(options),\n\t\tlimits: limitsOf(options),\n\t\tdsn: dsnOf(options, hostname),\n\t\tconcurrency: numberOf('concurrency', options.concurrency, 20, 1),\n\t\tperDomain: numberOf('perDomain', options.perDomain, 2, 1),\n\t\tleaseMs: numberOf(\n\t\t\t'leaseMs',\n\t\t\toptions.leaseMs,\n\t\t\t10 * MINUTE,\n\t\t\t1000,\n\t\t\t3 * MAX_TIMER,\n\t\t),\n\t\tpollInterval: numberOf(\n\t\t\t'pollInterval',\n\t\t\toptions.pollInterval,\n\t\t\t5000,\n\t\t\t1,\n\t\t\tMAX_TIMER,\n\t\t),\n\t\towner,\n\t\tnow: clock ? () => clock.now() : Date.now,\n\t\tsend: options.send ?? sendMail,\n\t\trandom: options.random ?? Math.random,\n\t};\n}\n",
9
+ "import { invalid } from '../../errors';\n\nexport const MINUTE = 60_000;\nexport const HOUR = 60 * MINUTE;\n/** The longest delay a timer takes: past it, Bun fires after 1 ms. */\nexport const MAX_TIMER = 2_147_483_647;\n\n/** A number in `[min, max]`, integer when asked, or its default. */\nexport function numberOf(\n\tname: string,\n\tvalue: unknown,\n\tfallback: number,\n\tmin: number,\n\tmax = Number.MAX_SAFE_INTEGER,\n\tinteger = true,\n): number {\n\tif (value === undefined) return fallback;\n\tconst ok =\n\t\ttypeof value === 'number' &&\n\t\t(integer ? Number.isInteger(value) : Number.isFinite(value)) &&\n\t\tvalue >= min &&\n\t\tvalue <= max;\n\tif (!ok) {\n\t\tconst kind = integer ? 'an integer' : 'a number';\n\t\tconst range =\n\t\t\tmax === Number.MAX_SAFE_INTEGER\n\t\t\t\t? `of at least ${min}`\n\t\t\t\t: `from ${min} to ${max}`;\n\t\tthrow invalid(`${name} must be ${kind} ${range}, not ${value}`);\n\t}\n\treturn value as number;\n}\n",
10
+ "import { invalid } from '../../errors';\nimport { checkAddress } from '../envelope';\nimport type { QueueOptions } from '../options';\nimport { HOUR, numberOf } from './numbers';\n\nexport interface DsnSettings {\n\treadonly from: string;\n\treadonly delayAfter: number | false;\n\treadonly returnContent: 'headers' | 'full';\n}\n\nexport function dsnOf(options: QueueOptions, hostname: string): DsnSettings {\n\tconst d = options.dsn ?? {};\n\tconst from = checkAddress('dsn.from', d.from ?? `postmaster@${hostname}`);\n\tconst delayAfter =\n\t\td.delayAfter === false\n\t\t\t? false\n\t\t\t: numberOf('dsn.delayAfter', d.delayAfter, 4 * HOUR, 0);\n\tconst returnContent = d.returnContent ?? 'headers';\n\tif (returnContent !== 'headers' && returnContent !== 'full') {\n\t\tthrow invalid(\n\t\t\t`dsn.returnContent must be 'headers' or 'full', not ${returnContent}`,\n\t\t);\n\t}\n\treturn { from, delayAfter, returnContent };\n}\n",
11
+ "import type { QueueOptions } from '../options';\nimport { HOUR, MINUTE, numberOf } from './numbers';\n\nexport interface RetrySettings {\n\treadonly first: number;\n\treadonly factor: number;\n\treadonly max: number;\n\treadonly jitter: number;\n\treadonly giveUpAfter: number;\n}\n\nexport interface LimitSettings {\n\treadonly maxMessageSize: number;\n\treadonly maxRecipients: number;\n\treadonly maxItems: number | undefined;\n\treadonly maxReplyText: number;\n\treadonly maxDsnReturn: number;\n}\n\nexport function retryOf(options: QueueOptions): RetrySettings {\n\tconst r = options.retry ?? {};\n\tconst first = numberOf('retry.first', r.first, 30 * MINUTE, 1);\n\treturn {\n\t\tfirst,\n\t\tfactor: numberOf('retry.factor', r.factor, 2, 1, 100, false),\n\t\tmax: numberOf('retry.max', r.max, Math.max(first, 4 * HOUR), first),\n\t\tjitter: numberOf('retry.jitter', r.jitter, 0.1, 0, 1, false),\n\t\tgiveUpAfter: numberOf('retry.giveUpAfter', r.giveUpAfter, 120 * HOUR, 0),\n\t};\n}\n\nexport function limitsOf(options: QueueOptions): LimitSettings {\n\tconst l = options.limits ?? {};\n\treturn {\n\t\tmaxMessageSize: numberOf(\n\t\t\t'limits.maxMessageSize',\n\t\t\tl.maxMessageSize,\n\t\t\t25 * 1024 * 1024,\n\t\t\t1,\n\t\t),\n\t\tmaxRecipients: numberOf('limits.maxRecipients', l.maxRecipients, 100, 1),\n\t\tmaxItems:\n\t\t\tl.maxItems === undefined\n\t\t\t\t? undefined\n\t\t\t\t: numberOf('limits.maxItems', l.maxItems, 0, 1),\n\t\tmaxReplyText: numberOf('limits.maxReplyText', l.maxReplyText, 512, 64, 900),\n\t\tmaxDsnReturn: numberOf('limits.maxDsnReturn', l.maxDsnReturn, 64 * 1024, 0),\n\t};\n}\n",
12
+ "import { invalid } from '../../errors';\nimport type { QueueOptions } from '../options';\nimport { MAX_TIMER, numberOf } from './numbers';\n\n/** The longest wait `sendMail` takes, in seconds: its timer's own limit. */\nconst MAX_SECONDS = Math.floor(MAX_TIMER / 1000);\n\nfunction checkSeconds(name: string, value: unknown): void {\n\tif (value === undefined) return;\n\tif (\n\t\ttypeof value !== 'number' ||\n\t\t!Number.isFinite(value) ||\n\t\tvalue <= 0 ||\n\t\tvalue > MAX_SECONDS\n\t) {\n\t\tthrow invalid(\n\t\t\t`${name} must be a number of seconds above 0 and at most ${MAX_SECONDS}, not ${value}`,\n\t\t);\n\t}\n}\n\nexport function checkTls(name: string, tls: unknown): void {\n\tif (\n\t\ttls !== undefined &&\n\t\ttls !== 'opportunistic' &&\n\t\ttls !== 'required' &&\n\t\ttls !== 'none'\n\t) {\n\t\tthrow invalid(\n\t\t\t`${name} must be 'opportunistic', 'required' or 'none', not ${tls}`,\n\t\t);\n\t}\n}\n\n/** What every session takes, whatever its route: the MX port and TLS, the timeouts. */\nexport function checkSessions(options: QueueOptions): void {\n\tnumberOf('mxPort', options.mxPort, 25, 1, 65535);\n\tcheckTls('mxTls', options.mxTls);\n\tconst timeouts = options.timeouts;\n\tif (timeouts !== undefined) {\n\t\tif (typeof timeouts !== 'object' || timeouts === null) {\n\t\t\tthrow invalid('timeouts must be an object of seconds');\n\t\t}\n\t\tfor (const [step, value] of Object.entries(timeouts)) {\n\t\t\tcheckSeconds(`timeouts.${step}`, value);\n\t\t}\n\t}\n\tcheckSeconds('deadline', options.deadline);\n}\n",
13
+ "import { invalid } from '../../errors';\nimport type { QueueOptions, Route, Smarthost } from '../options';\nimport { numberOf } from './numbers';\nimport { checkTls } from './sessions';\n\n/**\n * A smarthost `sendMail` will take, checked now rather than at each\n * delivery: a host, a port, a TLS mode, and credentials only over TLS\n * whose certificate is checked — `sendMail`'s own rule\n * (`@bumail/smtp`'s `client/settings.ts`), with no way out for a test.\n */\nfunction checkRoute(name: string, route: Route): void {\n\tif (route === 'mx') return;\n\tconst smarthost = route as Smarthost | undefined;\n\tconst host = smarthost?.host;\n\tif (typeof host !== 'string' || !/^[^\\s/]+$/.test(host)) {\n\t\tthrow invalid(`${name} must be 'mx' or a smarthost with a host`);\n\t}\n\tconst { port, secure, tls, auth } = smarthost as Smarthost;\n\tnumberOf(`${name}.port`, port, 25, 1, 65535);\n\tif (secure !== undefined && typeof secure !== 'boolean') {\n\t\tthrow invalid(`${name}.secure must be true or false, not ${secure}`);\n\t}\n\tcheckTls(`${name}.tls`, tls);\n\tif (tls === 'none' && secure) {\n\t\tthrow invalid(\n\t\t\t`${name}.secure is TLS from the first byte: it cannot go with tls: 'none'`,\n\t\t);\n\t}\n\tif (auth === undefined) return;\n\tif (typeof auth?.username !== 'string' || auth.username === '') {\n\t\tthrow invalid(`${name}.auth.username must be a non-empty string`);\n\t}\n\tif (typeof auth.password !== 'string' || auth.password === '') {\n\t\tthrow invalid(`${name}.auth.password must be a non-empty string`);\n\t}\n\tconst { mechanism } = auth;\n\tif (\n\t\tmechanism !== undefined &&\n\t\tmechanism !== 'PLAIN' &&\n\t\tmechanism !== 'LOGIN'\n\t) {\n\t\tthrow invalid(\n\t\t\t`${name}.auth.mechanism must be 'PLAIN' or 'LOGIN', not ${mechanism}`,\n\t\t);\n\t}\n\tif (tls !== undefined && tls !== 'required') {\n\t\tthrow invalid(\n\t\t\t`${name}.auth needs tls: 'required', the default with auth: with tls: '${tls}' the password would go to a server whose certificate is not checked`,\n\t\t);\n\t}\n}\n\nexport function checkRoutes(options: QueueOptions): void {\n\tcheckRoute('route', options.route ?? 'mx');\n\tconst routes = Object.entries(options.routes ?? {});\n\tfor (const [domain, route] of routes)\n\t\tcheckRoute(`routes[\"${domain}\"]`, route);\n\tconst usesMx =\n\t\t(options.route ?? 'mx') === 'mx' || routes.some(([, r]) => r === 'mx');\n\tif (usesMx && typeof options.resolver?.mx !== 'function') {\n\t\tthrow invalid(\n\t\t\t\"The 'mx' route needs a resolver, such as @bumail/dns's nodeResolver()\",\n\t\t);\n\t}\n}\n",
14
+ "import { isMailbox } from '@bumail/smtp/client';\nimport type { QueueItem, RecipientUpdate } from '../contract/types';\nimport { QueueError } from '../errors';\nimport { domainOf } from './envelope';\nimport type { Events } from './events';\nimport type { KeyedLimiter } from './limiter';\nimport { type NotifyContext, notify } from './notify';\nimport { isRouteError, outcomesOf, outcomesOfError } from './outcome';\nimport { hostOf, routeOf, sendOptionsOf } from './route';\nimport { type Settled, settle } from './settle';\n\nexport interface DeliveryContext extends NotifyContext {\n\treadonly domains: KeyedLimiter;\n\treadonly events: Events;\n\t/** The worker is stopping: a group not started yet is left for later. */\n\treadonly stopping: () => boolean;\n\t/** The outcome is recorded: the lease needs no more renewal. */\n\treadonly recorded: () => void;\n}\n\n/** The recipients still to deliver, by domain. */\nfunction groupsOf(item: QueueItem): Map<string, string[]> {\n\tconst groups = new Map<string, string[]>();\n\tfor (const r of item.recipients) {\n\t\tif (r.status === 'delivered' || r.status === 'failed') continue;\n\t\tconst domain = domainOf(r.address);\n\t\tconst group = groups.get(domain);\n\t\tif (group) group.push(r.address);\n\t\telse groups.set(domain, [r.address]);\n\t}\n\treturn groups;\n}\n\n/**\n * A recipient `sendMail` would refuse — kept by a store written to by\n * other code, since `enqueue` refuses it — fails alone, as X.1.3 (bad\n * destination mailbox address syntax), so the session for its domain\n * still goes ahead for the others.\n */\nconst badAddress = (address: string): RecipientUpdate => ({\n\taddress,\n\tstatus: 'failed',\n\treply: {\n\t\tstatus: '5.1.3',\n\t\ttext: 'The address is not one SMTP can carry',\n\t},\n});\n\n/**\n * Every recipient of an item whose sender `sendMail` would refuse — kept\n * by a store written to by other code, since `enqueue` refuses it — fails\n * at once, as X.1.7 (bad sender's mailbox address syntax), rather than be\n * deferred on every attempt until `retry.giveUpAfter`.\n */\nconst badSender = (address: string): RecipientUpdate => ({\n\taddress,\n\tstatus: 'failed',\n\treply: {\n\t\tstatus: '5.1.7',\n\t\ttext: \"The sender's address is not one SMTP can carry\",\n\t},\n});\n\n/** One session for one domain's recipients: each one's outcome, whatever happened. */\nasync function attemptGroup(\n\tctx: DeliveryContext,\n\titem: QueueItem,\n\tmessage: Uint8Array,\n\tdomain: string,\n\trecipients: readonly string[],\n): Promise<RecipientUpdate[]> {\n\tconst { settings } = ctx;\n\tconst max = settings.limits.maxReplyText;\n\tconst bad = recipients.filter((address) => !isMailbox(address));\n\tconst group = recipients.filter(isMailbox);\n\tif (group.length === 0) return bad.map(badAddress);\n\ttry {\n\t\tconst options = sendOptionsOf(settings, domain, item.from, group);\n\t\tconst result = await settings.send(message, options);\n\t\treturn [...outcomesOf(result, group, max), ...bad.map(badAddress)];\n\t} catch (error) {\n\t\t// A route sendMail cannot use is the operator's to fix: said, and retried.\n\t\tif (isRouteError(error)) ctx.events.emit('error', { error, id: item.id });\n\t\tconst host = hostOf(routeOf(settings, domain));\n\t\treturn [\n\t\t\t...outcomesOfError(error, group, max, host),\n\t\t\t...bad.map(badAddress),\n\t\t];\n\t}\n}\n\n/** Tells the listeners each recipient's outcome. */\nfunction emitOutcomes(events: Events, item: QueueItem, settled: Settled): void {\n\tconst { attempts, nextAttemptAt } = settled.result;\n\tconst base = (u: RecipientUpdate) => ({\n\t\tid: item.id,\n\t\tfrom: item.from,\n\t\trecipient: u.address,\n\t\t...(u.reply ? { reply: u.reply } : {}),\n\t\tattempts,\n\t});\n\tfor (const u of settled.delivered) events.emit('delivered', base(u));\n\tfor (const u of settled.deferred) {\n\t\tevents.emit('deferred', { ...base(u), nextAttemptAt });\n\t}\n\tfor (const u of settled.failed) events.emit('failed', base(u));\n}\n\n/**\n * Delivers a claimed item: one session per recipient domain, at most\n * `perDomain` at once to each — none, and no slot taken, when its sender\n * is one `sendMail` would refuse — then the outcome recorded — which lets go\n * of the lease — then the events and the DSNs.\n */\nexport async function deliverItem(\n\tctx: DeliveryContext,\n\titem: QueueItem,\n): Promise<void> {\n\tconst { settings, store, events } = ctx;\n\tconst message = await store.readMessage(item.id);\n\tif (!message) return;\n\tconst groups = groupsOf(item);\n\tlet skipped = false;\n\t// A sender sendMail would refuse: no session, no slot, every recipient at once.\n\tconst outcomes =\n\t\titem.from !== '' && !isMailbox(item.from)\n\t\t\t? [[...groups.values()].flat().map(badSender)]\n\t\t\t: await Promise.all(\n\t\t\t\t\t[...groups].map(async ([domain, group]) => {\n\t\t\t\t\t\tconst release = await ctx.domains.acquire(domain);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (ctx.stopping()) {\n\t\t\t\t\t\t\t\tskipped = true;\n\t\t\t\t\t\t\t\treturn [];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn await attemptGroup(ctx, item, message, domain, group);\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\trelease();\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t);\n\tconst now = settings.now();\n\tconst settled = settle(item, outcomes.flat(), skipped, now, settings);\n\tconst after = await store.complete(item.id, settings.owner, settled.result);\n\tctx.recorded();\n\tif (!after && (await store.get(item.id)) === undefined) {\n\t\t// Cancelled meanwhile: what the sessions did still happened; no DSN.\n\t\temitOutcomes(events, item, settled);\n\t\treturn;\n\t}\n\tif (!after) {\n\t\tconst error = new QueueError(\n\t\t\t'LEASE_LOST',\n\t\t\t`The lease on ${item.id} was lost before its outcome was recorded; another worker will try it again`,\n\t\t);\n\t\tevents.emit('error', { error, id: item.id });\n\t\treturn;\n\t}\n\temitOutcomes(events, item, settled);\n\tawait notify(ctx, item, message, 'failed', settled.failed, now);\n\tif (settled.delayDsn) {\n\t\tawait notify(ctx, item, message, 'delayed', settled.deferred, now);\n\t}\n}\n",
15
+ "import {\n\tencodeHeaderValue,\n\tencodeQuotedPrintable,\n\tfoldHeader,\n\tformatDate,\n} from '@bumail/mime';\nimport { cleanText, replaceControls } from '../text';\nimport { returned } from './content';\nimport {\n\ttype DsnKind,\n\ttype DsnRecipient,\n\tdeliveryStatus,\n\tstatusOf,\n} from './fields';\n\nexport type { DsnKind, DsnRecipient } from './fields';\n\n/** What a DSN says, about which message, to whom. */\nexport interface DsnInput {\n\treadonly kind: DsnKind;\n\t/** This server's public name: the Reporting-MTA, and the Message-ID's domain. */\n\treadonly reportingMta: string;\n\t/** The DSN's From: the postmaster's address. */\n\treadonly from: string;\n\t/** The original's sender, to whom the DSN goes. */\n\treadonly to: string;\n\t/** When the original was enqueued. */\n\treadonly arrival: Date;\n\t/** When the DSN is written. */\n\treadonly date: Date;\n\treadonly recipients: readonly DsnRecipient[];\n\t/** With `delayed`: when the queue gives up. */\n\treadonly willRetryUntil?: Date;\n\t/** The original message, as enqueued. */\n\treadonly original: Uint8Array;\n\treadonly returnContent: 'headers' | 'full';\n\t/** The most bytes of the original returned. */\n\treadonly maxReturn: number;\n}\n\nconst encoder = new TextEncoder();\nconst strip = (text: string) =>\n\treplaceControls(text, '').replace(/[\\s<>]/g, '');\n\n/** The text a person reads first: what happened, to whom, and why (RFC 3464 §2's first part). */\nfunction humanText(input: DsnInput): string {\n\tconst failed = input.kind === 'failed';\n\tconst lines = failed\n\t\t? [\n\t\t\t\t`This is the mail system at ${input.reportingMta}.`,\n\t\t\t\t'',\n\t\t\t\t'Your message could not be delivered to the recipients below.',\n\t\t\t\t'This is a permanent failure: the message will not be retried.',\n\t\t\t]\n\t\t: [\n\t\t\t\t`This is the mail system at ${input.reportingMta}.`,\n\t\t\t\t'',\n\t\t\t\t'Your message has not been delivered yet to the recipients below.',\n\t\t\t\t'This is a warning only: the message is still being retried',\n\t\t\t\t...(input.willRetryUntil\n\t\t\t\t\t? [`until ${formatDate(input.willRetryUntil)}.`]\n\t\t\t\t\t: []),\n\t\t\t\t'You do not need to send it again.',\n\t\t\t];\n\tlines.push('');\n\tfor (const r of input.recipients) {\n\t\tconst said = r.reply\n\t\t\t? `${r.reply.code ?? ''} ${cleanText(r.reply.text, 900)}`.trim()\n\t\t\t: statusOf(input.kind);\n\t\tconst why =\n\t\t\tr.reply?.status === '4.4.7'\n\t\t\t\t? `delivery time expired, still failing: ${said}`\n\t\t\t\t: said;\n\t\tlines.push(`<${cleanText(r.address, 254)}>: ${why}`);\n\t}\n\treturn `${lines.join('\\r\\n')}\\r\\n`;\n}\n\n/** The header fields of the DSN, every value cleaned and folded. */\nfunction headerFields(input: DsnInput, boundary: string): string[] {\n\tconst subject =\n\t\tinput.kind === 'failed'\n\t\t\t? 'Undelivered Mail Returned to Sender'\n\t\t\t: 'Delayed Mail (still being retried)';\n\tconst domain = strip(input.reportingMta);\n\treturn [\n\t\tfoldHeader('Date', formatDate(input.date)),\n\t\tfoldHeader('From', `Mail Delivery System <${strip(input.from)}>`),\n\t\tfoldHeader('To', `<${strip(input.to)}>`),\n\t\tfoldHeader('Subject', encodeHeaderValue(subject)),\n\t\tfoldHeader('Message-ID', `<${crypto.randomUUID()}@${domain}>`),\n\t\t// RFC 3834 §5: an automatic answer, which no one answers automatically.\n\t\tfoldHeader('Auto-Submitted', 'auto-replied'),\n\t\tfoldHeader('MIME-Version', '1.0'),\n\t\tfoldHeader(\n\t\t\t'Content-Type',\n\t\t\t`multipart/report; report-type=delivery-status; boundary=\"${boundary}\"`,\n\t\t),\n\t];\n}\n\nconst concat = (parts: readonly Uint8Array[]): Uint8Array => {\n\tconst out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n\tlet at = 0;\n\tfor (const part of parts) {\n\t\tout.set(part, at);\n\t\tat += part.length;\n\t}\n\treturn out;\n};\n\n/** A boundary that occurs nowhere in what it separates. */\nfunction boundaryFor(content: Uint8Array): string {\n\tconst text = new TextDecoder('latin1').decode(content);\n\tfor (;;) {\n\t\tconst boundary = `=_dsn_${crypto.randomUUID()}`;\n\t\tif (!text.includes(boundary)) return boundary;\n\t}\n}\n\n/**\n * A delivery status notification (RFC 3464): a `multipart/report`\n * (RFC 6522) of `report-type=delivery-status` holding the text a person\n * reads, the `message/delivery-status` fields a program reads, and the\n * original's header fields (or the whole original, when asked and small\n * enough), bounded by `maxReturn`. Nothing from the remote server or the\n * envelope reaches a header field raw: control characters, CR and LF are\n * taken out first.\n */\nexport function buildDsn(input: DsnInput): Uint8Array {\n\tconst original = returned(\n\t\tinput.original,\n\t\tinput.returnContent,\n\t\tinput.maxReturn,\n\t);\n\tconst boundary = boundaryFor(original.body);\n\tconst text = encodeQuotedPrintable(humanText(input));\n\tconst status = deliveryStatus({\n\t\tkind: input.kind,\n\t\treportingMta: input.reportingMta,\n\t\tarrival: input.arrival,\n\t\trecipients: input.recipients,\n\t\t...(input.willRetryUntil ? { willRetryUntil: input.willRetryUntil } : {}),\n\t});\n\tconst head = [\n\t\t...headerFields(input, boundary),\n\t\t'',\n\t\t'This is a MIME-formatted delivery status notification.',\n\t\t'',\n\t\t`--${boundary}`,\n\t\t'Content-Type: text/plain; charset=utf-8',\n\t\t'Content-Transfer-Encoding: quoted-printable',\n\t\t'',\n\t\ttext,\n\t\t`--${boundary}`,\n\t\t'Content-Type: message/delivery-status',\n\t\t'',\n\t\tstatus,\n\t\t`--${boundary}`,\n\t\t`Content-Type: ${original.type}`,\n\t\t...(original.eightBit ? ['Content-Transfer-Encoding: 8bit'] : []),\n\t\t'',\n\t\t'',\n\t].join('\\r\\n');\n\treturn concat([\n\t\tencoder.encode(head),\n\t\toriginal.body,\n\t\tencoder.encode(`\\r\\n--${boundary}--\\r\\n`),\n\t]);\n}\n",
16
+ "/** The part of a DSN that returns the original message (RFC 3464 §2, RFC 6522 §3). */\n\nconst CR = 13;\nconst LF = 10;\n\n/** RFC 5322 §2.1.1: a line is at most 998 characters, its CRLF aside. */\nexport const MAX_LINE = 998;\n\nconst isContinuation = (byte: number | undefined) =>\n\tbyte !== undefined && byte >= 0x80 && byte < 0xc0;\n\n/**\n * Every bare CR or LF as CRLF, and every line cut at 998 bytes, never in\n * the middle of a UTF-8 character: a DSN is sent as lines, whatever the\n * original held, and a longer one would get the DSN itself refused.\n */\nfunction crlf(bytes: Uint8Array): Uint8Array {\n\tconst out: number[] = [];\n\tlet column = 0;\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\tconst byte = bytes[i] as number;\n\t\tif (byte === CR || byte === LF) {\n\t\t\tout.push(CR, LF);\n\t\t\tcolumn = 0;\n\t\t\tif (byte === CR && bytes[i + 1] === LF) i++;\n\t\t} else if (column < MAX_LINE) {\n\t\t\tout.push(byte);\n\t\t\tcolumn++;\n\t\t} else if (column === MAX_LINE) {\n\t\t\t// The first byte cut: drop a character it would leave half written.\n\t\t\tif (isContinuation(byte)) {\n\t\t\t\twhile (isContinuation(out.at(-1))) {\n\t\t\t\t\tout.pop();\n\t\t\t\t}\n\t\t\t\tif ((out.at(-1) ?? 0) >= 0xc0) out.pop();\n\t\t\t}\n\t\t\tcolumn++;\n\t\t}\n\t}\n\treturn Uint8Array.from(out);\n}\n\n/** Where the header block ends: past the blank line, or the whole message when it has none. */\nfunction headerEnd(bytes: Uint8Array): number {\n\tfor (let i = 0; i + 3 < bytes.length; i++) {\n\t\tif (\n\t\t\tbytes[i] === CR &&\n\t\t\tbytes[i + 1] === LF &&\n\t\t\tbytes[i + 2] === CR &&\n\t\t\tbytes[i + 3] === LF\n\t\t) {\n\t\t\treturn i + 2;\n\t\t}\n\t}\n\treturn bytes.length;\n}\n\n/** The first `max` bytes at most, cut after the last whole line. */\nfunction wholeLines(bytes: Uint8Array, max: number): Uint8Array {\n\tif (bytes.length <= max) return bytes;\n\tconst cut = bytes.subarray(0, max).lastIndexOf(LF);\n\treturn bytes.subarray(0, cut + 1);\n}\n\nexport interface Returned {\n\t/** `text/rfc822-headers` or `message/rfc822`. */\n\treadonly type: string;\n\t/** Lines ending in CRLF, the last one included. */\n\treadonly body: Uint8Array;\n\t/** It holds a byte past ASCII: the part says `8bit`. */\n\treadonly eightBit: boolean;\n}\n\n/**\n * The original as a DSN returns it: the whole message when asked and it\n * fits `max` bytes, else its header fields, cut after the last whole line\n * that fits. Never more than `max` bytes.\n */\nexport function returned(\n\toriginal: Uint8Array,\n\tmode: 'headers' | 'full',\n\tmax: number,\n): Returned {\n\tconst message = crlf(original.subarray(0, max * 2 + 2));\n\tconst whole = original.length <= max && message.length <= max;\n\tconst body =\n\t\twhole && mode === 'full'\n\t\t\t? message\n\t\t\t: wholeLines(message.subarray(0, headerEnd(message)), max);\n\treturn {\n\t\ttype: whole && mode === 'full' ? 'message/rfc822' : 'text/rfc822-headers',\n\t\tbody,\n\t\teightBit: body.some((byte) => byte > 0x7f),\n\t};\n}\n",
17
+ "import { foldHeader, formatDate } from '@bumail/mime';\nimport type { Diagnostic } from '../contract/types';\nimport { asciiText, replaceControls } from '../text';\n\n/** One recipient a DSN reports on. */\nexport interface DsnRecipient {\n\treadonly address: string;\n\treadonly reply?: Diagnostic;\n\t/** When it was last tried. */\n\treadonly lastAttempt: Date;\n}\n\nexport type DsnKind = 'delayed' | 'failed';\n\n/** What a delivery-status part reports: who reports, on what, and each recipient. */\nexport interface StatusReport {\n\treadonly kind: DsnKind;\n\t/** This server's name. */\n\treadonly reportingMta: string;\n\t/** When the message was enqueued. */\n\treadonly arrival: Date;\n\treadonly recipients: readonly DsnRecipient[];\n\t/** With `delayed`: when the queue gives up. */\n\treadonly willRetryUntil?: Date;\n}\n\n/** Control characters out, CR and LF first: nothing from outside starts a field of its own. */\nconst strip = (text: string) => replaceControls(text, '');\n\n/** The longest escaped address: with its field name, within 998 characters a line. */\nconst MAX_ESCAPED = 900;\n\n/**\n * An address as a delivery-status field types it: `rfc822; addr` when it\n * is ASCII; otherwise `utf-8;` with each non-ASCII character as\n * `\\x{HEX}` (RFC 6533 §3, utf-8-addr-xtext), so the part stays 7-bit,\n * cut at 900 characters so it always fits a header line.\n */\nexport function typedAddress(address: string): string {\n\tconst clean = strip(address).replace(/[\\s\\\\]/g, '');\n\tif (/^[\\x21-\\x7e]*$/.test(clean)) return `rfc822; ${clean}`;\n\tlet escaped = '';\n\tfor (const c of clean) {\n\t\tconst piece = /[\\x21-\\x7e]/.test(c)\n\t\t\t? c\n\t\t\t: `\\\\x{${(c.codePointAt(0) ?? 0).toString(16).toUpperCase()}}`;\n\t\t// One word, so it must fit a line (RFC 5322 §2.1.1): cut, never lost.\n\t\tif (escaped.length + piece.length > MAX_ESCAPED) break;\n\t\tescaped += piece;\n\t}\n\treturn `utf-8; ${escaped}`;\n}\n\n/** A host name as `dns; host`, or nothing when it is not one. */\nconst remoteMta = (host: string | undefined) =>\n\thost && /^[A-Za-z0-9.:[\\]-]{1,255}$/.test(host) ? `dns; ${host}` : undefined;\n\n/**\n * The status (RFC 3463) of a recipient: the reply's enhanced code; else\n * its class from the reply code; else, with nothing at all, the kind's.\n */\nexport function statusOf(kind: DsnKind, reply?: Diagnostic): string {\n\tif (reply?.status) return reply.status;\n\tif (reply?.code !== undefined) {\n\t\treturn reply.code >= 500 ? '5.0.0' : '4.0.0';\n\t}\n\treturn kind === 'failed' ? '5.0.0' : '4.0.0';\n}\n\n/** The fields of one recipient (RFC 3464 §2.3), folded, no line from outside. */\nfunction recipientFields(\n\treport: StatusReport,\n\trecipient: DsnRecipient,\n): string[] {\n\tconst { reply } = recipient;\n\tconst fields: [string, string][] = [\n\t\t['Final-Recipient', typedAddress(recipient.address)],\n\t\t['Action', report.kind],\n\t\t['Status', statusOf(report.kind, reply)],\n\t];\n\tconst remote = remoteMta(reply?.host);\n\tif (remote) fields.push(['Remote-MTA', remote]);\n\tif (reply) {\n\t\tconst text = asciiText(reply.text, 900);\n\t\tfields.push(\n\t\t\treply.code === undefined\n\t\t\t\t? ['Diagnostic-Code', `X-Bumail; ${text}`]\n\t\t\t\t: ['Diagnostic-Code', `smtp; ${reply.code} ${text}`],\n\t\t);\n\t}\n\tfields.push(['Last-Attempt-Date', formatDate(recipient.lastAttempt)]);\n\tif (report.kind === 'delayed' && report.willRetryUntil) {\n\t\tfields.push(['Will-Retry-Until', formatDate(report.willRetryUntil)]);\n\t}\n\treturn fields.map(([name, value]) => foldHeader(name, value));\n}\n\n/**\n * The body of a `message/delivery-status` part (RFC 3464 §2.1): the\n * per-message fields, then each recipient's, a blank line between, CRLF.\n */\nexport function deliveryStatus(report: StatusReport): string {\n\tconst message = [\n\t\tfoldHeader('Reporting-MTA', `dns; ${strip(report.reportingMta)}`),\n\t\tfoldHeader('Arrival-Date', formatDate(report.arrival)),\n\t].join('\\r\\n');\n\tconst blocks = report.recipients.map((r) =>\n\t\trecipientFields(report, r).join('\\r\\n'),\n\t);\n\treturn `${[message, ...blocks].join('\\r\\n\\r\\n')}\\r\\n`;\n}\n",
18
+ "import type { RetrySettings } from './settings';\n\n/**\n * The wait after the `attempts`-th attempt failed for now: `first`, then\n * `factor` times the wait before, at most `max`, plus up to `jitter` of\n * itself — never less, so RFC 5321 §4.5.4.1's 30 minutes stay a floor.\n */\nexport function retryDelay(\n\tattempts: number,\n\tretry: RetrySettings,\n\trandom: () => number,\n): number {\n\tconst exponent = Math.max(0, attempts - 1);\n\tconst delay = Math.min(retry.first * retry.factor ** exponent, retry.max);\n\treturn delay + delay * retry.jitter * Math.min(1, Math.max(0, random()));\n}\n\n/** When a message's deferred recipients give up: `giveUpAfter` after it was enqueued. */\nexport const giveUpAt = (createdAt: number, retry: RetrySettings) =>\n\tcreatedAt + retry.giveUpAfter;\n\n/**\n * The next attempt after the `attempts`-th, at `now`: the back-off, but no\n * later than the moment of giving up, so the last try falls on it.\n * `undefined` when that moment has come: what is still deferred fails.\n */\nexport function nextAttemptAt(\n\tcreatedAt: number,\n\tnow: number,\n\tattempts: number,\n\tretry: RetrySettings,\n\trandom: () => number,\n): number | undefined {\n\tconst end = giveUpAt(createdAt, retry);\n\tif (now >= end) return undefined;\n\treturn Math.min(now + retryDelay(attempts, retry, random), end);\n}\n",
19
+ "import type { QueueStore } from '../contract/queue-store';\nimport type { QueueItem, RecipientUpdate } from '../contract/types';\nimport { buildDsn, type DsnKind } from '../dsn/build';\nimport type { Events } from './events';\nimport { giveUpAt } from './retry';\nimport type { Settings } from './settings';\n\nexport interface NotifyContext {\n\treadonly settings: Settings;\n\treadonly store: QueueStore;\n\treadonly events: Events;\n}\n\n/**\n * Enqueues a DSN (RFC 3464) back to the item's sender for these\n * recipients, from the null sender, so it never causes one of its own.\n * Nothing for an item from the null sender (RFC 5321 §4.5.5, RFC 3464\n * §2: a DSN is never sent about a DSN). It bypasses `maxItems`: a full\n * queue loses no bounce. A failure goes to the `error` event.\n */\nexport async function notify(\n\tctx: NotifyContext,\n\titem: QueueItem,\n\tmessage: Uint8Array,\n\tkind: DsnKind,\n\trecipients: readonly RecipientUpdate[],\n\tnow: number,\n): Promise<void> {\n\tif (item.from === '' || recipients.length === 0) return;\n\tconst { settings, store, events } = ctx;\n\ttry {\n\t\tconst lastAttempt = new Date(now);\n\t\tconst dsn = buildDsn({\n\t\t\tkind,\n\t\t\treportingMta: settings.hostname,\n\t\t\tfrom: settings.dsn.from,\n\t\t\tto: item.from,\n\t\t\tarrival: new Date(item.createdAt),\n\t\t\tdate: lastAttempt,\n\t\t\trecipients: recipients.map((r) => ({\n\t\t\t\taddress: r.address,\n\t\t\t\t...(r.reply ? { reply: r.reply } : {}),\n\t\t\t\tlastAttempt,\n\t\t\t})),\n\t\t\t...(kind === 'delayed'\n\t\t\t\t? { willRetryUntil: new Date(giveUpAt(item.createdAt, settings.retry)) }\n\t\t\t\t: {}),\n\t\t\toriginal: message,\n\t\t\treturnContent: settings.dsn.returnContent,\n\t\t\tmaxReturn: settings.limits.maxDsnReturn,\n\t\t});\n\t\tconst added = await store.add({\n\t\t\tfrom: '',\n\t\t\tto: [item.from],\n\t\t\tmessage: dsn,\n\t\t\tcreatedAt: now,\n\t\t});\n\t\tevents.emit('dsn', {\n\t\t\tkind,\n\t\t\tid: added.id,\n\t\t\tof: item.id,\n\t\t\tto: item.from,\n\t\t\trecipients: recipients.map((r) => r.address),\n\t\t});\n\t} catch (error) {\n\t\tevents.emit('error', { error, id: item.id });\n\t}\n}\n",
20
+ "import type {\n\tReply,\n\tSendMailResult,\n\tSmtpError,\n\tSmtpErrorCode,\n} from '@bumail/smtp/client';\nimport type { Diagnostic, RecipientUpdate } from '../contract/types';\nimport { cleanText } from '../text';\n\n/**\n * An `SmtpError`, read by its `name`: a second copy of `@bumail/smtp` (a\n * different version installed for the app) throws errors of another\n * class, which `instanceof` would take for unknown ones.\n */\nexport const isSmtpError = (error: unknown): error is SmtpError =>\n\terror instanceof Error &&\n\terror.name === 'SmtpError' &&\n\ttypeof (error as { code?: unknown }).code === 'string';\n\n/**\n * `sendMail` refused its options: the route is misconfigured (a smarthost\n * it cannot use, a bad timeout), not the recipient. Retried, never bounced\n * at once: fixing the configuration and restarting delivers the message.\n */\nexport const isRouteError = (error: unknown): boolean =>\n\tisSmtpError(error) && error.code === 'INVALID_OPTION';\n\n/** An enhanced status code, `x.y.z` (RFC 3463 §2). */\nconst STATUS = /^[245]\\.\\d{1,3}\\.\\d{1,3}$/;\n\n/** What a reply says, bounded and cleaned. */\nexport function diagnosticOf(\n\treply: Reply,\n\tmax: number,\n\thost?: string,\n): Diagnostic {\n\tconst text =\n\t\ttypeof reply.text === 'string' ? reply.text : reply.text.join(' ');\n\treturn {\n\t\tcode: reply.code,\n\t\t...(reply.status && STATUS.test(reply.status)\n\t\t\t? { status: reply.status }\n\t\t\t: {}),\n\t\ttext: cleanText(text, max),\n\t\t...(host ? { host: cleanText(host, 255) } : {}),\n\t};\n}\n\n/**\n * The status code an error with no reply stands for (RFC 3463 §3): a null\n * MX is X.1.10 (RFC 7505 §4.2), a domain that cannot be found X.1.2, a\n * host that does not answer X.4.1, a connection lost or timed out X.4.2,\n * TLS X.7.0 (security).\n */\nconst ERROR_STATUS: Partial<Record<SmtpErrorCode, string>> = {\n\tNULL_MX: '1.10',\n\tDNS_FAILED: '1.2',\n\tCONNECTION_FAILED: '4.1',\n\tCONNECTION_LOST: '4.2',\n\tTIMEOUT: '4.2',\n\tTLS_UNAVAILABLE: '7.10',\n\tTLS_FAILED: '7.0',\n\tAUTH_UNAVAILABLE: '7.0',\n\tINVALID_OPTION: '3.5',\n};\n\n/** A failure that never got a reply: an error of the network, the DNS, TLS, or anything else. */\nfunction diagnosticOfError(\n\terror: unknown,\n\ttemporary: boolean,\n\tmax: number,\n\thost?: string,\n): Diagnostic {\n\tconst text = error instanceof Error ? error.message : String(error);\n\tconst detail = isSmtpError(error)\n\t\t? (ERROR_STATUS[error.code] ?? '0.0')\n\t\t: '0.0';\n\treturn {\n\t\tstatus: `${temporary ? 4 : 5}.${detail}`,\n\t\ttext: cleanText(text, max),\n\t\t...(host ? { host } : {}),\n\t};\n}\n\n/** Each recipient of a delivery `sendMail` resolved: taken, or refused one by one. */\nexport function outcomesOf(\n\tresult: SendMailResult,\n\tgroup: readonly string[],\n\tmax: number,\n): RecipientUpdate[] {\n\tconst host = result.host;\n\tconst updates = new Map<string, RecipientUpdate>();\n\tfor (const { recipient } of result.accepted) {\n\t\tupdates.set(recipient, {\n\t\t\taddress: recipient,\n\t\t\tstatus: 'delivered',\n\t\t\treply: diagnosticOf(result.reply, max, host),\n\t\t});\n\t}\n\tfor (const { recipient, reply } of result.rejected) {\n\t\tupdates.set(recipient, {\n\t\t\taddress: recipient,\n\t\t\tstatus: reply.code >= 500 ? 'failed' : 'deferred',\n\t\t\treply: diagnosticOf(reply, max, host),\n\t\t});\n\t}\n\t// sendMail names every recipient it was given; a fake may not.\n\treturn group.map(\n\t\t(address) =>\n\t\t\tupdates.get(address) ?? {\n\t\t\t\taddress,\n\t\t\t\tstatus: 'deferred',\n\t\t\t\treply: { text: 'The delivery said nothing of this recipient', host },\n\t\t\t},\n\t);\n}\n\n/**\n * Each recipient of a delivery `sendMail` rejected: by its own reply when\n * the server refused every one, else all alike — deferred when the error\n * is temporary (a 4xx, the network, a timeout) or the route's own\n * (`INVALID_OPTION`, X.3.5), failed otherwise.\n */\nexport function outcomesOfError(\n\terror: unknown,\n\tgroup: readonly string[],\n\tmax: number,\n\thost?: string,\n): RecipientUpdate[] {\n\tconst rejected = new Map(\n\t\tisSmtpError(error)\n\t\t\t? (error.rejected ?? []).map((r) => [r.recipient, r.reply])\n\t\t\t: [],\n\t);\n\tconst temporary =\n\t\t!isSmtpError(error) || error.temporary || isRouteError(error);\n\treturn group.map((address): RecipientUpdate => {\n\t\tconst own = rejected.get(address);\n\t\tif (own) {\n\t\t\treturn {\n\t\t\t\taddress,\n\t\t\t\tstatus: own.code >= 500 ? 'failed' : 'deferred',\n\t\t\t\treply: diagnosticOf(own, max, host),\n\t\t\t};\n\t\t}\n\t\tconst reply =\n\t\t\tisSmtpError(error) && error.reply\n\t\t\t\t? diagnosticOf(error.reply, max, host)\n\t\t\t\t: diagnosticOfError(error, temporary, max, host);\n\t\treturn { address, status: temporary ? 'deferred' : 'failed', reply };\n\t});\n}\n",
21
+ "import type { SendMailOptions } from '@bumail/smtp/client';\nimport type { Route } from './options';\nimport type { Settings } from './settings';\n\n/** The route for a recipient domain: its own, else the default. */\nexport function routeOf(settings: Settings, domain: string): Route {\n\treturn settings.routes.get(domain) ?? settings.options.route ?? 'mx';\n}\n\n/** The host an attempt goes to, as far as the route says: the smarthost, or nothing for MX. */\nexport function hostOf(route: Route): string | undefined {\n\treturn route === 'mx' ? undefined : route.host;\n}\n\n/** What `sendMail` takes to send one domain's recipients of a message. */\nexport function sendOptionsOf(\n\tsettings: Settings,\n\tdomain: string,\n\tfrom: string,\n\tto: readonly string[],\n): SendMailOptions {\n\tconst { options, hostname } = settings;\n\tconst common = {\n\t\tfrom,\n\t\tto,\n\t\thelo: hostname,\n\t\t...(options.timeouts ? { timeouts: options.timeouts } : {}),\n\t\t...(options.deadline !== undefined ? { deadline: options.deadline } : {}),\n\t};\n\tconst route = routeOf(settings, domain);\n\tif (route === 'mx') {\n\t\tconst resolver = options.resolver;\n\t\tif (!resolver) throw new Error('unreachable: settings check the resolver');\n\t\treturn {\n\t\t\t...common,\n\t\t\tdomain,\n\t\t\tresolver,\n\t\t\t...(options.mxPort !== undefined ? { port: options.mxPort } : {}),\n\t\t\t...(options.mxTls ? { tls: options.mxTls } : {}),\n\t\t};\n\t}\n\treturn {\n\t\t...common,\n\t\thost: route.host,\n\t\t...(route.port !== undefined ? { port: route.port } : {}),\n\t\t...(route.secure !== undefined ? { secure: route.secure } : {}),\n\t\t...(route.tls ? { tls: route.tls } : {}),\n\t\t...(route.auth ? { auth: route.auth } : {}),\n\t\t...(route.ca ? { ca: route.ca } : {}),\n\t};\n}\n",
22
+ "import type {\n\tAttemptResult,\n\tQueueItem,\n\tRecipientUpdate,\n} from '../contract/types';\nimport { nextAttemptAt } from './retry';\nimport type { Settings } from './settings';\n\n/** An attempt's outcomes, sorted, and what to record and send for them. */\nexport interface Settled {\n\treadonly result: AttemptResult;\n\treadonly delivered: readonly RecipientUpdate[];\n\t/** Failed in this attempt: a 5xx, or given up. */\n\treadonly failed: readonly RecipientUpdate[];\n\t/** Still deferred, to try again at `result.nextAttemptAt`. */\n\treadonly deferred: readonly RecipientUpdate[];\n\t/** A \"delayed\" DSN is due for the deferred recipients. */\n\treadonly delayDsn: boolean;\n}\n\n/**\n * A deferred recipient past the moment of giving up: failed, as X.4.7\n * (RFC 3463 §3.5, delivery time expired), the remote reply's code and text\n * kept as they were said.\n */\nfunction expired(update: RecipientUpdate): RecipientUpdate {\n\treturn {\n\t\taddress: update.address,\n\t\tstatus: 'failed',\n\t\treply: { text: '', ...update.reply, status: '4.4.7' },\n\t};\n}\n\n/**\n * What an attempt comes to: the count, the next attempt (RFC 5321\n * §4.5.4.1's back-off, or now when some recipients were left out because\n * the worker is stopping), the deferred recipients that gave up, and\n * whether the \"delayed\" DSN is due — once, for a sender that is not null.\n */\nexport function settle(\n\titem: QueueItem,\n\tupdates: readonly RecipientUpdate[],\n\tskipped: boolean,\n\tnow: number,\n\tsettings: Settings,\n): Settled {\n\tconst attempts = item.attempts + (updates.length > 0 ? 1 : 0);\n\tconst next = nextAttemptAt(\n\t\titem.createdAt,\n\t\tnow,\n\t\tattempts,\n\t\tsettings.retry,\n\t\tsettings.random,\n\t);\n\tconst all = updates.map((u) =>\n\t\tu.status === 'deferred' && next === undefined ? expired(u) : u,\n\t);\n\tconst deferred = all.filter((u) => u.status === 'deferred');\n\tconst { delayAfter } = settings.dsn;\n\tconst delayDsn =\n\t\t!item.delayNotified &&\n\t\titem.from !== '' &&\n\t\tdelayAfter !== false &&\n\t\tdeferred.length > 0 &&\n\t\tnow - item.createdAt >= delayAfter;\n\treturn {\n\t\tresult: {\n\t\t\tnow,\n\t\t\trecipients: all,\n\t\t\t// Left out by a stop with nothing deferred: due at once. Otherwise the\n\t\t\t// back-off holds for the whole item, the left-out domains included.\n\t\t\tnextAttemptAt:\n\t\t\t\tnext === undefined || (skipped && deferred.length === 0) ? now : next,\n\t\t\tattempts,\n\t\t\tdelayNotified: item.delayNotified || delayDsn,\n\t\t},\n\t\tdelivered: all.filter((u) => u.status === 'delivered'),\n\t\tfailed: all.filter((u) => u.status === 'failed'),\n\t\tdeferred,\n\t\tdelayDsn,\n\t};\n}\n",
23
+ "/** A count of slots: who asks past it waits, first come first served. */\nexport class Limiter {\n\treadonly #size: number;\n\t#used = 0;\n\treadonly #waiting: (() => void)[] = [];\n\n\tconstructor(size: number) {\n\t\tthis.#size = size;\n\t}\n\n\t/** A slot, once one is free; call what it resolves to, once, to give it back. */\n\tasync acquire(): Promise<() => void> {\n\t\tif (this.#used >= this.#size) {\n\t\t\tawait new Promise<void>((resolve) => this.#waiting.push(resolve));\n\t\t} else {\n\t\t\tthis.#used++;\n\t\t}\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tconst next = this.#waiting.shift();\n\t\t\t// The slot passes to the next in line without being freed in between.\n\t\t\tif (next) next();\n\t\t\telse this.#used--;\n\t\t};\n\t}\n}\n\n/** One `Limiter` per key, made when first asked for and dropped once idle. */\nexport class KeyedLimiter {\n\treadonly #size: number;\n\treadonly #limiters = new Map<string, { limiter: Limiter; users: number }>();\n\n\tconstructor(size: number) {\n\t\tthis.#size = size;\n\t}\n\n\tasync acquire(key: string): Promise<() => void> {\n\t\tlet entry = this.#limiters.get(key);\n\t\tif (!entry) {\n\t\t\tentry = { limiter: new Limiter(this.#size), users: 0 };\n\t\t\tthis.#limiters.set(key, entry);\n\t\t}\n\t\tentry.users++;\n\t\tconst release = await entry.limiter.acquire();\n\t\tconst held = entry;\n\t\treturn () => {\n\t\t\trelease();\n\t\t\tif (--held.users === 0) this.#limiters.delete(key);\n\t\t};\n\t}\n}\n",
24
+ "import type { QueueItem } from '../contract/types';\nimport { QueueError } from '../errors';\nimport { deliverItem } from './deliver';\nimport { KeyedLimiter, Limiter } from './limiter';\nimport type { NotifyContext } from './notify';\n\n/**\n * Claims due items and delivers them, at most `concurrency` at once,\n * renewing each lease while its item is delivered. `start()` runs passes\n * every `pollInterval`, or at once when woken; `stop()` lets every\n * delivery under way finish and gives back what it had not started.\n */\nexport class Worker {\n\treadonly #ctx: NotifyContext;\n\treadonly #slots: Limiter;\n\treadonly #domains: KeyedLimiter;\n\treadonly #inFlight = new Set<Promise<void>>();\n\t#stopping = false;\n\t/** `start()` was called while a `stop()` was under way: start again once it ends. */\n\t#restart = false;\n\t#loop: Promise<void> | undefined;\n\t#wake: (() => void) | undefined;\n\t/** A wake came while no sleep was under way: the next sleep is skipped. */\n\t#woken = false;\n\n\tconstructor(ctx: NotifyContext) {\n\t\tthis.#ctx = ctx;\n\t\tthis.#slots = new Limiter(ctx.settings.concurrency);\n\t\tthis.#domains = new KeyedLimiter(ctx.settings.perDomain);\n\t}\n\n\t/**\n\t * Renews the lease every third of it until the outcome is recorded. A\n\t * renewal that finds the lease taken says so once, and stops; one that\n\t * fails (the store busy, unreachable) says so, and the next one tries\n\t * again: the lease may still be held.\n\t */\n\t#renewing(item: QueueItem): () => void {\n\t\tconst { settings, store, events } = this.#ctx;\n\t\tlet done = false;\n\t\tconst stop = () => {\n\t\t\tdone = true;\n\t\t\tclearInterval(timer);\n\t\t};\n\t\tconst timer = setInterval(() => {\n\t\t\tconst expiresAt = settings.now() + settings.leaseMs;\n\t\t\tstore.renew(item.id, settings.owner, expiresAt).then(\n\t\t\t\t(held) => {\n\t\t\t\t\tif (held || done) return;\n\t\t\t\t\tstop();\n\t\t\t\t\tconst error = new QueueError(\n\t\t\t\t\t\t'LEASE_LOST',\n\t\t\t\t\t\t`The lease on ${item.id} was lost while it was delivered`,\n\t\t\t\t\t);\n\t\t\t\t\tevents.emit('error', { error, id: item.id });\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tif (!done) events.emit('error', { error, id: item.id });\n\t\t\t\t},\n\t\t\t);\n\t\t}, settings.leaseMs / 3);\n\t\ttimer.unref?.();\n\t\treturn stop;\n\t}\n\n\tasync #deliver(item: QueueItem): Promise<void> {\n\t\tconst stopRenewing = this.#renewing(item);\n\t\ttry {\n\t\t\tawait deliverItem(\n\t\t\t\t{\n\t\t\t\t\t...this.#ctx,\n\t\t\t\t\tdomains: this.#domains,\n\t\t\t\t\tstopping: () => this.#stopping,\n\t\t\t\t\trecorded: stopRenewing,\n\t\t\t\t},\n\t\t\t\titem,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.#ctx.events.emit('error', { error, id: item.id });\n\t\t} finally {\n\t\t\tstopRenewing();\n\t\t}\n\t}\n\n\t/** The next due item, or `undefined` when nothing is, or the worker is stopping. */\n\t#claim(): Promise<QueueItem | undefined> {\n\t\tconst { settings, store } = this.#ctx;\n\t\tif (this.#stopping) return Promise.resolve(undefined);\n\t\treturn store.claim({\n\t\t\towner: settings.owner,\n\t\t\tnow: settings.now(),\n\t\t\tleaseMs: settings.leaseMs,\n\t\t});\n\t}\n\n\t/**\n\t * One pass: claims and delivers every item due, `concurrency` at a time,\n\t * claiming again as each one ends — so a DSN enqueued meanwhile goes in\n\t * the same pass. Resolves once all are done, with how many it claimed.\n\t */\n\tasync deliverDue(): Promise<number> {\n\t\tconst mine = new Set<Promise<void>>();\n\t\tlet claimed = 0;\n\t\twhile (!this.#stopping) {\n\t\t\tconst release = await this.#slots.acquire();\n\t\t\tlet item: QueueItem | undefined;\n\t\t\ttry {\n\t\t\t\titem = await this.#claim();\n\t\t\t} catch (error) {\n\t\t\t\trelease();\n\t\t\t\tawait Promise.all(mine);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (!item) {\n\t\t\t\trelease();\n\t\t\t\tif (mine.size === 0) break;\n\t\t\t\tawait Promise.race(mine);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tclaimed++;\n\t\t\tconst delivery: Promise<void> = this.#deliver(item).finally(() => {\n\t\t\t\trelease();\n\t\t\t\tmine.delete(delivery);\n\t\t\t\tthis.#inFlight.delete(delivery);\n\t\t\t});\n\t\t\tmine.add(delivery);\n\t\t\tthis.#inFlight.add(delivery);\n\t\t}\n\t\tawait Promise.all(mine);\n\t\treturn claimed;\n\t}\n\n\t/** Wakes a sleeping `start()` loop, or spares it its next sleep: something was enqueued. */\n\twake(): void {\n\t\tif (this.#wake) this.#wake();\n\t\telse this.#woken = true;\n\t}\n\n\tstart(): void {\n\t\tif (this.#stopping) {\n\t\t\tthis.#restart = true;\n\t\t\treturn;\n\t\t}\n\t\tif (this.#loop) return;\n\t\tthis.#loop = this.#run();\n\t}\n\n\tasync #sleep(): Promise<void> {\n\t\tif (this.#woken) {\n\t\t\tthis.#woken = false;\n\t\t\treturn;\n\t\t}\n\t\tawait new Promise<void>((resolve) => {\n\t\t\tconst timer = setTimeout(resolve, this.#ctx.settings.pollInterval);\n\t\t\tthis.#wake = () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t};\n\t\t});\n\t\tthis.#wake = undefined;\n\t}\n\n\tasync #run(): Promise<void> {\n\t\twhile (!this.#stopping) {\n\t\t\tthis.#woken = false;\n\t\t\ttry {\n\t\t\t\tawait this.deliverDue();\n\t\t\t} catch (error) {\n\t\t\t\tthis.#ctx.events.emit('error', { error });\n\t\t\t}\n\t\t\tif (this.#stopping) break;\n\t\t\tawait this.#sleep();\n\t\t}\n\t}\n\n\t/**\n\t * Claims nothing more, lets every delivery under way end, and gives back\n\t * what was claimed but not started, due at once for the next worker. A\n\t * `start()` called meanwhile starts again once this ends.\n\t */\n\tasync stop(): Promise<void> {\n\t\tthis.#restart = false;\n\t\tthis.#stopping = true;\n\t\tthis.#wake?.();\n\t\tawait this.#loop;\n\t\tawait Promise.all(this.#inFlight);\n\t\tthis.#loop = undefined;\n\t\tthis.#stopping = false;\n\t\tif (this.#restart) {\n\t\t\tthis.#restart = false;\n\t\t\tthis.start();\n\t\t}\n\t}\n}\n",
25
+ "import type { QueueItem, QueueListOptions } from '../contract/types';\nimport {\n\tcheckEnvelope,\n\tcheckLineEnds,\n\ttype MessageSource,\n\ttype QueueEnvelope,\n\treadMessage,\n} from './envelope';\nimport { Events, type QueueEvents, type QueueListener } from './events';\nimport type { QueueOptions } from './options';\nimport { settingsOf } from './settings';\nimport { Worker } from './worker';\n\n/** The outbound queue: what the app enqueues, delivered across restarts. */\nexport interface Queue {\n\t/** This worker's name on its leases. */\n\treadonly owner: string;\n\t/**\n\t * Takes a message to send — already signed, as it will leave — with its\n\t * envelope, and keeps it in the store, every recipient pending, due at\n\t * once. Refuses with `INVALID`, `MESSAGE_TOO_BIG`,\n\t * `TOO_MANY_RECIPIENTS` or `QUEUE_FULL`. The queue sends whatever it is\n\t * given: authenticate the submitter before you enqueue.\n\t */\n\tenqueue(message: MessageSource, envelope: QueueEnvelope): Promise<QueueItem>;\n\t/** One pass by hand: delivers every item due now; resolves with how many it claimed. */\n\tdeliverDue(): Promise<number>;\n\t/** Delivers in the background: a pass every `pollInterval`, and at once after `enqueue`. */\n\tstart(): void;\n\t/** Claims nothing more, lets the deliveries under way end, and gives back the rest. */\n\tstop(): Promise<void>;\n\t/** Listens to an event; returns what stops listening. */\n\ton<E extends keyof QueueEvents>(\n\t\tevent: E,\n\t\tlistener: QueueListener<E>,\n\t): () => void;\n\t/** The items in the queue, the next due first. */\n\tlist(options?: QueueListOptions): Promise<QueueItem[]>;\n\tget(id: string): Promise<QueueItem | undefined>;\n\t/**\n\t * Makes an item due now, and wakes the worker. False when there is no\n\t * such item, or when a worker is delivering it: its outcome sets the\n\t * next attempt, so asking now would change nothing.\n\t */\n\tretryNow(id: string): Promise<boolean>;\n\t/** Drops an item, its message and its recipients, with no DSN; the item as it stood, or `undefined`. */\n\tcancel(id: string): Promise<QueueItem | undefined>;\n}\n\n/**\n * Creates the queue over a store. Nothing is delivered until `start()`,\n * or `deliverDue()` by hand. Several queues — in one process or several —\n * may share a store: each claims items under its own `owner`.\n */\nexport function createQueue(options: QueueOptions): Queue {\n\tconst settings = settingsOf(options);\n\tconst store = options.store;\n\tconst events = new Events();\n\tconst worker = new Worker({ settings, store, events });\n\tconst { limits } = settings;\n\treturn {\n\t\towner: settings.owner,\n\t\tasync enqueue(message, envelope) {\n\t\t\tconst { from, to } = checkEnvelope(envelope, limits.maxRecipients);\n\t\t\tconst bytes = await readMessage(message, limits.maxMessageSize);\n\t\t\tcheckLineEnds(bytes);\n\t\t\tconst item = await store.add(\n\t\t\t\t{ from, to, message: bytes, createdAt: settings.now() },\n\t\t\t\tlimits.maxItems === undefined ? {} : { maxItems: limits.maxItems },\n\t\t\t);\n\t\t\tworker.wake();\n\t\t\treturn item;\n\t\t},\n\t\tdeliverDue: () => worker.deliverDue(),\n\t\tstart: () => worker.start(),\n\t\tstop: () => worker.stop(),\n\t\ton: (event, listener) => events.on(event, listener),\n\t\tlist: (listOptions) => store.list(listOptions),\n\t\tget: (id) => store.get(id),\n\t\tasync retryNow(id) {\n\t\t\tconst now = settings.now();\n\t\t\tconst lease = (await store.get(id))?.lease;\n\t\t\tif (lease && lease.expiresAt > now) return false;\n\t\t\tconst moved = await store.reschedule(id, now);\n\t\t\tif (moved) worker.wake();\n\t\t\treturn moved;\n\t\t},\n\t\tcancel: (id) => store.cancel(id),\n\t};\n}\n"
26
+ ],
27
+ "mappings": ";;;;;AAAA;;;ACGA,IAAM,YAAY,CAAC,SAClB,OAAO,MAAS,QAAQ,OAAQ,QAAQ;AAGlC,SAAS,UAAU,CAAC,MAAuB;AAAA,EACjD,SAAS,IAAI,EAAG,IAAI,KAAK,QAAQ,KAAK;AAAA,IACrC,IAAI,UAAU,KAAK,WAAW,CAAC,CAAC;AA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0,0 +1,2 @@
1
+ export { MemoryQueueStore } from './store';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/memory/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC"}
@@ -0,0 +1,121 @@
1
+ import {
2
+ checkTime,
3
+ checkOwner,
4
+ checkNewItem,
5
+ checkMaxItems,
6
+ checkClaim,
7
+ checkResult,
8
+ checkList,
9
+ isDone,
10
+ applyAttempt,
11
+ newItem,
12
+ claimable
13
+ } from "../chunks/index-xhsw4xcz.js";
14
+ import {
15
+ QueueError2
16
+ } from "../chunks/index-p4k4rjb7.js";
17
+
18
+ // src/memory/store.ts
19
+ var byDue = (a, b) => a.item.nextAttemptAt - b.item.nextAttemptAt || a.seq - b.seq;
20
+
21
+ class MemoryQueueStore {
22
+ #entries = new Map;
23
+ #seq = 0;
24
+ async add(item, options = {}) {
25
+ checkNewItem(item);
26
+ const max = checkMaxItems(options.maxItems);
27
+ if (max !== undefined && this.#entries.size >= max) {
28
+ throw new QueueError2("QUEUE_FULL", `The queue holds ${this.#entries.size} items, its limit`);
29
+ }
30
+ const entry = {
31
+ item: newItem(crypto.randomUUID(), item),
32
+ message: item.message.slice(),
33
+ seq: this.#seq++
34
+ };
35
+ this.#entries.set(entry.item.id, entry);
36
+ return structuredClone(entry.item);
37
+ }
38
+ async get(id) {
39
+ const entry = this.#entries.get(id);
40
+ return entry && structuredClone(entry.item);
41
+ }
42
+ async list(options) {
43
+ const { offset, limit } = checkList(options);
44
+ return [...this.#entries.values()].sort(byDue).slice(offset, offset + limit).map((entry) => structuredClone(entry.item));
45
+ }
46
+ async count() {
47
+ return this.#entries.size;
48
+ }
49
+ async readMessage(id) {
50
+ return this.#entries.get(id)?.message.slice();
51
+ }
52
+ async claim(request) {
53
+ checkClaim(request);
54
+ let next;
55
+ for (const entry of this.#entries.values()) {
56
+ if (!claimable(entry.item, request.now))
57
+ continue;
58
+ if (!next || byDue(entry, next) < 0)
59
+ next = entry;
60
+ }
61
+ if (!next)
62
+ return;
63
+ next.item = {
64
+ ...next.item,
65
+ lease: {
66
+ owner: request.owner,
67
+ expiresAt: request.now + request.leaseMs
68
+ }
69
+ };
70
+ return structuredClone(next.item);
71
+ }
72
+ #held(id, owner) {
73
+ checkOwner(owner);
74
+ const entry = this.#entries.get(id);
75
+ return entry?.item.lease?.owner === owner ? entry : undefined;
76
+ }
77
+ async renew(id, owner, expiresAt) {
78
+ checkTime("expiresAt", expiresAt);
79
+ const entry = this.#held(id, owner);
80
+ if (!entry)
81
+ return false;
82
+ entry.item = { ...entry.item, lease: { owner, expiresAt } };
83
+ return true;
84
+ }
85
+ async complete(id, owner, result) {
86
+ checkResult(result);
87
+ const entry = this.#held(id, owner);
88
+ if (!entry)
89
+ return;
90
+ entry.item = applyAttempt(entry.item, result);
91
+ if (isDone(entry.item))
92
+ this.#entries.delete(id);
93
+ return structuredClone(entry.item);
94
+ }
95
+ async reschedule(id, at, owner) {
96
+ checkTime("at", at);
97
+ const entry = owner === undefined ? this.#entries.get(id) : this.#held(id, owner);
98
+ if (!entry)
99
+ return false;
100
+ if (owner === undefined) {
101
+ entry.item = { ...entry.item, nextAttemptAt: at };
102
+ } else {
103
+ const { lease: _, ...rest } = entry.item;
104
+ entry.item = { ...rest, nextAttemptAt: at };
105
+ }
106
+ return true;
107
+ }
108
+ async cancel(id) {
109
+ const entry = this.#entries.get(id);
110
+ if (!entry)
111
+ return;
112
+ this.#entries.delete(id);
113
+ return structuredClone(entry.item);
114
+ }
115
+ }
116
+ export {
117
+ MemoryQueueStore
118
+ };
119
+
120
+ //# debugId=8E4ADDAFA6329C8564756E2164756E21
121
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/memory/store.ts"],
4
+ "sourcesContent": [
5
+ "import {\n\tapplyAttempt,\n\tcheckClaim,\n\tcheckList,\n\tcheckMaxItems,\n\tcheckNewItem,\n\tcheckOwner,\n\tcheckResult,\n\tcheckTime,\n\tclaimable,\n\tisDone,\n\tnewItem,\n} from '../contract/checks';\nimport type { QueueStore } from '../contract/queue-store';\nimport type {\n\tAddOptions,\n\tAttemptResult,\n\tClaimRequest,\n\tNewQueueItem,\n\tQueueItem,\n\tQueueListOptions,\n} from '../contract/types';\nimport { QueueError } from '../errors';\n\ninterface Entry {\n\titem: QueueItem;\n\tmessage: Uint8Array;\n\t/** The order items were added in: the oldest first among those equally due. */\n\treadonly seq: number;\n}\n\n/** The earliest due first, then the oldest. */\nconst byDue = (a: Entry, b: Entry) =>\n\ta.item.nextAttemptAt - b.item.nextAttemptAt || a.seq - b.seq;\n\n/**\n * A `QueueStore` in memory: for specs, and for a single process that can\n * lose its queue on a restart. Every operation runs without awaiting, so\n * claims never interleave, and every item it returns is a copy.\n */\nexport class MemoryQueueStore implements QueueStore {\n\treadonly #entries = new Map<string, Entry>();\n\t#seq = 0;\n\n\tasync add(item: NewQueueItem, options: AddOptions = {}): Promise<QueueItem> {\n\t\tcheckNewItem(item);\n\t\tconst max = checkMaxItems(options.maxItems);\n\t\tif (max !== undefined && this.#entries.size >= max) {\n\t\t\tthrow new QueueError(\n\t\t\t\t'QUEUE_FULL',\n\t\t\t\t`The queue holds ${this.#entries.size} items, its limit`,\n\t\t\t);\n\t\t}\n\t\tconst entry: Entry = {\n\t\t\titem: newItem(crypto.randomUUID(), item),\n\t\t\tmessage: item.message.slice(),\n\t\t\tseq: this.#seq++,\n\t\t};\n\t\tthis.#entries.set(entry.item.id, entry);\n\t\treturn structuredClone(entry.item);\n\t}\n\n\tasync get(id: string): Promise<QueueItem | undefined> {\n\t\tconst entry = this.#entries.get(id);\n\t\treturn entry && structuredClone(entry.item);\n\t}\n\n\tasync list(options?: QueueListOptions): Promise<QueueItem[]> {\n\t\tconst { offset, limit } = checkList(options);\n\t\treturn [...this.#entries.values()]\n\t\t\t.sort(byDue)\n\t\t\t.slice(offset, offset + limit)\n\t\t\t.map((entry) => structuredClone(entry.item));\n\t}\n\n\tasync count(): Promise<number> {\n\t\treturn this.#entries.size;\n\t}\n\n\tasync readMessage(id: string): Promise<Uint8Array | undefined> {\n\t\treturn this.#entries.get(id)?.message.slice();\n\t}\n\n\tasync claim(request: ClaimRequest): Promise<QueueItem | undefined> {\n\t\tcheckClaim(request);\n\t\tlet next: Entry | undefined;\n\t\tfor (const entry of this.#entries.values()) {\n\t\t\tif (!claimable(entry.item, request.now)) continue;\n\t\t\tif (!next || byDue(entry, next) < 0) next = entry;\n\t\t}\n\t\tif (!next) return undefined;\n\t\tnext.item = {\n\t\t\t...next.item,\n\t\t\tlease: {\n\t\t\t\towner: request.owner,\n\t\t\t\texpiresAt: request.now + request.leaseMs,\n\t\t\t},\n\t\t};\n\t\treturn structuredClone(next.item);\n\t}\n\n\t/** The entry while `owner` holds its lease. */\n\t#held(id: string, owner: string): Entry | undefined {\n\t\tcheckOwner(owner);\n\t\tconst entry = this.#entries.get(id);\n\t\treturn entry?.item.lease?.owner === owner ? entry : undefined;\n\t}\n\n\tasync renew(id: string, owner: string, expiresAt: number): Promise<boolean> {\n\t\tcheckTime('expiresAt', expiresAt);\n\t\tconst entry = this.#held(id, owner);\n\t\tif (!entry) return false;\n\t\tentry.item = { ...entry.item, lease: { owner, expiresAt } };\n\t\treturn true;\n\t}\n\n\tasync complete(\n\t\tid: string,\n\t\towner: string,\n\t\tresult: AttemptResult,\n\t): Promise<QueueItem | undefined> {\n\t\tcheckResult(result);\n\t\tconst entry = this.#held(id, owner);\n\t\tif (!entry) return undefined;\n\t\tentry.item = applyAttempt(entry.item, result);\n\t\tif (isDone(entry.item)) this.#entries.delete(id);\n\t\treturn structuredClone(entry.item);\n\t}\n\n\tasync reschedule(id: string, at: number, owner?: string): Promise<boolean> {\n\t\tcheckTime('at', at);\n\t\tconst entry =\n\t\t\towner === undefined ? this.#entries.get(id) : this.#held(id, owner);\n\t\tif (!entry) return false;\n\t\tif (owner === undefined) {\n\t\t\tentry.item = { ...entry.item, nextAttemptAt: at };\n\t\t} else {\n\t\t\tconst { lease: _, ...rest } = entry.item;\n\t\t\tentry.item = { ...rest, nextAttemptAt: at };\n\t\t}\n\t\treturn true;\n\t}\n\n\tasync cancel(id: string): Promise<QueueItem | undefined> {\n\t\tconst entry = this.#entries.get(id);\n\t\tif (!entry) return undefined;\n\t\tthis.#entries.delete(id);\n\t\treturn structuredClone(entry.item);\n\t}\n}\n"
6
+ ],
7
+ "mappings": ";;;;;;;;;;;;;;;;;;AAgCA,IAAM,QAAQ,CAAC,GAAU,MACxB,EAAE,KAAK,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,MAAM,EAAE;AAAA;AAOnD,MAAM,iBAAuC;AAAA,EAC1C,WAAW,IAAI;AAAA,EACxB,OAAO;AAAA,OAED,IAAG,CAAC,MAAoB,UAAsB,CAAC,GAAuB;AAAA,IAC3E,aAAa,IAAI;AAAA,IACjB,MAAM,MAAM,cAAc,QAAQ,QAAQ;AAAA,IAC1C,IAAI,QAAQ,aAAa,KAAK,SAAS,QAAQ,KAAK;AAAA,MACnD,MAAM,IAAI,YACT,cACA,mBAAmB,KAAK,SAAS,uBAClC;AAAA,IACD;AAAA,IACA,MAAM,QAAe;AAAA,MACpB,MAAM,QAAQ,OAAO,WAAW,GAAG,IAAI;AAAA,MACvC,SAAS,KAAK,QAAQ,MAAM;AAAA,MAC5B,KAAK,KAAK;AAAA,IACX;AAAA,IACA,KAAK,SAAS,IAAI,MAAM,KAAK,IAAI,KAAK;AAAA,IACtC,OAAO,gBAAgB,MAAM,IAAI;AAAA;AAAA,OAG5B,IAAG,CAAC,IAA4C;AAAA,IACrD,MAAM,QAAQ,KAAK,SAAS,IAAI,EAAE;AAAA,IAClC,OAAO,SAAS,gBAAgB,MAAM,IAAI;AAAA;AAAA,OAGrC,KAAI,CAAC,SAAkD;AAAA,IAC5D,QAAQ,QAAQ,UAAU,UAAU,OAAO;AAAA,IAC3C,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AC1D,OAAO;AAAA;AAAA,OAGF,SAAQ,CACb,IACA,OACA,QACiC;AAAA,IACjC,YAAY,MAAM;AAAA,IAClB,MAAM,QAAQ,KAAK,MAAM,IAAI,KAAK;AAAA,IAClC,IAAI,CAAC;AAAA,MAAO;AAAA,IACZ,MAAM,OAAO,aAAa,MAAM,MAAM,MAAM;AAAA,IAC5C,IAAI,OAAO,MAAM,IAAI;AAAA,MAAG,KAAK,SAAS,OAAO,EAAE;AAAA,IAC/C,OAAO,gBAAgB,MAAM,IAAI;AAAA;AAAA,OAG5B,WAAU,CAAC,IAAY,IAAY,OAAkC;AAAA,IAC1E,UAAU,MAAM,EAAE;AAAA,IAClB,MAAM,QACL,UAAU,YAAY,KAAK,SAAS,IAAI,EAAE,IAAI,KAAK,MAAM,IAAI,KAAK;AAAA,IACnE,IAAI,CAAC;AAAA,MAAO,OAAO;AAAA,IACnB,IAAI,UAAU,WAAW;AAAA,MACxB,MAAM,OAAO,KAAK,MAAM,MAAM,eAAe,GAAG;AAAA,IACjD,EAAO;AAAA,MACN,QAAQ,OAAO,MAAM,SAAS,MAAM;AAAA,MACpC,MAAM,OAAO,KAAK,MAAM,eAAe,GAAG;AAAA;AAAA,IAE3C,OAAO;AAAA;AAAA,OAGF,OAAM,CAAC,IAA4C;AAAA,IACxD,MAAM,QAAQ,KAAK,SAAS,IAAI,EAAE;AAAA,IAClC,IAAI,CAAC;AAAA,MAAO;AAAA,IACZ,KAAK,SAAS,OAAO,EAAE;AAAA,IACvB,OAAO,gBAAgB,MAAM,IAAI;AAAA;AAEnC;",
8
+ "debugId": "8E4ADDAFA6329C8564756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,21 @@
1
+ import type { QueueStore } from '../contract/queue-store';
2
+ import type { AddOptions, AttemptResult, ClaimRequest, NewQueueItem, QueueItem, QueueListOptions } from '../contract/types';
3
+ /**
4
+ * A `QueueStore` in memory: for specs, and for a single process that can
5
+ * lose its queue on a restart. Every operation runs without awaiting, so
6
+ * claims never interleave, and every item it returns is a copy.
7
+ */
8
+ export declare class MemoryQueueStore implements QueueStore {
9
+ #private;
10
+ add(item: NewQueueItem, options?: AddOptions): Promise<QueueItem>;
11
+ get(id: string): Promise<QueueItem | undefined>;
12
+ list(options?: QueueListOptions): Promise<QueueItem[]>;
13
+ count(): Promise<number>;
14
+ readMessage(id: string): Promise<Uint8Array | undefined>;
15
+ claim(request: ClaimRequest): Promise<QueueItem | undefined>;
16
+ renew(id: string, owner: string, expiresAt: number): Promise<boolean>;
17
+ complete(id: string, owner: string, result: AttemptResult): Promise<QueueItem | undefined>;
18
+ reschedule(id: string, at: number, owner?: string): Promise<boolean>;
19
+ cancel(id: string): Promise<QueueItem | undefined>;
20
+ }
21
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/memory/store.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EACX,UAAU,EACV,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,MAAM,mBAAmB,CAAC;AAc3B;;;;GAIG;AACH,qBAAa,gBAAiB,YAAW,UAAU;;IAI5C,GAAG,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,GAAE,UAAe,GAAG,OAAO,CAAC,SAAS,CAAC;IAkBrE,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;IAK/C,IAAI,CAAC,OAAO,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAQtD,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;IAIxB,WAAW,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC;IAIxD,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;IAyB5D,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAQrE,QAAQ,CACb,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,aAAa,GACnB,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;IAS3B,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAcpE,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;CAMxD"}
@@ -0,0 +1,20 @@
1
+ import type { QueueItem } from '../contract/types';
2
+ import type { Events } from './events';
3
+ import type { KeyedLimiter } from './limiter';
4
+ import { type NotifyContext } from './notify';
5
+ export interface DeliveryContext extends NotifyContext {
6
+ readonly domains: KeyedLimiter;
7
+ readonly events: Events;
8
+ /** The worker is stopping: a group not started yet is left for later. */
9
+ readonly stopping: () => boolean;
10
+ /** The outcome is recorded: the lease needs no more renewal. */
11
+ readonly recorded: () => void;
12
+ }
13
+ /**
14
+ * Delivers a claimed item: one session per recipient domain, at most
15
+ * `perDomain` at once to each — none, and no slot taken, when its sender
16
+ * is one `sendMail` would refuse — then the outcome recorded — which lets go
17
+ * of the lease — then the events and the DSNs.
18
+ */
19
+ export declare function deliverItem(ctx: DeliveryContext, item: QueueItem): Promise<void>;
20
+ //# sourceMappingURL=deliver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deliver.d.ts","sourceRoot":"","sources":["../../src/queue/deliver.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,mBAAmB,CAAC;AAGpE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,KAAK,aAAa,EAAU,MAAM,UAAU,CAAC;AAKtD,MAAM,WAAW,eAAgB,SAAQ,aAAa;IACrD,QAAQ,CAAC,OAAO,EAAE,YAAY,CAAC;IAC/B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,yEAAyE;IACzE,QAAQ,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC;IACjC,gEAAgE;IAChE,QAAQ,CAAC,QAAQ,EAAE,MAAM,IAAI,CAAC;CAC9B;AA0FD;;;;;GAKG;AACH,wBAAsB,WAAW,CAChC,GAAG,EAAE,eAAe,EACpB,IAAI,EAAE,SAAS,GACb,OAAO,CAAC,IAAI,CAAC,CA8Cf"}
@@ -0,0 +1,26 @@
1
+ /** What `enqueue` takes as the message: its bytes, its text, or a stream of it. */
2
+ export type MessageSource = Uint8Array | string | ReadableStream<Uint8Array>;
3
+ /** The SMTP envelope of a message to send. */
4
+ export interface QueueEnvelope {
5
+ /** The reverse-path, `local@domain`; `''` for the null sender (a bounce of your own). */
6
+ readonly from: string;
7
+ /** One recipient or more, `local@domain` each. */
8
+ readonly to: string | readonly string[];
9
+ }
10
+ export declare function checkAddress(name: string, address: unknown): string;
11
+ /** The recipient's domain, in lowercase: what deliveries are grouped by. */
12
+ export declare const domainOf: (address: string) => string;
13
+ /** The envelope, checked: the sender, and each recipient once, at most `maxRecipients`. */
14
+ export declare function checkEnvelope(envelope: QueueEnvelope, maxRecipients: number): {
15
+ from: string;
16
+ to: string[];
17
+ };
18
+ /**
19
+ * Refuses a message with a CR not followed by an LF, or an LF not after a
20
+ * CR: `sendMail` would refuse it at delivery (`BARE_LINE_BREAK`, SMTP
21
+ * smuggling), failing every recipient.
22
+ */
23
+ export declare function checkLineEnds(bytes: Uint8Array): void;
24
+ /** The message's bytes, read to its end but never past `max`: past it, `MESSAGE_TOO_BIG`. */
25
+ export declare function readMessage(source: MessageSource, max: number): Promise<Uint8Array>;
26
+ //# sourceMappingURL=envelope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../../src/queue/envelope.ts"],"names":[],"mappings":"AAIA,mFAAmF;AACnF,MAAM,MAAM,aAAa,GAAG,UAAU,GAAG,MAAM,GAAG,cAAc,CAAC,UAAU,CAAC,CAAC;AAE7E,8CAA8C;AAC9C,MAAM,WAAW,aAAa;IAC7B,yFAAyF;IACzF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,kDAAkD;IAClD,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;CACxC;AAYD,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,MAAM,CAanE;AAED,4EAA4E;AAC5E,eAAO,MAAM,QAAQ,GAAI,SAAS,MAAM,WACkB,CAAC;AAE3D,2FAA2F;AAC3F,wBAAgB,aAAa,CAC5B,QAAQ,EAAE,aAAa,EACvB,aAAa,EAAE,MAAM,GACnB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,EAAE,CAAA;CAAE,CAyBhC;AAWD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAarD;AAED,6FAA6F;AAC7F,wBAAsB,WAAW,CAChC,MAAM,EAAE,aAAa,EACrB,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,UAAU,CAAC,CAsCrB"}
@@ -0,0 +1,48 @@
1
+ import type { Diagnostic } from '../contract/types';
2
+ /** One recipient's outcome. */
3
+ export interface RecipientEvent {
4
+ /** The item's id. */
5
+ readonly id: string;
6
+ readonly from: string;
7
+ readonly recipient: string;
8
+ /** What the other side said, or why nobody said anything. */
9
+ readonly reply?: Diagnostic;
10
+ /** The attempts made so far, this one included. */
11
+ readonly attempts: number;
12
+ }
13
+ export interface DeferredEvent extends RecipientEvent {
14
+ /** When the recipient is tried again, in milliseconds since the epoch. */
15
+ readonly nextAttemptAt: number;
16
+ }
17
+ /** A DSN, enqueued back to the sender. */
18
+ export interface DsnEvent {
19
+ readonly kind: 'delayed' | 'failed';
20
+ /** The DSN's own item id. */
21
+ readonly id: string;
22
+ /** The id of the item it reports on. */
23
+ readonly of: string;
24
+ /** The original's sender, to whom it goes. */
25
+ readonly to: string;
26
+ readonly recipients: readonly string[];
27
+ }
28
+ /** A failure of the queue itself: the store, a DSN that could not be enqueued, a lease lost. */
29
+ export interface QueueErrorEvent {
30
+ readonly error: unknown;
31
+ /** The item it happened to, if any. */
32
+ readonly id?: string;
33
+ }
34
+ export interface QueueEvents {
35
+ delivered: RecipientEvent;
36
+ deferred: DeferredEvent;
37
+ failed: RecipientEvent;
38
+ dsn: DsnEvent;
39
+ error: QueueErrorEvent;
40
+ }
41
+ export type QueueListener<E extends keyof QueueEvents> = (event: QueueEvents[E]) => void;
42
+ /** Listeners by event. One that throws is ignored: it never stops a delivery. */
43
+ export declare class Events {
44
+ #private;
45
+ on<E extends keyof QueueEvents>(event: E, listener: QueueListener<E>): () => void;
46
+ emit<E extends keyof QueueEvents>(event: E, payload: QueueEvents[E]): void;
47
+ }
48
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/queue/events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,+BAA+B;AAC/B,MAAM,WAAW,cAAc;IAC9B,qBAAqB;IACrB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,6DAA6D;IAC7D,QAAQ,CAAC,KAAK,CAAC,EAAE,UAAU,CAAC;IAC5B,mDAAmD;IACnD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC1B;AAED,MA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export declare class Limiter {
3
+ #private;
4
+ constructor(size: number);
5
+ /** A slot, once one is free; call what it resolves to, once, to give it back. */
6
+ acquire(): Promise<() => void>;
7
+ }
8
+ /** One `Limiter` per key, made when first asked for and dropped once idle. */
9
+ export declare class KeyedLimiter {
10
+ #private;
11
+ constructor(size: number);
12
+ acquire(key: string): Promise<() => void>;
13
+ }
14
+ //# sourceMappingURL=limiter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limiter.d.ts","sourceRoot":"","sources":["../../src/queue/limiter.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,qBAAa,OAAO;;gBAKP,IAAI,EAAE,MAAM;IAIxB,iFAAiF;IAC3E,OAAO,IAAI,OAAO,CAAC,MAAM,IAAI,CAAC;CAgBpC;AAED,8EAA8E;AAC9E,qBAAa,YAAY;;gBAIZ,IAAI,EAAE,MAAM;IAIlB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,CAAC;CAc/C"}
@@ -0,0 +1,19 @@
1
+ import type { QueueStore } from '../contract/queue-store';
2
+ import type { QueueItem, RecipientUpdate } from '../contract/types';
3
+ import { type DsnKind } from '../dsn/build';
4
+ import type { Events } from './events';
5
+ import type { Settings } from './settings';
6
+ export interface NotifyContext {
7
+ readonly settings: Settings;
8
+ readonly store: QueueStore;
9
+ readonly events: Events;
10
+ }
11
+ /**
12
+ * Enqueues a DSN (RFC 3464) back to the item's sender for these
13
+ * recipients, from the null sender, so it never causes one of its own.
14
+ * Nothing for an item from the null sender (RFC 5321 §4.5.5, RFC 3464
15
+ * §2: a DSN is never sent about a DSN). It bypasses `maxItems`: a full
16
+ * queue loses no bounce. A failure goes to the `error` event.
17
+ */
18
+ export declare function notify(ctx: NotifyContext, item: QueueItem, message: Uint8Array, kind: DsnKind, recipients: readonly RecipientUpdate[], now: number): Promise<void>;
19
+ //# sourceMappingURL=notify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notify.d.ts","sourceRoot":"","sources":["../../src/queue/notify.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAY,KAAK,OAAO,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAEvC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;GAMG;AACH,wBAAsB,MAAM,CAC3B,GAAG,EAAE,aAAa,EAClB,IAAI,EAAE,SAAS,EACf,OAAO,EAAE,UAAU,EACnB,IAAI,EAAE,OAAO,EACb,UAAU,EAAE,SAAS,eAAe,EAAE,EACtC,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,IAAI,CAAC,CAwCf"}