@geekmidas/constructs 10.0.0-alpha.167 → 10.0.0-alpha.169
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/dist/Construct-127M7yrl.d.cts.map +1 -1
- package/dist/Construct-BMk_CRSD.d.mts.map +1 -1
- package/dist/{Queue-u8w8_HpE.mjs → Queue-9Hh20ZCk.mjs} +3 -3
- package/dist/Queue-9Hh20ZCk.mjs.map +1 -0
- package/dist/Queue-B8HGg439.d.mts.map +1 -1
- package/dist/Queue-C4rijiM7.d.cts.map +1 -1
- package/dist/{Queue-D4Iaidrs.cjs → Queue-W1wueijP.cjs} +2 -2
- package/dist/Queue-W1wueijP.cjs.map +1 -0
- package/dist/{QueueBuilder-BxsZ9o5z.cjs → QueueBuilder-BDcv9B71.cjs} +2 -2
- package/dist/{QueueBuilder-BxsZ9o5z.cjs.map → QueueBuilder-BDcv9B71.cjs.map} +1 -1
- package/dist/{QueueBuilder-2wP5lEC8.mjs → QueueBuilder-CrZL8HHs.mjs} +2 -2
- package/dist/{QueueBuilder-2wP5lEC8.mjs.map → QueueBuilder-CrZL8HHs.mjs.map} +1 -1
- package/dist/{Topic-DN2gYJ-p.mjs → Topic-BGoOeCT6.mjs} +3 -3
- package/dist/Topic-BGoOeCT6.mjs.map +1 -0
- package/dist/{Topic-Dp9Q7Lj2.cjs → Topic-DLCZBNwK.cjs} +2 -2
- package/dist/Topic-DLCZBNwK.cjs.map +1 -0
- package/dist/adaptors/awsWebsocket.d.cts +1 -1
- package/dist/adaptors/awsWebsocket.d.mts +1 -1
- package/dist/adaptors/testing.cjs +15 -15
- package/dist/adaptors/testing.cjs.map +1 -1
- package/dist/adaptors/testing.d.cts +1 -1
- package/dist/adaptors/testing.d.cts.map +1 -1
- package/dist/adaptors/testing.d.mts +1 -1
- package/dist/adaptors/testing.d.mts.map +1 -1
- package/dist/adaptors/testing.mjs +16 -16
- package/dist/adaptors/testing.mjs.map +1 -1
- package/dist/auth-1yI2wR-4.d.cts.map +1 -1
- package/dist/auth-D4NMXgLt.d.mts.map +1 -1
- package/dist/auth.cjs +5 -5
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.mjs +6 -6
- package/dist/auth.mjs.map +1 -1
- package/dist/cache.cjs +1 -1
- package/dist/cache.cjs.map +1 -1
- package/dist/cache.mjs +2 -2
- package/dist/cache.mjs.map +1 -1
- package/dist/{credential-DfSAOOdY.mjs → credential-B80mOxwT.mjs} +3 -3
- package/dist/credential-B80mOxwT.mjs.map +1 -0
- package/dist/{credential-DYymbp_7.cjs → credential-RlgbzZAc.cjs} +2 -2
- package/dist/credential-RlgbzZAc.cjs.map +1 -0
- package/dist/credential.cjs +1 -1
- package/dist/credential.mjs +1 -1
- package/dist/database/kysely.cjs +1 -1
- package/dist/database/kysely.mjs +1 -1
- package/dist/email.cjs +22 -3
- package/dist/email.cjs.map +1 -1
- package/dist/email.d.cts +14 -4
- package/dist/email.d.cts.map +1 -1
- package/dist/email.d.mts +14 -4
- package/dist/email.d.mts.map +1 -1
- package/dist/email.mjs +23 -5
- package/dist/email.mjs.map +1 -1
- package/dist/encryption.cjs +1 -1
- package/dist/encryption.cjs.map +1 -1
- package/dist/encryption.mjs +2 -2
- package/dist/encryption.mjs.map +1 -1
- package/dist/external-api.cjs +3 -3
- package/dist/external-api.cjs.map +1 -1
- package/dist/external-api.mjs +4 -4
- package/dist/external-api.mjs.map +1 -1
- package/dist/fake-BvOXkZmj.d.mts.map +1 -1
- package/dist/fake-Djx8E0o1.d.cts.map +1 -1
- package/dist/file-server.cjs +1 -1
- package/dist/file-server.cjs.map +1 -1
- package/dist/file-server.d.cts.map +1 -1
- package/dist/file-server.d.mts.map +1 -1
- package/dist/file-server.mjs +2 -2
- package/dist/file-server.mjs.map +1 -1
- package/dist/inbox.cjs +3 -3
- package/dist/inbox.cjs.map +1 -1
- package/dist/inbox.mjs +4 -4
- package/dist/inbox.mjs.map +1 -1
- package/dist/{kysely-Cs4uPO8k.mjs → kysely-Bc9xzaik.mjs} +4 -4
- package/dist/kysely-Bc9xzaik.mjs.map +1 -0
- package/dist/{kysely-CukArHJ0.cjs → kysely-D7f6J2lh.cjs} +3 -3
- package/dist/kysely-D7f6J2lh.cjs.map +1 -0
- package/dist/mobile-app.cjs +1 -1
- package/dist/mobile-app.cjs.map +1 -1
- package/dist/mobile-app.mjs +2 -2
- package/dist/mobile-app.mjs.map +1 -1
- package/dist/object-storage.cjs +1 -1
- package/dist/object-storage.cjs.map +1 -1
- package/dist/object-storage.d.cts.map +1 -1
- package/dist/object-storage.d.mts.map +1 -1
- package/dist/object-storage.mjs +2 -2
- package/dist/object-storage.mjs.map +1 -1
- package/dist/queue/index.cjs +2 -2
- package/dist/queue/index.mjs +2 -2
- package/dist/rest-api.cjs +15 -3
- package/dist/rest-api.cjs.map +1 -1
- package/dist/rest-api.d.cts +8 -2
- package/dist/rest-api.d.cts.map +1 -1
- package/dist/rest-api.d.mts +8 -2
- package/dist/rest-api.d.mts.map +1 -1
- package/dist/rest-api.mjs +11 -5
- package/dist/rest-api.mjs.map +1 -1
- package/dist/site.cjs +28 -2
- package/dist/site.cjs.map +1 -1
- package/dist/site.d.cts +16 -1
- package/dist/site.d.cts.map +1 -1
- package/dist/site.d.mts +16 -1
- package/dist/site.d.mts.map +1 -1
- package/dist/site.mjs +12 -4
- package/dist/site.mjs.map +1 -1
- package/dist/topic/index.cjs +1 -1
- package/dist/topic/index.mjs +1 -1
- package/dist/{websocket-api-Bg9SowJ5.mjs → websocket-api-C6LGg9-D.mjs} +12 -6
- package/dist/{websocket-api-Bg9SowJ5.mjs.map → websocket-api-C6LGg9-D.mjs.map} +1 -1
- package/dist/{websocket-api-B1Wl3tg4.d.cts → websocket-api-CD-E5Ogr.d.cts} +9 -3
- package/dist/{websocket-api-B1Wl3tg4.d.cts.map → websocket-api-CD-E5Ogr.d.cts.map} +1 -1
- package/dist/{websocket-api-czxhekGG.cjs → websocket-api-CoKPJJRl.cjs} +10 -4
- package/dist/websocket-api-CoKPJJRl.cjs.map +1 -0
- package/dist/{websocket-api-CvnPDSZB.d.mts → websocket-api-pJJfeTcm.d.mts} +9 -3
- package/dist/{websocket-api-CvnPDSZB.d.mts.map → websocket-api-pJJfeTcm.d.mts.map} +1 -1
- package/dist/websocket-api.cjs +8 -1
- package/dist/websocket-api.d.cts +2 -2
- package/dist/websocket-api.d.mts +2 -2
- package/dist/websocket-api.mjs +2 -2
- package/dist/worker.cjs +1 -1
- package/dist/worker.mjs +1 -1
- package/package.json +31 -31
- package/dist/Queue-D4Iaidrs.cjs.map +0 -1
- package/dist/Queue-u8w8_HpE.mjs.map +0 -1
- package/dist/Topic-DN2gYJ-p.mjs.map +0 -1
- package/dist/Topic-Dp9Q7Lj2.cjs.map +0 -1
- package/dist/credential-DYymbp_7.cjs.map +0 -1
- package/dist/credential-DfSAOOdY.mjs.map +0 -1
- package/dist/kysely-Cs4uPO8k.mjs.map +0 -1
- package/dist/kysely-CukArHJ0.cjs.map +0 -1
- package/dist/websocket-api-czxhekGG.cjs.map +0 -1
package/dist/inbox.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inbox.mjs","names":[],"sources":["../src/inbox.ts"],"sourcesContent":["/**\n * `Inbox` — mail received at addresses on the stage's domain, each message\n * handled in a worker.\n *\n * ```ts\n * export const requests = new Inbox('Requests', {\n * addresses: ['requests'], // local parts: structural\n * subdomains: true, // requests@<tenant>.<stage domain>\n * });\n *\n * export const onRequest = worker\n * .inbox(requests)\n * .handle(async ({ messages }) => {\n * for (const message of messages) {\n * message.recipient.subdomain; // the tenant, from the envelope\n * message.recipient.tag; // requests+<tag>@\n * }\n * });\n * ```\n *\n * **Its own bucket, and a topic.** An inbox owns the bucket its raw messages\n * are kept in — each target creates it for the inbox, never one the stack\n * already runs — and provides its URL itself, so the bucket is no `objects`\n * node and no object subscriber can be bound to it. It declares the topic\n * each message is announced on, which only the provider publishes to.\n *\n * **One decoder.** Deployed, SES's receipt rule stores the raw message and\n * publishes its receipt notification on the topic. Locally `gkm dev` brings a\n * message in from Mailpit and publishes the same notification; in a feature\n * test `mailbox.receive` does. The handler is handed what {@link InboxClient}\n * makes of that notification, wherever it came from.\n *\n * **The envelope routes.** Which inbox, which tenant and which tag come from\n * the envelope recipient, never from `From:` or `To:`, which the sender wrote.\n */\n\nimport { type ParsedEmail, parseEmail } from '@geekmidas/emailkit/inbound';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tINBOX_EVENT,\n\ttype InboxAddressing,\n\ttype InboxRecipient,\n\tinboxRecipient,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { createStorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Construct } from './construct-interface';\nimport { Topic } from './topic/Topic';\n\nexport interface InboxOptions {\n\t/**\n\t * The local parts it receives at: `['requests']`. Each also takes a\n\t * `+tag` — `requests+t_8f3k@` — handed to the handler as `recipient.tag`.\n\t */\n\taddresses: readonly string[];\n\t/**\n\t * Receive at `<address>@<label>.<domain>` — one label, a tenant's — rather\n\t * than at the stage's domain itself.\n\t */\n\tsubdomains?: boolean;\n}\n\n/** An inbox declared with no address receives nothing. */\nexport class InboxHasNoAddresses extends Error {\n\tconstructor(readonly inbox: string) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' names no address, so it would receive nothing. ` +\n\t\t\t\t`Name the local parts it receives at: addresses: ['requests'].`,\n\t\t);\n\t\tthis.name = 'InboxHasNoAddresses';\n\t}\n}\n\n/** An address that is not a bare local part: `requests@x`, `a+b`, `''`. */\nexport class InboxAddressInvalid extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly address: string,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' names '${address}', which is not a local part. ` +\n\t\t\t\t`Name only what goes before the @ — the domain is the stage's — ` +\n\t\t\t\t`and no '+': every address takes a +tag already.`,\n\t\t);\n\t\tthis.name = 'InboxAddressInvalid';\n\t}\n}\n\n/**\n * A receipt notification the inbox cannot read: not SES's shape, or an action\n * other than the S3 one that stores the message where the decoder reads it.\n */\nexport class ReceiptNotificationMalformed extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' was handed a notification it cannot read: ${reason}. ` +\n\t\t\t\t`It reads SES receipt notifications whose action stored the message in S3.`,\n\t\t);\n\t\tthis.name = 'ReceiptNotificationMalformed';\n\t}\n}\n\n/**\n * A provider's verdict on a message.\n *\n * `'unavailable'` where nothing judged it — locally, always — and never a\n * faked `'pass'`.\n */\nexport type Verdict = 'pass' | 'fail' | 'gray' | 'unavailable';\n\n/** What the provider judged of a message, which the message cannot say of itself. */\nexport interface Verdicts {\n\tspf: Verdict;\n\tdkim: Verdict;\n\tdmarc: Verdict;\n\tspam: Verdict;\n\tvirus: Verdict;\n}\n\n/**\n * One received message, for one recipient it was delivered to.\n *\n * `recipient` is the envelope's; every other address is a header, written by\n * the sender. Inbound mail is untrusted input: route on `recipient`, treat\n * `from` as a claim until `verdicts.dmarc` passes *and* the address is known,\n * sanitise `html`, and never use an attachment's filename as a key or path.\n */\nexport interface InboxMessage\n\textends Omit<ParsedEmail, 'attachments'>,\n\t\tPick<ParsedEmail, 'attachments'> {\n\trecipient: InboxRecipient;\n\t/**\n\t * Where the raw message is kept: the bucket SES stored it in (`mailpit`\n\t * locally), and its key there.\n\t */\n\traw: { bucket: string; key: string };\n\tverdicts: Verdicts;\n}\n\n/** A status as SES writes one: `PASS`, `FAIL`, `GRAY`, `PROCESSING_FAILED`, `DISABLED`. */\ninterface ReceiptVerdict {\n\tstatus: string;\n}\n\n/**\n * SES's receipt notification — the part an inbox reads.\n *\n * `gkm dev` and the test mailbox publish the same shape, with every verdict\n * `UNAVAILABLE`, so one decoder serves all three.\n */\nexport interface ReceiptNotification {\n\tnotificationType: 'Received';\n\tmail: {\n\t\tmessageId: string;\n\t\ttimestamp: string;\n\t\t/** The envelope sender (`MAIL FROM`). */\n\t\tsource: string;\n\t\tdestination: string[];\n\t};\n\treceipt: {\n\t\ttimestamp: string;\n\t\t/** The envelope recipients this receipt rule matched. */\n\t\trecipients: string[];\n\t\tspamVerdict?: ReceiptVerdict;\n\t\tvirusVerdict?: ReceiptVerdict;\n\t\tspfVerdict?: ReceiptVerdict;\n\t\tdkimVerdict?: ReceiptVerdict;\n\t\tdmarcVerdict?: ReceiptVerdict;\n\t\taction: {\n\t\t\ttype: string;\n\t\t\tbucketName?: string;\n\t\t\tobjectKey?: string;\n\t\t\ttopicArn?: string;\n\t\t};\n\t};\n}\n\n/** What the handler's inbox is: its domain, its raw messages, the decoder. */\nexport interface InboxClient {\n\t/** The stage's domain it receives on. */\n\treadonly domain: string;\n\t/** A raw message's bytes, by its key in the bucket. */\n\traw(key: string): Promise<Uint8Array>;\n\t/**\n\t * The messages a notification announces: one per envelope recipient this\n\t * inbox receives at, parsed. Empty when none is — a receipt rule that takes\n\t * a whole domain stores mail for addresses no inbox declared.\n\t */\n\tmessages(notification: ReceiptNotification): Promise<InboxMessage[]>;\n}\n\n/** A schema that takes a receipt notification as it is — SES wrote it, not the app. */\nconst RECEIPT_NOTIFICATION: StandardSchemaV1<ReceiptNotification> = {\n\t'~standard': {\n\t\tversion: 1,\n\t\tvendor: 'geekmidas',\n\t\tvalidate: (value) => ({ value: value as ReceiptNotification }),\n\t},\n};\n\ntype InboxTopic = Topic<string, { [INBOX_EVENT]: typeof RECEIPT_NOTIFICATION }>;\n\nexport class Inbox<TName extends string = string>\n\timplements Construct<TName, InboxClient>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, InboxClient>;\n\t/** Where each received message is announced. Published to by the provider only. */\n\treadonly topic: InboxTopic;\n\n\t/** The local parts it receives at, and whether on a tenant's subdomain. */\n\treadonly addressing: InboxAddressing;\n\tprivate readonly addresses: readonly string[];\n\tprivate readonly subdomains: boolean;\n\tprivate readonly keys: { url: string; domain: string };\n\n\tconstructor(name: ConstructName<TName>, options: InboxOptions) {\n\t\tconst canonical = canonicalId(name as string);\n\t\tif (options.addresses.length === 0) {\n\t\t\tthrow new InboxHasNoAddresses(canonical);\n\t\t}\n\t\tfor (const address of options.addresses) {\n\t\t\tif (!/^[a-z0-9][a-z0-9._-]*$/i.test(address)) {\n\t\t\t\tthrow new InboxAddressInvalid(canonical, address);\n\t\t\t}\n\t\t}\n\n\t\tthis.id = canonical as TName;\n\t\tthis.addresses = options.addresses.map((a) => a.toLowerCase());\n\t\tthis.subdomains = options.subdomains === true;\n\t\tthis.addressing = {\n\t\t\taddresses: this.addresses,\n\t\t\t...(this.subdomains ? { subdomains: true } : {}),\n\t\t};\n\t\tthis.keys = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\tdomain: provideKey(canonical, 'domain'),\n\t\t};\n\t\tthis.topic = new Topic(`${canonical}Mail`, {\n\t\t\tevents: { [INBOX_EVENT]: RECEIPT_NOTIFICATION },\n\t\t}) as InboxTopic;\n\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (register) => this.connect(register),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t...this.topic.declare(),\n\t\t\t{\n\t\t\t\tkind: 'inbox',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.keys.url, this.keys.domain],\n\t\t\t\taddresses: this.addresses,\n\t\t\t\t...(this.subdomains ? { subdomains: true } : {}),\n\t\t\t\ttopic: this.topic.id,\n\t\t\t},\n\t\t];\n\t}\n\n\tprivate async connect(\n\t\tregister: ServiceRegisterOptions,\n\t): Promise<InboxClient> {\n\t\tconst { url, domain } = register.envParser\n\t\t\t.create((get) => ({\n\t\t\t\turl: get(this.keys.url).string(),\n\t\t\t\tdomain: get(this.keys.domain).string(),\n\t\t\t}))\n\t\t\t.parse();\n\t\tconst read = rawReader(url);\n\t\tconst addressing = {\n\t\t\taddresses: this.addresses,\n\t\t\tsubdomains: this.subdomains,\n\t\t};\n\t\tconst inbox = this.id;\n\n\t\tconst raw = async (key: string): Promise<Uint8Array> => {\n\t\t\tconst response = await fetch(await read(key));\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new RawMessageUnreadable(inbox, key, response.status);\n\t\t\t}\n\t\t\treturn new Uint8Array(await response.arrayBuffer());\n\t\t};\n\n\t\treturn {\n\t\t\tdomain,\n\t\t\traw,\n\t\t\tasync messages(notification) {\n\t\t\t\tconst { receipt } = assertReceipt(inbox, notification);\n\t\t\t\tconst recipients = receipt.recipients.flatMap((address) => {\n\t\t\t\t\tconst recipient = inboxRecipient(address, addressing, domain);\n\t\t\t\t\treturn recipient ? [recipient] : [];\n\t\t\t\t});\n\t\t\t\tif (recipients.length === 0) return [];\n\n\t\t\t\tconst key = receipt.action.objectKey!;\n\t\t\t\tconst parsed = await parseEmail(await raw(key));\n\t\t\t\tconst verdicts = verdictsOf(receipt);\n\t\t\t\treturn recipients.map((recipient) => ({\n\t\t\t\t\t...parsed,\n\t\t\t\t\trecipient,\n\t\t\t\t\traw: { bucket: receipt.action.bucketName!, key },\n\t\t\t\t\tverdicts,\n\t\t\t\t}));\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * Where a raw message is read from, by its key, for the store `url` names:\n * an `s3://` bucket deployed — SES stored it at `messages/<id>` — or, locally,\n * Mailpit's API, which keeps every message it receives under its own id.\n *\n * The one place local and deployed differ; everything that reads a message\n * goes through it.\n */\nfunction rawReader(url: string): (key: string) => Promise<string> {\n\tif (url.startsWith('s3:')) {\n\t\tconst bucket = createStorageClient(url);\n\t\treturn async (key) => (await bucket).getDownloadURL({ path: key });\n\t}\n\tconst base = url.replace(/\\/+$/, '');\n\treturn async (key) => `${base}/api/v1/message/${encodeURIComponent(key)}/raw`;\n}\n\n/** The raw message a notification names could not be read from its store. */\nexport class RawMessageUnreadable extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly key: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' could not read its raw message '${key}' (HTTP ${status}). ` +\n\t\t\t\t`It is written by the receipt rule before the notification is sent; ` +\n\t\t\t\t`check the bucket's policy lets the process that runs the handler read it.`,\n\t\t);\n\t\tthis.name = 'RawMessageUnreadable';\n\t}\n}\n\nfunction assertReceipt(inbox: string, value: unknown): ReceiptNotification {\n\tconst notification = value as Partial<ReceiptNotification> | undefined;\n\tif (notification?.notificationType !== 'Received') {\n\t\tthrow new ReceiptNotificationMalformed(\n\t\t\tinbox,\n\t\t\t`its notificationType is '${String(notification?.notificationType)}', not 'Received'`,\n\t\t);\n\t}\n\tconst action = notification.receipt?.action;\n\tif (action?.type !== 'S3' || !action.objectKey || !action.bucketName) {\n\t\tthrow new ReceiptNotificationMalformed(\n\t\t\tinbox,\n\t\t\t`its action is '${String(action?.type)}' without an S3 object`,\n\t\t);\n\t}\n\tif (!Array.isArray(notification.receipt?.recipients)) {\n\t\tthrow new ReceiptNotificationMalformed(inbox, 'it names no recipients');\n\t}\n\treturn notification as ReceiptNotification;\n}\n\nfunction verdict(status: ReceiptVerdict | undefined): Verdict {\n\tswitch (status?.status) {\n\t\tcase 'PASS':\n\t\t\treturn 'pass';\n\t\tcase 'FAIL':\n\t\t\treturn 'fail';\n\t\tcase 'GRAY':\n\t\t\treturn 'gray';\n\t\tdefault:\n\t\t\treturn 'unavailable';\n\t}\n}\n\nfunction verdictsOf(receipt: ReceiptNotification['receipt']): Verdicts {\n\treturn {\n\t\tspf: verdict(receipt.spfVerdict),\n\t\tdkim: verdict(receipt.dkimVerdict),\n\t\tdmarc: verdict(receipt.dmarcVerdict),\n\t\tspam: verdict(receipt.spamVerdict),\n\t\tvirus: verdict(receipt.virusVerdict),\n\t};\n}\n\n/**\n * The receipt notification a provider that judges nothing publishes —\n * `gkm dev` and the test mailbox — for a message stored at `objectKey`.\n */\nexport function unjudgedReceipt(options: {\n\tmessageId: string;\n\tsource: string;\n\trecipients: readonly string[];\n\tbucketName: string;\n\tobjectKey: string;\n\tverdicts?: Partial<Verdicts>;\n\ttimestamp?: Date;\n}): ReceiptNotification {\n\tconst at = (options.timestamp ?? new Date()).toISOString();\n\tconst status = (v: Verdict | undefined): ReceiptVerdict => ({\n\t\tstatus: v ? v.toUpperCase() : 'UNAVAILABLE',\n\t});\n\treturn {\n\t\tnotificationType: 'Received',\n\t\tmail: {\n\t\t\tmessageId: options.messageId,\n\t\t\ttimestamp: at,\n\t\t\tsource: options.source,\n\t\t\tdestination: [...options.recipients],\n\t\t},\n\t\treceipt: {\n\t\t\ttimestamp: at,\n\t\t\trecipients: [...options.recipients],\n\t\t\tspfVerdict: status(options.verdicts?.spf),\n\t\t\tdkimVerdict: status(options.verdicts?.dkim),\n\t\t\tdmarcVerdict: status(options.verdicts?.dmarc),\n\t\t\tspamVerdict: status(options.verdicts?.spam),\n\t\t\tvirusVerdict: status(options.verdicts?.virus),\n\t\t\taction: {\n\t\t\t\ttype: 'S3',\n\t\t\t\tbucketName: options.bucketName,\n\t\t\t\tobjectKey: options.objectKey,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/** An inbox, as the receiver routes to it. */\nexport interface ReceivingInbox {\n\tid: string;\n\taddressing: InboxAddressing;\n\t/** The stage's domain it receives on. */\n\tdomain: string;\n\t/** Announce a received message on the inbox's topic. */\n\tpublish(notification: ReceiptNotification): Promise<void>;\n}\n\n/** A message that arrived where a provider that judges nothing stores mail. */\nexport interface ArrivedMessage {\n\t/** Its key in that store — Mailpit's message id locally. */\n\tkey: string;\n\t/** Where the store is, as a notification names it: `mailpit`. */\n\tstore: string;\n\t/** The envelope sender. */\n\tfrom: string;\n\t/** The envelope recipients — never `To:`. */\n\trecipients: readonly string[];\n\t/** What a test says the provider judged; `'unavailable'` otherwise. */\n\tverdicts?: Partial<Verdicts>;\n}\n\n/**\n * Receive a message the way a receipt rule does: for each inbox one of its\n * envelope recipients is addressed to, publish the receipt notification for\n * those recipients on the inbox's topic. What no inbox receives at goes\n * nowhere — mail the app sent to anyone else included.\n *\n * The one receiver for every local path: Mailpit's webhook under `gkm dev`\n * and a local compose stack, and `mailbox.receive` in a feature test. SES is\n * the receiver deployed. Returns the ids of the inboxes it announced to.\n */\nexport async function receiveMail(\n\tmessage: ArrivedMessage,\n\tinboxes: readonly ReceivingInbox[],\n): Promise<string[]> {\n\tconst received: string[] = [];\n\tfor (const inbox of inboxes) {\n\t\tconst recipients = message.recipients.filter((address) =>\n\t\t\tinboxRecipient(address, inbox.addressing, inbox.domain),\n\t\t);\n\t\tif (recipients.length === 0) continue;\n\t\tawait inbox.publish(\n\t\t\tunjudgedReceipt({\n\t\t\t\tmessageId: message.key,\n\t\t\t\tsource: message.from,\n\t\t\t\trecipients,\n\t\t\t\tbucketName: message.store,\n\t\t\t\tobjectKey: message.key,\n\t\t\t\t...(message.verdicts ? { verdicts: message.verdicts } : {}),\n\t\t\t}),\n\t\t);\n\t\treceived.push(inbox.id);\n\t}\n\treturn received;\n}\n\n/** Whether `value` is an {@link Inbox}. */\nexport function isInbox(value: unknown): value is Inbox {\n\treturn value instanceof Inbox;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,IAAa,sBAAb,cAAyC,MAAM;CACzB;CAArB,YAAY,OAAwB;EACnC,MACC,cAAc,MAAM,+GAErB;EAJoB,KAAA,QAAA;EAKpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,sBAAb,cAAyC,MAAM;CAEpC;CACA;CAFV,YACC,OACA,SACC;EACD,MACC,cAAc,MAAM,WAAW,QAAQ,6IAGxC;EAPS,KAAA,QAAA;EACA,KAAA,UAAA;EAOT,KAAK,OAAO;CACb;AACD;;;;;AAMA,IAAa,+BAAb,cAAkD,MAAM;CAE7C;CACA;CAFV,YACC,OACA,QACC;EACD,MACC,cAAc,MAAM,8CAA8C,OAAO,4EAE1E;EANS,KA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,IAAI,cAC/B;CACA,OAAO;EACN,kBAAkB;EAClB,MAAM;GACL,WAAW,QAAQ;GACnB,WAAW;GACX,QAAQ,QAAQ;GAChB,aAAa,CAAC,GAAG,QAAQ,UAAU;EACpC;EACA,SAAS;GACR,WAAW;GACX,YAAY,CAAC,GAAG,QAAQ,UAAU;GAClC,YAAY,OAAO,QAAQ,UAAU,GAAG;GACxC,aAAa,OAAO,QAAQ,UAAU,IAAI;GAC1C,cAAc,OAAO,QAAQ,UAAU,KAAK;GAC5C,aAAa,OAAO,QAAQ,UAAU,IAAI;GAC1C,cAAc,OAAO,QAAQ,UAAU,KAAK;GAC5C,QAAQ;IACP,MAAM;IACN,YAAY,QAAQ;IACpB,WAAW,QAAQ;GACpB;EACD;CACD;AACD;;;;;;;;;;;AAoCA,eAAsB,YACrB,SACA,SACoB;CACpB,MAAM,WAAqB,CAAC;CAC5B,KAAK,MAAM,SAAS,SAAS;EAC5B,MAAM,aAAa,QAAQ,WAAW,QAAQ,YAC7C,eAAe,SAAS,MAAM,YAAY,MAAM,MAAM,CACvD;EACA,IAAI,WAAW,WAAW,GAAG;EAC7B,MAAM,MAAM,QACX,gBAAgB;GACf,WAAW,QAAQ;GACnB,QAAQ,QAAQ;GAChB;GACA,YAAY,QAAQ;GACpB,WAAW,QAAQ;GACnB,GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;EAC1D,CAAC,CACF;EACA,SAAS,KAAK,MAAM,EAAE;CACvB;CACA,OAAO;AACR;;AAGA,SAAgB,QAAQ,OAAgC;CACvD,OAAO,iBAAiB;AACzB"}
|
|
1
|
+
{"version":3,"file":"inbox.mjs","names":[],"sources":["../src/inbox.ts"],"sourcesContent":["/**\n * `Inbox` — mail received at addresses on the stage's domain, each message\n * handled in a worker.\n *\n * ```ts\n * export const requests = new Inbox('Requests', {\n * addresses: ['requests'], // local parts: structural\n * subdomains: true, // requests@<tenant>.<stage domain>\n * });\n *\n * export const onRequest = worker\n * .inbox(requests)\n * .handle(async ({ messages }) => {\n * for (const message of messages) {\n * message.recipient.subdomain; // the tenant, from the envelope\n * message.recipient.tag; // requests+<tag>@\n * }\n * });\n * ```\n *\n * **Its own bucket, and a topic.** An inbox owns the bucket its raw messages\n * are kept in — each target creates it for the inbox, never one the stack\n * already runs — and provides its URL itself, so the bucket is no `objects`\n * node and no object subscriber can be bound to it. It declares the topic\n * each message is announced on, which only the provider publishes to.\n *\n * **One decoder.** Deployed, SES's receipt rule stores the raw message and\n * publishes its receipt notification on the topic. Locally `gkm dev` brings a\n * message in from Mailpit and publishes the same notification; in a feature\n * test `mailbox.receive` does. The handler is handed what {@link InboxClient}\n * makes of that notification, wherever it came from.\n *\n * **The envelope routes.** Which inbox, which tenant and which tag come from\n * the envelope recipient, never from `From:` or `To:`, which the sender wrote.\n */\n\nimport { type ParsedEmail, parseEmail } from '@geekmidas/emailkit/inbound';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tINBOX_EVENT,\n\ttype InboxAddressing,\n\ttype InboxRecipient,\n\tinboxRecipient,\n\tprovidedKeyFor,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { createStorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Construct } from './construct-interface';\nimport { Topic } from './topic/Topic';\n\nexport interface InboxOptions {\n\t/**\n\t * The local parts it receives at: `['requests']`. Each also takes a\n\t * `+tag` — `requests+t_8f3k@` — handed to the handler as `recipient.tag`.\n\t */\n\taddresses: readonly string[];\n\t/**\n\t * Receive at `<address>@<label>.<domain>` — one label, a tenant's — rather\n\t * than at the stage's domain itself.\n\t */\n\tsubdomains?: boolean;\n}\n\n/** An inbox declared with no address receives nothing. */\nexport class InboxHasNoAddresses extends Error {\n\tconstructor(readonly inbox: string) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' names no address, so it would receive nothing. ` +\n\t\t\t\t`Name the local parts it receives at: addresses: ['requests'].`,\n\t\t);\n\t\tthis.name = 'InboxHasNoAddresses';\n\t}\n}\n\n/** An address that is not a bare local part: `requests@x`, `a+b`, `''`. */\nexport class InboxAddressInvalid extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly address: string,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' names '${address}', which is not a local part. ` +\n\t\t\t\t`Name only what goes before the @ — the domain is the stage's — ` +\n\t\t\t\t`and no '+': every address takes a +tag already.`,\n\t\t);\n\t\tthis.name = 'InboxAddressInvalid';\n\t}\n}\n\n/**\n * A receipt notification the inbox cannot read: not SES's shape, or an action\n * other than the S3 one that stores the message where the decoder reads it.\n */\nexport class ReceiptNotificationMalformed extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' was handed a notification it cannot read: ${reason}. ` +\n\t\t\t\t`It reads SES receipt notifications whose action stored the message in S3.`,\n\t\t);\n\t\tthis.name = 'ReceiptNotificationMalformed';\n\t}\n}\n\n/**\n * A provider's verdict on a message.\n *\n * `'unavailable'` where nothing judged it — locally, always — and never a\n * faked `'pass'`.\n */\nexport type Verdict = 'pass' | 'fail' | 'gray' | 'unavailable';\n\n/** What the provider judged of a message, which the message cannot say of itself. */\nexport interface Verdicts {\n\tspf: Verdict;\n\tdkim: Verdict;\n\tdmarc: Verdict;\n\tspam: Verdict;\n\tvirus: Verdict;\n}\n\n/**\n * One received message, for one recipient it was delivered to.\n *\n * `recipient` is the envelope's; every other address is a header, written by\n * the sender. Inbound mail is untrusted input: route on `recipient`, treat\n * `from` as a claim until `verdicts.dmarc` passes *and* the address is known,\n * sanitise `html`, and never use an attachment's filename as a key or path.\n */\nexport interface InboxMessage\n\textends Omit<ParsedEmail, 'attachments'>,\n\t\tPick<ParsedEmail, 'attachments'> {\n\trecipient: InboxRecipient;\n\t/**\n\t * Where the raw message is kept: the bucket SES stored it in (`mailpit`\n\t * locally), and its key there.\n\t */\n\traw: { bucket: string; key: string };\n\tverdicts: Verdicts;\n}\n\n/** A status as SES writes one: `PASS`, `FAIL`, `GRAY`, `PROCESSING_FAILED`, `DISABLED`. */\ninterface ReceiptVerdict {\n\tstatus: string;\n}\n\n/**\n * SES's receipt notification — the part an inbox reads.\n *\n * `gkm dev` and the test mailbox publish the same shape, with every verdict\n * `UNAVAILABLE`, so one decoder serves all three.\n */\nexport interface ReceiptNotification {\n\tnotificationType: 'Received';\n\tmail: {\n\t\tmessageId: string;\n\t\ttimestamp: string;\n\t\t/** The envelope sender (`MAIL FROM`). */\n\t\tsource: string;\n\t\tdestination: string[];\n\t};\n\treceipt: {\n\t\ttimestamp: string;\n\t\t/** The envelope recipients this receipt rule matched. */\n\t\trecipients: string[];\n\t\tspamVerdict?: ReceiptVerdict;\n\t\tvirusVerdict?: ReceiptVerdict;\n\t\tspfVerdict?: ReceiptVerdict;\n\t\tdkimVerdict?: ReceiptVerdict;\n\t\tdmarcVerdict?: ReceiptVerdict;\n\t\taction: {\n\t\t\ttype: string;\n\t\t\tbucketName?: string;\n\t\t\tobjectKey?: string;\n\t\t\ttopicArn?: string;\n\t\t};\n\t};\n}\n\n/** What the handler's inbox is: its domain, its raw messages, the decoder. */\nexport interface InboxClient {\n\t/** The stage's domain it receives on. */\n\treadonly domain: string;\n\t/** A raw message's bytes, by its key in the bucket. */\n\traw(key: string): Promise<Uint8Array>;\n\t/**\n\t * The messages a notification announces: one per envelope recipient this\n\t * inbox receives at, parsed. Empty when none is — a receipt rule that takes\n\t * a whole domain stores mail for addresses no inbox declared.\n\t */\n\tmessages(notification: ReceiptNotification): Promise<InboxMessage[]>;\n}\n\n/** A schema that takes a receipt notification as it is — SES wrote it, not the app. */\nconst RECEIPT_NOTIFICATION: StandardSchemaV1<ReceiptNotification> = {\n\t'~standard': {\n\t\tversion: 1,\n\t\tvendor: 'geekmidas',\n\t\tvalidate: (value) => ({ value: value as ReceiptNotification }),\n\t},\n};\n\ntype InboxTopic = Topic<string, { [INBOX_EVENT]: typeof RECEIPT_NOTIFICATION }>;\n\nexport class Inbox<TName extends string = string>\n\timplements Construct<TName, InboxClient>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, InboxClient>;\n\t/** Where each received message is announced. Published to by the provider only. */\n\treadonly topic: InboxTopic;\n\n\t/** The local parts it receives at, and whether on a tenant's subdomain. */\n\treadonly addressing: InboxAddressing;\n\tprivate readonly addresses: readonly string[];\n\tprivate readonly subdomains: boolean;\n\tprivate readonly keys: { url: string; domain: string };\n\n\tconstructor(name: ConstructName<TName>, options: InboxOptions) {\n\t\tconst canonical = canonicalId(name as string);\n\t\tif (options.addresses.length === 0) {\n\t\t\tthrow new InboxHasNoAddresses(canonical);\n\t\t}\n\t\tfor (const address of options.addresses) {\n\t\t\tif (!/^[a-z0-9][a-z0-9._-]*$/i.test(address)) {\n\t\t\t\tthrow new InboxAddressInvalid(canonical, address);\n\t\t\t}\n\t\t}\n\n\t\tthis.id = canonical as TName;\n\t\tthis.addresses = options.addresses.map((a) => a.toLowerCase());\n\t\tthis.subdomains = options.subdomains === true;\n\t\tthis.addressing = {\n\t\t\taddresses: this.addresses,\n\t\t\t...(this.subdomains ? { subdomains: true } : {}),\n\t\t};\n\t\tthis.keys = {\n\t\t\turl: providedKeyFor(canonical, 'inbox', 'url'),\n\t\t\tdomain: providedKeyFor(canonical, 'inbox', 'domain'),\n\t\t};\n\t\tthis.topic = new Topic(`${canonical}Mail`, {\n\t\t\tevents: { [INBOX_EVENT]: RECEIPT_NOTIFICATION },\n\t\t}) as InboxTopic;\n\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (register) => this.connect(register),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t...this.topic.declare(),\n\t\t\t{\n\t\t\t\tkind: 'inbox',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.keys.url, this.keys.domain],\n\t\t\t\taddresses: this.addresses,\n\t\t\t\t...(this.subdomains ? { subdomains: true } : {}),\n\t\t\t\ttopic: this.topic.id,\n\t\t\t},\n\t\t];\n\t}\n\n\tprivate async connect(\n\t\tregister: ServiceRegisterOptions,\n\t): Promise<InboxClient> {\n\t\tconst { url, domain } = register.envParser\n\t\t\t.create((get) => ({\n\t\t\t\turl: get(this.keys.url).string(),\n\t\t\t\tdomain: get(this.keys.domain).string(),\n\t\t\t}))\n\t\t\t.parse();\n\t\tconst read = rawReader(url);\n\t\tconst addressing = {\n\t\t\taddresses: this.addresses,\n\t\t\tsubdomains: this.subdomains,\n\t\t};\n\t\tconst inbox = this.id;\n\n\t\tconst raw = async (key: string): Promise<Uint8Array> => {\n\t\t\tconst response = await fetch(await read(key));\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new RawMessageUnreadable(inbox, key, response.status);\n\t\t\t}\n\t\t\treturn new Uint8Array(await response.arrayBuffer());\n\t\t};\n\n\t\treturn {\n\t\t\tdomain,\n\t\t\traw,\n\t\t\tasync messages(notification) {\n\t\t\t\tconst { receipt } = assertReceipt(inbox, notification);\n\t\t\t\tconst recipients = receipt.recipients.flatMap((address) => {\n\t\t\t\t\tconst recipient = inboxRecipient(address, addressing, domain);\n\t\t\t\t\treturn recipient ? [recipient] : [];\n\t\t\t\t});\n\t\t\t\tif (recipients.length === 0) return [];\n\n\t\t\t\tconst key = receipt.action.objectKey!;\n\t\t\t\tconst parsed = await parseEmail(await raw(key));\n\t\t\t\tconst verdicts = verdictsOf(receipt);\n\t\t\t\treturn recipients.map((recipient) => ({\n\t\t\t\t\t...parsed,\n\t\t\t\t\trecipient,\n\t\t\t\t\traw: { bucket: receipt.action.bucketName!, key },\n\t\t\t\t\tverdicts,\n\t\t\t\t}));\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * Where a raw message is read from, by its key, for the store `url` names:\n * an `s3://` bucket deployed — SES stored it at `messages/<id>` — or, locally,\n * Mailpit's API, which keeps every message it receives under its own id.\n *\n * The one place local and deployed differ; everything that reads a message\n * goes through it.\n */\nfunction rawReader(url: string): (key: string) => Promise<string> {\n\tif (url.startsWith('s3:')) {\n\t\tconst bucket = createStorageClient(url);\n\t\treturn async (key) => (await bucket).getDownloadURL({ path: key });\n\t}\n\tconst base = url.replace(/\\/+$/, '');\n\treturn async (key) => `${base}/api/v1/message/${encodeURIComponent(key)}/raw`;\n}\n\n/** The raw message a notification names could not be read from its store. */\nexport class RawMessageUnreadable extends Error {\n\tconstructor(\n\t\treadonly inbox: string,\n\t\treadonly key: string,\n\t\treadonly status: number,\n\t) {\n\t\tsuper(\n\t\t\t`The inbox '${inbox}' could not read its raw message '${key}' (HTTP ${status}). ` +\n\t\t\t\t`It is written by the receipt rule before the notification is sent; ` +\n\t\t\t\t`check the bucket's policy lets the process that runs the handler read it.`,\n\t\t);\n\t\tthis.name = 'RawMessageUnreadable';\n\t}\n}\n\nfunction assertReceipt(inbox: string, value: unknown): ReceiptNotification {\n\tconst notification = value as Partial<ReceiptNotification> | undefined;\n\tif (notification?.notificationType !== 'Received') {\n\t\tthrow new ReceiptNotificationMalformed(\n\t\t\tinbox,\n\t\t\t`its notificationType is '${String(notification?.notificationType)}', not 'Received'`,\n\t\t);\n\t}\n\tconst action = notification.receipt?.action;\n\tif (action?.type !== 'S3' || !action.objectKey || !action.bucketName) {\n\t\tthrow new ReceiptNotificationMalformed(\n\t\t\tinbox,\n\t\t\t`its action is '${String(action?.type)}' without an S3 object`,\n\t\t);\n\t}\n\tif (!Array.isArray(notification.receipt?.recipients)) {\n\t\tthrow new ReceiptNotificationMalformed(inbox, 'it names no recipients');\n\t}\n\treturn notification as ReceiptNotification;\n}\n\nfunction verdict(status: ReceiptVerdict | undefined): Verdict {\n\tswitch (status?.status) {\n\t\tcase 'PASS':\n\t\t\treturn 'pass';\n\t\tcase 'FAIL':\n\t\t\treturn 'fail';\n\t\tcase 'GRAY':\n\t\t\treturn 'gray';\n\t\tdefault:\n\t\t\treturn 'unavailable';\n\t}\n}\n\nfunction verdictsOf(receipt: ReceiptNotification['receipt']): Verdicts {\n\treturn {\n\t\tspf: verdict(receipt.spfVerdict),\n\t\tdkim: verdict(receipt.dkimVerdict),\n\t\tdmarc: verdict(receipt.dmarcVerdict),\n\t\tspam: verdict(receipt.spamVerdict),\n\t\tvirus: verdict(receipt.virusVerdict),\n\t};\n}\n\n/**\n * The receipt notification a provider that judges nothing publishes —\n * `gkm dev` and the test mailbox — for a message stored at `objectKey`.\n */\nexport function unjudgedReceipt(options: {\n\tmessageId: string;\n\tsource: string;\n\trecipients: readonly string[];\n\tbucketName: string;\n\tobjectKey: string;\n\tverdicts?: Partial<Verdicts>;\n\ttimestamp?: Date;\n}): ReceiptNotification {\n\tconst at = (options.timestamp ?? new Date()).toISOString();\n\tconst status = (v: Verdict | undefined): ReceiptVerdict => ({\n\t\tstatus: v ? v.toUpperCase() : 'UNAVAILABLE',\n\t});\n\treturn {\n\t\tnotificationType: 'Received',\n\t\tmail: {\n\t\t\tmessageId: options.messageId,\n\t\t\ttimestamp: at,\n\t\t\tsource: options.source,\n\t\t\tdestination: [...options.recipients],\n\t\t},\n\t\treceipt: {\n\t\t\ttimestamp: at,\n\t\t\trecipients: [...options.recipients],\n\t\t\tspfVerdict: status(options.verdicts?.spf),\n\t\t\tdkimVerdict: status(options.verdicts?.dkim),\n\t\t\tdmarcVerdict: status(options.verdicts?.dmarc),\n\t\t\tspamVerdict: status(options.verdicts?.spam),\n\t\t\tvirusVerdict: status(options.verdicts?.virus),\n\t\t\taction: {\n\t\t\t\ttype: 'S3',\n\t\t\t\tbucketName: options.bucketName,\n\t\t\t\tobjectKey: options.objectKey,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/** An inbox, as the receiver routes to it. */\nexport interface ReceivingInbox {\n\tid: string;\n\taddressing: InboxAddressing;\n\t/** The stage's domain it receives on. */\n\tdomain: string;\n\t/** Announce a received message on the inbox's topic. */\n\tpublish(notification: ReceiptNotification): Promise<void>;\n}\n\n/** A message that arrived where a provider that judges nothing stores mail. */\nexport interface ArrivedMessage {\n\t/** Its key in that store — Mailpit's message id locally. */\n\tkey: string;\n\t/** Where the store is, as a notification names it: `mailpit`. */\n\tstore: string;\n\t/** The envelope sender. */\n\tfrom: string;\n\t/** The envelope recipients — never `To:`. */\n\trecipients: readonly string[];\n\t/** What a test says the provider judged; `'unavailable'` otherwise. */\n\tverdicts?: Partial<Verdicts>;\n}\n\n/**\n * Receive a message the way a receipt rule does: for each inbox one of its\n * envelope recipients is addressed to, publish the receipt notification for\n * those recipients on the inbox's topic. What no inbox receives at goes\n * nowhere — mail the app sent to anyone else included.\n *\n * The one receiver for every local path: Mailpit's webhook under `gkm dev`\n * and a local compose stack, and `mailbox.receive` in a feature test. SES is\n * the receiver deployed. Returns the ids of the inboxes it announced to.\n */\nexport async function receiveMail(\n\tmessage: ArrivedMessage,\n\tinboxes: readonly ReceivingInbox[],\n): Promise<string[]> {\n\tconst received: string[] = [];\n\tfor (const inbox of inboxes) {\n\t\tconst recipients = message.recipients.filter((address) =>\n\t\t\tinboxRecipient(address, inbox.addressing, inbox.domain),\n\t\t);\n\t\tif (recipients.length === 0) continue;\n\t\tawait inbox.publish(\n\t\t\tunjudgedReceipt({\n\t\t\t\tmessageId: message.key,\n\t\t\t\tsource: message.from,\n\t\t\t\trecipients,\n\t\t\t\tbucketName: message.store,\n\t\t\t\tobjectKey: message.key,\n\t\t\t\t...(message.verdicts ? { verdicts: message.verdicts } : {}),\n\t\t\t}),\n\t\t);\n\t\treceived.push(inbox.id);\n\t}\n\treturn received;\n}\n\n/** Whether `value` is an {@link Inbox}. */\nexport function isInbox(value: unknown): value is Inbox {\n\treturn value instanceof Inbox;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,IAAa,sBAAb,cAAyC,MAAM;CACzB;CAArB,YAAY,OAAwB;EACnC,MACC,cAAc,MAAM,+GAErB;EAJoB,KAAA,QAA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AS,KAAK,MAAM,EAAE;CACvB;CACA,OAAO;AACR;;AAGA,SAAgB,QAAQ,OAAgC;CACvD,OAAO,iBAAiB;AACzB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as onShutdown } from "./shutdown-C7xa8x9S.mjs";
|
|
2
2
|
import { Cache } from "./cache.mjs";
|
|
3
|
-
import { DEFAULT_POSTGRES_VERSION, canonicalId,
|
|
3
|
+
import { DEFAULT_POSTGRES_VERSION, canonicalId, providedKeyFor, serviceKey } from "@geekmidas/manifest";
|
|
4
4
|
import { currentRequestContext } from "@geekmidas/services";
|
|
5
5
|
import { SpanKind, SpanStatusCode, context, isSpanContextValid, trace } from "@opentelemetry/api";
|
|
6
6
|
import { Kysely, PostgresDialect } from "kysely";
|
|
@@ -229,8 +229,8 @@ var KyselyDatabase = class KyselyDatabase {
|
|
|
229
229
|
const canonical = canonicalId(id);
|
|
230
230
|
this.id = canonical;
|
|
231
231
|
this.config = {
|
|
232
|
-
url:
|
|
233
|
-
ownerUrl:
|
|
232
|
+
url: providedKeyFor(canonical, "database", "url"),
|
|
233
|
+
ownerUrl: providedKeyFor(canonical, "database", "ownerUrl")
|
|
234
234
|
};
|
|
235
235
|
this.schemaName = options.schema ?? DEFAULT_SCHEMA;
|
|
236
236
|
this.roles = options.roles ?? true;
|
|
@@ -368,4 +368,4 @@ var KyselyDatabase = class KyselyDatabase {
|
|
|
368
368
|
//#endregion
|
|
369
369
|
export { closeDatabasePools as n, KyselyDatabase as t };
|
|
370
370
|
|
|
371
|
-
//# sourceMappingURL=kysely-
|
|
371
|
+
//# sourceMappingURL=kysely-Bc9xzaik.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kysely-Bc9xzaik.mjs","names":[],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"sourcesContent":["/**\n * The `pg` pools a database construct opens, and what every one of them gets:\n *\n * - **A name.** `application_name` is what `pg_stat_activity` shows beside a\n * connection. Without one, a database at `max_connections` cannot say who\n * holds them. It is a *fallback*, so `PGAPPNAME` or `?application_name=` in\n * the URL still win.\n * - **Tagged queries.** Inside a request, each query ends in a comment naming\n * what ran it — `/*operation='POST /orders',request_id='…'*\\/` — in the\n * sqlcommenter form, and inside a trace the query's own span as\n * `traceparent='00-<trace>-<span>-<flags>'`. It shows in\n * `pg_stat_activity.query`, in the server's slow-query and `auto_explain`\n * logs, and costs no round trip; `pg_stat_statements` ignores comments, so\n * its grouping is unchanged.\n * - **A listener for idle-client errors.** When the server ends an idle\n * connection (`idle_session_timeout`, a failover, an admin), the pool emits\n * `'error'`. With no listener that is an uncaught exception that kills the\n * process — for a client the pool has already discarded.\n * - **A span per query.** Through the global OpenTelemetry tracer, so a no-op\n * without a provider. `pg` is bundled into a production entry, where no\n * instrumentation can hook its module load — so the client is wrapped here,\n * as the tags are. See {@link traceQueries}.\n * - **A way to close.** {@link closeDatabasePools} ends every pool opened, so a\n * server shutting down releases its connections instead of holding them\n * until the process dies.\n */\n\nimport { currentRequestContext } from '@geekmidas/services';\nimport {\n\ttype Attributes,\n\tcontext,\n\tisSpanContextValid,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\nimport pg from 'pg';\nimport { onShutdown } from '../shutdown';\n\nexport interface DatabasePoolOptions {\n\t/** Tag queries with what ran them and the trace they ran in. Default true. */\n\tqueryTags?: boolean;\n}\n\n/** The longest statement text a query span carries. */\nexport const MAX_STATEMENT_LENGTH = 2048;\n\n/** Every pool opened and not yet closed, so a shutdown can end them all. */\nconst open = new Set<pg.Pool>();\nonShutdown(() => closeDatabasePools());\n\n/**\n * A pool for one URL, with its schema actually on the search path.\n *\n * `?search_path=` is not a libpq parameter — a URL carrying it connects\n * happily and then resolves every unqualified name against `public`, which is\n * how a schema tenant silently writes its tables into the database it was\n * separated from. Postgres takes it as a startup option instead, so the URL\n * keeps the readable form the target derives and this turns it into the thing\n * the server understands.\n */\nexport function openPool(\n\turl: string,\n\toptions: DatabasePoolOptions = {},\n): pg.Pool {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\tparsed.searchParams.delete('search_path');\n\n\tconst pool = new pg.Pool({\n\t\tconnectionString: parsed.toString(),\n\t\t...(searchPath ? { options: `-c search_path=${searchPath}` } : {}),\n\t\tfallback_application_name: applicationName(),\n\t});\n\n\tpool.on('error', (error) => {\n\t\tconst logger = currentRequestContext()?.logger;\n\t\tif (logger) logger.warn({ err: error }, 'Idle database connection lost');\n\t\telse console.warn('Idle database connection lost:', error.message);\n\t});\n\tconst target = connectionAttributes(parsed);\n\tpool.on('connect', (client) => {\n\t\t// Tags first, so the span wraps them: it records the statement as the\n\t\t// application wrote it rather than with the comment on the end, and it\n\t\t// is the active span when the tag is written — so the `traceparent` a\n\t\t// query carries names the query's own span.\n\t\tif (options.queryTags !== false) tagQueries(client);\n\t\ttraceQueries(client, target);\n\t});\n\n\topen.add(pool);\n\tconst end = pool.end.bind(pool);\n\tpool.end = (async () => {\n\t\topen.delete(pool);\n\t\tawait end();\n\t}) as typeof pool.end;\n\n\treturn pool;\n}\n\n/**\n * End every pool opened, waiting for checked-out connections to come back.\n * For a server's shutdown, after it has stopped taking requests.\n */\nexport async function closeDatabasePools(): Promise<void> {\n\tawait Promise.all([...open].map((pool) => pool.end()));\n}\n\n/**\n * Who this process is, as Postgres will show it: the Lambda function, else the\n * app — `GKM_APP_NAME` where an entry sets it, `gkm dev`'s app tag otherwise.\n * Postgres keeps 63 bytes of it.\n */\nexport function applicationName(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\treturn (\n\t\tenv.AWS_LAMBDA_FUNCTION_NAME ||\n\t\tenv.GKM_APP_NAME ||\n\t\tenv.GKM_DEV_APP?.split('#').pop() ||\n\t\tundefined\n\t);\n}\n\n/**\n * The comment that says what ran a query: the request's operation and id, and\n * the active span as a W3C `traceparent` — the query's own span when it runs\n * through a traced client, since the span wraps the tagging. '' with neither.\n *\n * The keys are in sqlcommenter's sorted order. Values keep only characters\n * that cannot end a comment or a quoted value — `*` and `'` among those\n * dropped — so a route cannot inject SQL through it.\n */\nexport function queryTag(): string {\n\tconst request = currentRequestContext();\n\tconst span = trace.getActiveSpan()?.spanContext();\n\n\tconst tags = [\n\t\t['operation', request?.operation],\n\t\t['request_id', request?.requestId],\n\t\t['traceparent', span && isSpanContextValid(span) ? traceparent(span) : ''],\n\t].filter((tag): tag is [string, string] => Boolean(tag[1]));\n\tif (tags.length === 0) return '';\n\n\tconst clean = (value: string) => value.replace(/[^\\w ./:{}@-]/g, '');\n\treturn ` /*${tags.map(([key, value]) => `${key}='${clean(value)}'`).join(',')}*/`;\n}\n\n/** A span as W3C trace context's `traceparent`, version 00. */\nfunction traceparent(span: {\n\ttraceId: string;\n\tspanId: string;\n\ttraceFlags: number;\n}): string {\n\tconst flags = (span.traceFlags & 0xff).toString(16).padStart(2, '0');\n\treturn `00-${span.traceId}-${span.spanId}-${flags}`;\n}\n\n/**\n * Append {@link queryTag} to everything `client` runs: a SQL string — what\n * Kysely sends — or a query object such as a cursor's.\n */\nfunction tagQueries(client: pg.PoolClient): void {\n\tconst query = client.query.bind(client) as (...args: unknown[]) => unknown;\n\tclient.query = ((first: unknown, ...rest: unknown[]) => {\n\t\tconst tag = queryTag();\n\t\tif (tag && typeof first === 'string') return query(first + tag, ...rest);\n\t\tif (\n\t\t\ttag &&\n\t\t\tfirst &&\n\t\t\ttypeof first === 'object' &&\n\t\t\ttypeof (first as { text?: unknown }).text === 'string'\n\t\t) {\n\t\t\tconst config = first as { text: string };\n\t\t\tconfig.text += tag;\n\t\t}\n\t\treturn query(first, ...rest);\n\t}) as typeof client.query;\n}\n\n/** What every span of one pool says about where it connects. */\nfunction connectionAttributes(url: URL): Attributes {\n\tconst name = decodeURIComponent(url.pathname.slice(1));\n\treturn {\n\t\t'db.system': 'postgresql',\n\t\t...(name && { 'db.name': name }),\n\t\t'server.address': url.hostname,\n\t\t'server.port': Number(url.port || 5432),\n\t};\n}\n\nconst TRACER = '@geekmidas/constructs';\n\n/** `select`, `insert`, … — the first keyword, or `with`'s main statement. */\nconst OPERATION = /^\\s*(?:\\/\\*.*?\\*\\/\\s*)?(\\w+)/s;\n/** The table a statement is about, when it names one where it usually does. */\nconst TABLE =\n\t/\\b(?:from|into|update|join)\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i;\n\n/**\n * What a statement does and to which table, parsed cheaply from its first\n * characters: `select \"orders\"`, `insert \"public\".\"users\"`. A statement the\n * patterns cannot read leaves `table` unset.\n */\nexport function describeStatement(text: string): {\n\toperation?: string;\n\ttable?: string;\n} {\n\tconst head = text.length > 512 ? text.slice(0, 512) : text;\n\tconst operation = OPERATION.exec(head)?.[1]?.toLowerCase();\n\tconst table = TABLE.exec(head)?.[1]?.replace(/\"/g, '');\n\treturn {\n\t\t...(operation && { operation }),\n\t\t...(table && { table }),\n\t};\n}\n\n/**\n * A span around everything `client` runs — `<operation> <table>`, or\n * `db.query` when the statement does not say.\n *\n * The statement text goes on the span only for a parameterized query — values\n * passed separately, as Kysely always does — and truncated. Parameter values\n * never do. A bare string with no values could hold anything a caller\n * concatenated into it, so it gets no text at all.\n */\nfunction traceQueries(client: pg.PoolClient, connection: Attributes): void {\n\tconst query = client.query.bind(client) as (...args: unknown[]) => unknown;\n\tclient.query = ((first: unknown, ...rest: unknown[]) => {\n\t\tconst config =\n\t\t\tfirst && typeof first === 'object'\n\t\t\t\t? (first as { text?: unknown; values?: unknown })\n\t\t\t\t: undefined;\n\t\tconst text =\n\t\t\ttypeof first === 'string'\n\t\t\t\t? first\n\t\t\t\t: typeof config?.text === 'string'\n\t\t\t\t\t? config.text\n\t\t\t\t\t: undefined;\n\t\tconst values = typeof first === 'string' ? rest[0] : config?.values;\n\t\tconst { operation, table } = text ? describeStatement(text) : {};\n\n\t\tconst span = trace\n\t\t\t.getTracer(TRACER)\n\t\t\t.startSpan(operation && table ? `${operation} ${table}` : 'db.query', {\n\t\t\t\tkind: SpanKind.CLIENT,\n\t\t\t\tattributes: {\n\t\t\t\t\t...connection,\n\t\t\t\t\t...(operation && { 'db.operation': operation }),\n\t\t\t\t\t...(table && { 'db.sql.table': table }),\n\t\t\t\t\t...(text &&\n\t\t\t\t\t\tArray.isArray(values) && {\n\t\t\t\t\t\t\t'db.statement':\n\t\t\t\t\t\t\t\ttext.length > MAX_STATEMENT_LENGTH\n\t\t\t\t\t\t\t\t\t? text.slice(0, MAX_STATEMENT_LENGTH)\n\t\t\t\t\t\t\t\t\t: text,\n\t\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t});\n\t\tconst end = (error?: unknown) => {\n\t\t\tif (error) {\n\t\t\t\tif (error instanceof Error) span.recordException(error);\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t}\n\t\t\tspan.end();\n\t\t};\n\n\t\t// A callback, as `pg`'s own callback form takes it.\n\t\tconst last = rest[rest.length - 1];\n\t\tif (typeof last === 'function') {\n\t\t\tconst args = [...rest];\n\t\t\targs[args.length - 1] = (error: unknown, ...result: unknown[]) => {\n\t\t\t\tend(error);\n\t\t\t\treturn (last as (...a: unknown[]) => unknown)(error, ...result);\n\t\t\t};\n\t\t\treturn context.with(trace.setSpan(context.active(), span), () =>\n\t\t\t\tquery(first, ...args),\n\t\t\t);\n\t\t}\n\n\t\tlet result: unknown;\n\t\ttry {\n\t\t\tresult = context.with(trace.setSpan(context.active(), span), () =>\n\t\t\t\tquery(first, ...rest),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tend(error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\t\t(result as Promise<unknown>).then(\n\t\t\t\t() => end(),\n\t\t\t\t(error) => end(error),\n\t\t\t);\n\t\t} else if (\n\t\t\tresult &&\n\t\t\ttypeof (result as { once?: unknown }).once === 'function'\n\t\t) {\n\t\t\t// A submittable — a cursor or a stream — ends when it says so.\n\t\t\tconst emitter = result as {\n\t\t\t\tonce(event: string, fn: (e?: unknown) => void): void;\n\t\t\t};\n\t\t\temitter.once('end', () => end());\n\t\t\temitter.once('error', (error) => end(error));\n\t\t} else {\n\t\t\tend();\n\t\t}\n\t\treturn result;\n\t}) as typeof client.query;\n}\n","/**\n * `KyselyDatabase` — a declared Postgres database, typed by its schema.\n *\n * It declares a logical database, a schema, and the roles that reach it, and\n * hands back a Kysely client built from the one URL the adapter supplied. It\n * names no cloud: `--target=aws` fills that URL from RDS, local dev from the\n * Postgres container.\n *\n * Transactions and RLS context are the execution wrapper's job — it opens the\n * transaction and puts it in `ctx.db`. This construct does not resolve\n * connections per request.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\tDEFAULT_POSTGRES_VERSION,\n\ttype Declaration,\n\ttype PostgresVersion,\n\tprovidedKeyFor,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { Kysely, type KyselyConfig, PostgresDialect } from 'kysely';\nimport { Cache } from '../cache';\nimport type { Construct } from '../construct-interface';\nimport { openPool } from './pool';\n\n/** The schema a database uses when it does not say otherwise. */\nconst DEFAULT_SCHEMA = 'app';\n\n/**\n * Everything Kysely takes, plus what this construct declares.\n *\n * `dialect` is omitted because the construct owns it — it is built from the one\n * URL the adapter supplied, which is the whole point of the construct. The rest\n * of `KyselyConfig` (`plugins`, `log`) is the app's business and passes\n * straight through, so anything Kysely adds later arrives without being\n * tracked here.\n */\ninterface KyselyDatabaseBaseOptions extends Omit<KyselyConfig, 'dialect'> {\n\t/**\n\t * The schema, pinned on both roles' `search_path`.\n\t *\n\t * Defaults to `app` — the role the schema plays, rather than a restatement\n\t * of the database's own name, which reads correctly beside `auth` and\n\t * `pgboss` and keeps the application off `public`.\n\t */\n\tschema?: string;\n\t/**\n\t * Provision the owner/runtime role split. Defaults to on.\n\t *\n\t * Off falls back to the cluster's master credential in both URLs, giving up\n\t * the DDL/DML split and putting credentials that can drop a table into the\n\t * function's environment. A deliberate downgrade, not a default.\n\t */\n\troles?: boolean;\n\t/**\n\t * Extensions to create in this database, as the cluster master, before the\n\t * first migration — for the ones the owner role a migration runs as may not\n\t * create (PostGIS is not a trusted extension). They are created in\n\t * `public`, which joins this database's roles' `search_path`, so their\n\t * types resolve unqualified.\n\t *\n\t * Only attempted: the image has to ship them.\n\t */\n\textensions?: readonly string[];\n\t/**\n\t * End each query run inside a request with a comment naming what ran it —\n\t * `/*operation='POST /orders',request_id='…'*\\/` — so `pg_stat_activity`\n\t * and the server's logs can tie a query to its endpoint — and, inside a\n\t * trace, with the query span's `traceparent='00-…'` (sqlcommenter), so\n\t * they can tie it to the trace too. Defaults to on.\n\t */\n\tqueryTags?: boolean;\n}\n\n/**\n * Which Postgres the database runs: a major on the stock image, or an image\n * the project names. One or the other, never both — an image's tag already\n * says its major, and a second statement of it is one that can disagree.\n */\nexport type PostgresRuntime =\n\t| {\n\t\t\t/**\n\t\t\t * The Postgres major version to provision, on the stock image.\n\t\t\t *\n\t\t\t * Declared here so one statement reaches every target. It was\n\t\t\t * previously set in two unrelated places — a container tag locally,\n\t\t\t * nothing at all on AWS (so Aurora chose) — which is how local came to\n\t\t\t * run 18 while deployed ran 17.7 with nothing recording the difference.\n\t\t\t *\n\t\t\t * Defaults to {@link DEFAULT_POSTGRES_VERSION}.\n\t\t\t */\n\t\t\tversion?: PostgresVersion;\n\t\t\timage?: never;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * The container image to run, wherever a target runs one (local,\n\t\t\t * Dokploy), in place of `postgres:<version>`.\n\t\t\t *\n\t\t\t * Yours to choose and used as written: its tag is the major, and it\n\t\t\t * should ship every extension in `extensions`. AWS runs RDS, ignores\n\t\t\t * it, and provisions {@link DEFAULT_POSTGRES_VERSION}.\n\t\t\t *\n\t\t\t * ```ts\n\t\t\t * new KyselyDatabase<GeoDB>('Geo', {\n\t\t\t * image: 'postgis/postgis:18-3.6-alpine',\n\t\t\t * extensions: ['postgis'],\n\t\t\t * });\n\t\t\t * ```\n\t\t\t */\n\t\t\timage: string;\n\t\t\tversion?: never;\n\t };\n\n/**\n * Everything Kysely takes, plus what this construct declares — including\n * which Postgres it runs, as a version or an image.\n */\nexport type KyselyDatabaseOptions = KyselyDatabaseBaseOptions & PostgresRuntime;\n\n/** What makes a construct derived rather than a database in its own right. */\ninterface DerivedFrom {\n\tkind: 'database-reader' | 'database-schema';\n\tof: string;\n\tschema?: string;\n}\n\n/**\n * @typeParam DB - the database's schema.\n * @typeParam TName - the canonical id. TypeScript has no partial\n * type-argument inference, so `new KyselyDatabase<OrdersDB>('orders')` leaves\n * this at its default and the service key widens to `string`. `db` still types\n * through `.database()`, which infers from the service.\n */\nexport class KyselyDatabase<DB = unknown, TName extends string = string>\n\timplements Construct<TName, Kysely<DB>>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, Kysely<DB>>;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the key the\n\t * build publishes and the key the client reads cannot drift.\n\t */\n\tprivate readonly config: { url: string; ownerUrl: string };\n\tprivate readonly schemaName: string;\n\tprivate readonly roles: boolean;\n\tprivate readonly runtime: { version: PostgresVersion } | { image: string };\n\tprivate readonly derivedFrom?: DerivedFrom;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: KyselyDatabaseOptions = {},\n\t\tderivedFrom?: DerivedFrom,\n\t) {\n\t\t// Canonicalises, so `orders` and `Orders` are one construct rather than\n\t\t// two that collide. Throws on anything that cannot become a valid id.\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.config = {\n\t\t\turl: providedKeyFor(canonical, 'database', 'url'),\n\t\t\townerUrl: providedKeyFor(canonical, 'database', 'ownerUrl'),\n\t\t};\n\t\tthis.schemaName = options.schema ?? DEFAULT_SCHEMA;\n\t\tthis.roles = options.roles ?? true;\n\t\tthis.runtime = options.image\n\t\t\t? { image: options.image }\n\t\t\t: { version: options.version ?? DEFAULT_POSTGRES_VERSION };\n\t\tthis.derivedFrom = derivedFrom;\n\n\t\t// A field, not a getter: service discovery caches by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\t// Forwards the whole options object — cherry-picking `envParser` strips\n\t\t\t// `context` and with it the request-scoped logger.\n\t\t\tregister: (registerOptions) => this.connect(registerOptions),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\tif (this.derivedFrom) {\n\t\t\tconst { kind, of, schema } = this.derivedFrom;\n\n\t\t\treturn [\n\t\t\t\tkind === 'database-schema'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tid: this.id,\n\t\t\t\t\t\t\tof,\n\t\t\t\t\t\t\tschema: schema ?? this.schemaName,\n\t\t\t\t\t\t\t// The runtime key alone — see the note below on the parent.\n\t\t\t\t\t\t\tprovides: [this.config.url],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tid: this.id,\n\t\t\t\t\t\t\tof,\n\t\t\t\t\t\t\t// A reader has no owner URL of its own — nothing migrates\n\t\t\t\t\t\t\t// through a read-only endpoint — so this is the one key.\n\t\t\t\t\t\t\tprovides: [this.config.url],\n\t\t\t\t\t\t},\n\t\t\t];\n\t\t}\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'database',\n\t\t\t\tid: this.id,\n\t\t\t\tengine: 'postgres',\n\t\t\t\tschema: this.schemaName,\n\t\t\t\t// A version, or the image whose tag is one — never both.\n\t\t\t\t...this.runtime,\n\t\t\t\t...(this.options.extensions?.length\n\t\t\t\t\t? { extensions: [...new Set(this.options.extensions)] }\n\t\t\t\t\t: {}),\n\t\t\t\t// One key, the runtime role's. `config` also holds the owner key and\n\t\t\t\t// it is deliberately absent here: a key in `provides` is a key an\n\t\t\t\t// edge can name, and nothing should be able to depend on DDL rights.\n\t\t\t\tprovides: [this.config.url],\n\t\t\t\t...(this.roles ? {} : { roles: false }),\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * A read-only endpoint on this database.\n\t *\n\t * Read-only is enforced by the reader role's grants rather than by which\n\t * endpoint it resolves to, so falling back to the writer where no replica\n\t * exists is safe rather than a silently writable connection behind a name\n\t * that says reader. There is no `writer()`: the database *is* the writer, so\n\t * a replica can never be reached by accident.\n\t *\n\t * The return type is narrower than this class on purpose — see\n\t * {@link ReadOnlyDatabase}.\n\t */\n\treader(): ReadOnlyDatabase<DB, `${TName}Reader`> {\n\t\treturn new KyselyDatabase<DB, `${TName}Reader`>(\n\t\t\t`${this.id}Reader` as ConstructName<`${TName}Reader`>,\n\t\t\tthis.options,\n\t\t\t{ kind: 'database-reader', of: this.id },\n\t\t);\n\t}\n\n\t/**\n\t * A cache that lives in this database.\n\t *\n\t * The same strengthening `schema()` is over a second database: `new\n\t * Cache('Sessions')` says the app caches and leaves where to the deployment,\n\t * while this says it caches *here* — which is a fact about the application\n\t * and so belongs in its code.\n\t *\n\t * What it buys beyond being explicit: the table's schema and the role that\n\t * reaches it come from this database rather than from a second convention,\n\t * and the backend no longer has to guess which database \"the database\" meant\n\t * when an app declares two.\n\t *\n\t * A cache is not a `KyselyDatabase`, so this returns a `Cache` — the client\n\t * is a key/value store, not a query builder, and typing it as the parent\n\t * would be a convenience that lies.\n\t */\n\tcache<TCache extends string = `${TName}Cache`>(\n\t\tid: ConstructName<TCache> = `${this.id}Cache` as ConstructName<TCache>,\n\t\toptions: { table?: string } = {},\n\t): Cache<TCache> {\n\t\treturn new Cache<TCache>(id, {\n\t\t\tof: this.id,\n\t\t\t...(options.table ? { table: options.table } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * A second schema in this database, with its own role(s) and its own URL —\n\t * so this database's role holds no grant on those tables at all.\n\t *\n\t * Typed separately because a tenant has its own tables: the point is that\n\t * `auth.selectFrom('sessions')` type-checks and\n\t * `orders.selectFrom('sessions')` does not.\n\t */\n\tschema<TenantDB, TTenant extends string>(\n\t\tid: ConstructName<TTenant>,\n\t\toptions: KyselyDatabaseOptions = {},\n\t): KyselyDatabase<TenantDB, TTenant> {\n\t\treturn new KyselyDatabase<TenantDB, TTenant>(id, options, {\n\t\t\tkind: 'database-schema',\n\t\t\tof: this.id,\n\t\t\tschema: options.schema ?? (id as string).toLowerCase(),\n\t\t});\n\t}\n\n\t/**\n\t * A connection as the *owner* role — the one that may create, alter and drop.\n\t *\n\t * A `Service` rather than part of the construct, and deliberately so: a\n\t * construct is what `.dependsOn()` accepts, and nothing should be able to\n\t * depend on this. A migrator asks for it by name; a handler cannot ask at\n\t * all, which is the security property the role split exists for.\n\t *\n\t * Falls back to the runtime URL where no owner URL was published — the\n\t * `roles: false` downgrade, where there is only one credential and it is the\n\t * cluster master's.\n\t */\n\tget owner(): Service<`${Uncapitalize<TName>}Owner`, Kysely<DB>> {\n\t\treturn {\n\t\t\tserviceName:\n\t\t\t\t`${serviceKey(this.id)}Owner` as `${Uncapitalize<TName>}Owner`,\n\t\t\tregister: (options) => this.connect(options, { owner: true }),\n\t\t};\n\t}\n\n\t/**\n\t * What this database's clients are built with besides a dialect — the\n\t * plugins and logging it was declared with.\n\t *\n\t * Public so that whatever opens a connection to it outside \\`connect()\\` —\n\t * a test's transaction — builds the same client. A test that dropped the\n\t * plugins would write \\`createdAt\\` where production writes \\`created_at\\`.\n\t */\n\tget clientConfig(): Omit<KyselyConfig, 'dialect'> {\n\t\t// Split what the manifest declared from what Kysely takes, so neither\n\t\t// leaks into the other: \\`schema\\`, \\`roles\\`, \\`version\\`, \\`image\\`\n\t\t// and \\`extensions\\` describe infrastructure and mean nothing to a\n\t\t// client.\n\t\tconst {\n\t\t\tschema: _schema,\n\t\t\troles: _roles,\n\t\t\tversion: _version,\n\t\t\timage: _image,\n\t\t\textensions: _extensions,\n\t\t\tqueryTags: _queryTags,\n\t\t\t...kysely\n\t\t} = this.options;\n\t\treturn kysely;\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<Kysely<DB>> {\n\t\tconst { url, ownerUrl } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\turl: get(this.config.url).string(),\n\t\t\t\townerUrl: get(this.config.ownerUrl).string().optional(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\treturn new Kysely<DB>({\n\t\t\t...this.clientConfig,\n\t\t\tdialect: new PostgresDialect({\n\t\t\t\tpool: openPool(as.owner ? (ownerUrl ?? url) : url, {\n\t\t\t\t\tqueryTags: this.options.queryTags,\n\t\t\t\t}),\n\t\t\t}),\n\t\t});\n\t}\n}\n\n/**\n * A database you may read through, and derive nothing from.\n *\n * A reader is terminal in the graph, and this is that fact in the type system.\n * `DERIVES_FROM` gives `cache` and `database-schema` no `database-reader`\n * parent, and there is no reader of a reader — so `orders.reader().cache(…)`\n * has always been illegal, but it type-checked and failed later at\n * `assertDerivations`. That is a long way round to learn that a read-only\n * endpoint cannot own a table something writes to.\n *\n * Omitting the three deriving methods rather than making them throw keeps the\n * failure where it costs least: the editor, on the line that wrote it.\n *\n * The result is deliberately not assignable back to `KyselyDatabase` — a\n * reader is not one, and anything that genuinely needs the writer should say\n * so.\n */\nexport type ReadOnlyDatabase<DB, TName extends string> = Omit<\n\tKyselyDatabase<DB, TName>,\n\t'reader' | 'cache' | 'schema'\n>;\nexport { closeDatabasePools } from './pool';\n"],"mappings":";;;;;;;;AAgDA,MAAM,uBAAO,IAAI,IAAa;AAC9B,iBAAiB,mBAAmB,CAAC;;;;;;;;;;;AAYrC,SAAgB,SACf,KACA,UAA+B,CAAC,GACtB;CACV,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,aAAa,OAAO,aAAa,IAAI,aAAa;CACxD,OAAO,aAAa,OAAO,aAAa;CAExC,MAAM,OAAO,IAAI,GAAG,KAAK;EACxB,kBAAkB,OAAO,SAAS;EAClC,GAAI,aAAa,EAAE,SAAS,kBAAkB,aAAa,IAAI,C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KAA0B,CAAC,GACL;EACtB,MAAM,EAAE,KAAK,aAAa,QAAQ,UAChC,QAAQ,SAAS;GACjB,KAAK,IAAI,KAAK,OAAO,GAAG,CAAC,CAAC,OAAO;GACjC,UAAU,IAAI,KAAK,OAAO,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,SAAS;EACvD,EAAE,CAAC,CACF,MAAM;EAER,OAAO,IAAI,OAAW;GACrB,GAAG,KAAK;GACR,SAAS,IAAI,gBAAgB,EAC5B,MAAM,SAAS,GAAG,QAAS,YAAY,MAAO,KAAK,EAClD,WAAW,KAAK,QAAQ,UACzB,CAAC,EACF,CAAC;EACF,CAAC;CACF;AACD"}
|
|
@@ -231,8 +231,8 @@ var KyselyDatabase = class KyselyDatabase {
|
|
|
231
231
|
const canonical = (0, _geekmidas_manifest.canonicalId)(id);
|
|
232
232
|
this.id = canonical;
|
|
233
233
|
this.config = {
|
|
234
|
-
url: (0, _geekmidas_manifest.
|
|
235
|
-
ownerUrl: (0, _geekmidas_manifest.
|
|
234
|
+
url: (0, _geekmidas_manifest.providedKeyFor)(canonical, "database", "url"),
|
|
235
|
+
ownerUrl: (0, _geekmidas_manifest.providedKeyFor)(canonical, "database", "ownerUrl")
|
|
236
236
|
};
|
|
237
237
|
this.schemaName = options.schema ?? DEFAULT_SCHEMA;
|
|
238
238
|
this.roles = options.roles ?? true;
|
|
@@ -381,4 +381,4 @@ Object.defineProperty(exports, "closeDatabasePools", {
|
|
|
381
381
|
}
|
|
382
382
|
});
|
|
383
383
|
|
|
384
|
-
//# sourceMappingURL=kysely-
|
|
384
|
+
//# sourceMappingURL=kysely-D7f6J2lh.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kysely-D7f6J2lh.cjs","names":["onShutdown","currentRequestContext","trace","isSpanContextValid","SpanKind","SpanStatusCode","context","canonicalId","providedKeyFor","DEFAULT_POSTGRES_VERSION","serviceKey","Cache","kysely","Kysely","PostgresDialect"],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"sourcesContent":["/**\n * The `pg` pools a database construct opens, and what every one of them gets:\n *\n * - **A name.** `application_name` is what `pg_stat_activity` shows beside a\n * connection. Without one, a database at `max_connections` cannot say who\n * holds them. It is a *fallback*, so `PGAPPNAME` or `?application_name=` in\n * the URL still win.\n * - **Tagged queries.** Inside a request, each query ends in a comment naming\n * what ran it — `/*operation='POST /orders',request_id='…'*\\/` — in the\n * sqlcommenter form, and inside a trace the query's own span as\n * `traceparent='00-<trace>-<span>-<flags>'`. It shows in\n * `pg_stat_activity.query`, in the server's slow-query and `auto_explain`\n * logs, and costs no round trip; `pg_stat_statements` ignores comments, so\n * its grouping is unchanged.\n * - **A listener for idle-client errors.** When the server ends an idle\n * connection (`idle_session_timeout`, a failover, an admin), the pool emits\n * `'error'`. With no listener that is an uncaught exception that kills the\n * process — for a client the pool has already discarded.\n * - **A span per query.** Through the global OpenTelemetry tracer, so a no-op\n * without a provider. `pg` is bundled into a production entry, where no\n * instrumentation can hook its module load — so the client is wrapped here,\n * as the tags are. See {@link traceQueries}.\n * - **A way to close.** {@link closeDatabasePools} ends every pool opened, so a\n * server shutting down releases its connections instead of holding them\n * until the process dies.\n */\n\nimport { currentRequestContext } from '@geekmidas/services';\nimport {\n\ttype Attributes,\n\tcontext,\n\tisSpanContextValid,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\nimport pg from 'pg';\nimport { onShutdown } from '../shutdown';\n\nexport interface DatabasePoolOptions {\n\t/** Tag queries with what ran them and the trace they ran in. Default true. */\n\tqueryTags?: boolean;\n}\n\n/** The longest statement text a query span carries. */\nexport const MAX_STATEMENT_LENGTH = 2048;\n\n/** Every pool opened and not yet closed, so a shutdown can end them all. */\nconst open = new Set<pg.Pool>();\nonShutdown(() => closeDatabasePools());\n\n/**\n * A pool for one URL, with its schema actually on the search path.\n *\n * `?search_path=` is not a libpq parameter — a URL carrying it connects\n * happily and then resolves every unqualified name against `public`, which is\n * how a schema tenant silently writes its tables into the database it was\n * separated from. Postgres takes it as a startup option instead, so the URL\n * keeps the readable form the target derives and this turns it into the thing\n * the server understands.\n */\nexport function openPool(\n\turl: string,\n\toptions: DatabasePoolOptions = {},\n): pg.Pool {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\tparsed.searchParams.delete('search_path');\n\n\tconst pool = new pg.Pool({\n\t\tconnectionString: parsed.toString(),\n\t\t...(searchPath ? { options: `-c search_path=${searchPath}` } : {}),\n\t\tfallback_application_name: applicationName(),\n\t});\n\n\tpool.on('error', (error) => {\n\t\tconst logger = currentRequestContext()?.logger;\n\t\tif (logger) logger.warn({ err: error }, 'Idle database connection lost');\n\t\telse console.warn('Idle database connection lost:', error.message);\n\t});\n\tconst target = connectionAttributes(parsed);\n\tpool.on('connect', (client) => {\n\t\t// Tags first, so the span wraps them: it records the statement as the\n\t\t// application wrote it rather than with the comment on the end, and it\n\t\t// is the active span when the tag is written — so the `traceparent` a\n\t\t// query carries names the query's own span.\n\t\tif (options.queryTags !== false) tagQueries(client);\n\t\ttraceQueries(client, target);\n\t});\n\n\topen.add(pool);\n\tconst end = pool.end.bind(pool);\n\tpool.end = (async () => {\n\t\topen.delete(pool);\n\t\tawait end();\n\t}) as typeof pool.end;\n\n\treturn pool;\n}\n\n/**\n * End every pool opened, waiting for checked-out connections to come back.\n * For a server's shutdown, after it has stopped taking requests.\n */\nexport async function closeDatabasePools(): Promise<void> {\n\tawait Promise.all([...open].map((pool) => pool.end()));\n}\n\n/**\n * Who this process is, as Postgres will show it: the Lambda function, else the\n * app — `GKM_APP_NAME` where an entry sets it, `gkm dev`'s app tag otherwise.\n * Postgres keeps 63 bytes of it.\n */\nexport function applicationName(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\treturn (\n\t\tenv.AWS_LAMBDA_FUNCTION_NAME ||\n\t\tenv.GKM_APP_NAME ||\n\t\tenv.GKM_DEV_APP?.split('#').pop() ||\n\t\tundefined\n\t);\n}\n\n/**\n * The comment that says what ran a query: the request's operation and id, and\n * the active span as a W3C `traceparent` — the query's own span when it runs\n * through a traced client, since the span wraps the tagging. '' with neither.\n *\n * The keys are in sqlcommenter's sorted order. Values keep only characters\n * that cannot end a comment or a quoted value — `*` and `'` among those\n * dropped — so a route cannot inject SQL through it.\n */\nexport function queryTag(): string {\n\tconst request = currentRequestContext();\n\tconst span = trace.getActiveSpan()?.spanContext();\n\n\tconst tags = [\n\t\t['operation', request?.operation],\n\t\t['request_id', request?.requestId],\n\t\t['traceparent', span && isSpanContextValid(span) ? traceparent(span) : ''],\n\t].filter((tag): tag is [string, string] => Boolean(tag[1]));\n\tif (tags.length === 0) return '';\n\n\tconst clean = (value: string) => value.replace(/[^\\w ./:{}@-]/g, '');\n\treturn ` /*${tags.map(([key, value]) => `${key}='${clean(value)}'`).join(',')}*/`;\n}\n\n/** A span as W3C trace context's `traceparent`, version 00. */\nfunction traceparent(span: {\n\ttraceId: string;\n\tspanId: string;\n\ttraceFlags: number;\n}): string {\n\tconst flags = (span.traceFlags & 0xff).toString(16).padStart(2, '0');\n\treturn `00-${span.traceId}-${span.spanId}-${flags}`;\n}\n\n/**\n * Append {@link queryTag} to everything `client` runs: a SQL string — what\n * Kysely sends — or a query object such as a cursor's.\n */\nfunction tagQueries(client: pg.PoolClient): void {\n\tconst query = client.query.bind(client) as (...args: unknown[]) => unknown;\n\tclient.query = ((first: unknown, ...rest: unknown[]) => {\n\t\tconst tag = queryTag();\n\t\tif (tag && typeof first === 'string') return query(first + tag, ...rest);\n\t\tif (\n\t\t\ttag &&\n\t\t\tfirst &&\n\t\t\ttypeof first === 'object' &&\n\t\t\ttypeof (first as { text?: unknown }).text === 'string'\n\t\t) {\n\t\t\tconst config = first as { text: string };\n\t\t\tconfig.text += tag;\n\t\t}\n\t\treturn query(first, ...rest);\n\t}) as typeof client.query;\n}\n\n/** What every span of one pool says about where it connects. */\nfunction connectionAttributes(url: URL): Attributes {\n\tconst name = decodeURIComponent(url.pathname.slice(1));\n\treturn {\n\t\t'db.system': 'postgresql',\n\t\t...(name && { 'db.name': name }),\n\t\t'server.address': url.hostname,\n\t\t'server.port': Number(url.port || 5432),\n\t};\n}\n\nconst TRACER = '@geekmidas/constructs';\n\n/** `select`, `insert`, … — the first keyword, or `with`'s main statement. */\nconst OPERATION = /^\\s*(?:\\/\\*.*?\\*\\/\\s*)?(\\w+)/s;\n/** The table a statement is about, when it names one where it usually does. */\nconst TABLE =\n\t/\\b(?:from|into|update|join)\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i;\n\n/**\n * What a statement does and to which table, parsed cheaply from its first\n * characters: `select \"orders\"`, `insert \"public\".\"users\"`. A statement the\n * patterns cannot read leaves `table` unset.\n */\nexport function describeStatement(text: string): {\n\toperation?: string;\n\ttable?: string;\n} {\n\tconst head = text.length > 512 ? text.slice(0, 512) : text;\n\tconst operation = OPERATION.exec(head)?.[1]?.toLowerCase();\n\tconst table = TABLE.exec(head)?.[1]?.replace(/\"/g, '');\n\treturn {\n\t\t...(operation && { operation }),\n\t\t...(table && { table }),\n\t};\n}\n\n/**\n * A span around everything `client` runs — `<operation> <table>`, or\n * `db.query` when the statement does not say.\n *\n * The statement text goes on the span only for a parameterized query — values\n * passed separately, as Kysely always does — and truncated. Parameter values\n * never do. A bare string with no values could hold anything a caller\n * concatenated into it, so it gets no text at all.\n */\nfunction traceQueries(client: pg.PoolClient, connection: Attributes): void {\n\tconst query = client.query.bind(client) as (...args: unknown[]) => unknown;\n\tclient.query = ((first: unknown, ...rest: unknown[]) => {\n\t\tconst config =\n\t\t\tfirst && typeof first === 'object'\n\t\t\t\t? (first as { text?: unknown; values?: unknown })\n\t\t\t\t: undefined;\n\t\tconst text =\n\t\t\ttypeof first === 'string'\n\t\t\t\t? first\n\t\t\t\t: typeof config?.text === 'string'\n\t\t\t\t\t? config.text\n\t\t\t\t\t: undefined;\n\t\tconst values = typeof first === 'string' ? rest[0] : config?.values;\n\t\tconst { operation, table } = text ? describeStatement(text) : {};\n\n\t\tconst span = trace\n\t\t\t.getTracer(TRACER)\n\t\t\t.startSpan(operation && table ? `${operation} ${table}` : 'db.query', {\n\t\t\t\tkind: SpanKind.CLIENT,\n\t\t\t\tattributes: {\n\t\t\t\t\t...connection,\n\t\t\t\t\t...(operation && { 'db.operation': operation }),\n\t\t\t\t\t...(table && { 'db.sql.table': table }),\n\t\t\t\t\t...(text &&\n\t\t\t\t\t\tArray.isArray(values) && {\n\t\t\t\t\t\t\t'db.statement':\n\t\t\t\t\t\t\t\ttext.length > MAX_STATEMENT_LENGTH\n\t\t\t\t\t\t\t\t\t? text.slice(0, MAX_STATEMENT_LENGTH)\n\t\t\t\t\t\t\t\t\t: text,\n\t\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t});\n\t\tconst end = (error?: unknown) => {\n\t\t\tif (error) {\n\t\t\t\tif (error instanceof Error) span.recordException(error);\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t}\n\t\t\tspan.end();\n\t\t};\n\n\t\t// A callback, as `pg`'s own callback form takes it.\n\t\tconst last = rest[rest.length - 1];\n\t\tif (typeof last === 'function') {\n\t\t\tconst args = [...rest];\n\t\t\targs[args.length - 1] = (error: unknown, ...result: unknown[]) => {\n\t\t\t\tend(error);\n\t\t\t\treturn (last as (...a: unknown[]) => unknown)(error, ...result);\n\t\t\t};\n\t\t\treturn context.with(trace.setSpan(context.active(), span), () =>\n\t\t\t\tquery(first, ...args),\n\t\t\t);\n\t\t}\n\n\t\tlet result: unknown;\n\t\ttry {\n\t\t\tresult = context.with(trace.setSpan(context.active(), span), () =>\n\t\t\t\tquery(first, ...rest),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tend(error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\t\t(result as Promise<unknown>).then(\n\t\t\t\t() => end(),\n\t\t\t\t(error) => end(error),\n\t\t\t);\n\t\t} else if (\n\t\t\tresult &&\n\t\t\ttypeof (result as { once?: unknown }).once === 'function'\n\t\t) {\n\t\t\t// A submittable — a cursor or a stream — ends when it says so.\n\t\t\tconst emitter = result as {\n\t\t\t\tonce(event: string, fn: (e?: unknown) => void): void;\n\t\t\t};\n\t\t\temitter.once('end', () => end());\n\t\t\temitter.once('error', (error) => end(error));\n\t\t} else {\n\t\t\tend();\n\t\t}\n\t\treturn result;\n\t}) as typeof client.query;\n}\n","/**\n * `KyselyDatabase` — a declared Postgres database, typed by its schema.\n *\n * It declares a logical database, a schema, and the roles that reach it, and\n * hands back a Kysely client built from the one URL the adapter supplied. It\n * names no cloud: `--target=aws` fills that URL from RDS, local dev from the\n * Postgres container.\n *\n * Transactions and RLS context are the execution wrapper's job — it opens the\n * transaction and puts it in `ctx.db`. This construct does not resolve\n * connections per request.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\tDEFAULT_POSTGRES_VERSION,\n\ttype Declaration,\n\ttype PostgresVersion,\n\tprovidedKeyFor,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { Kysely, type KyselyConfig, PostgresDialect } from 'kysely';\nimport { Cache } from '../cache';\nimport type { Construct } from '../construct-interface';\nimport { openPool } from './pool';\n\n/** The schema a database uses when it does not say otherwise. */\nconst DEFAULT_SCHEMA = 'app';\n\n/**\n * Everything Kysely takes, plus what this construct declares.\n *\n * `dialect` is omitted because the construct owns it — it is built from the one\n * URL the adapter supplied, which is the whole point of the construct. The rest\n * of `KyselyConfig` (`plugins`, `log`) is the app's business and passes\n * straight through, so anything Kysely adds later arrives without being\n * tracked here.\n */\ninterface KyselyDatabaseBaseOptions extends Omit<KyselyConfig, 'dialect'> {\n\t/**\n\t * The schema, pinned on both roles' `search_path`.\n\t *\n\t * Defaults to `app` — the role the schema plays, rather than a restatement\n\t * of the database's own name, which reads correctly beside `auth` and\n\t * `pgboss` and keeps the application off `public`.\n\t */\n\tschema?: string;\n\t/**\n\t * Provision the owner/runtime role split. Defaults to on.\n\t *\n\t * Off falls back to the cluster's master credential in both URLs, giving up\n\t * the DDL/DML split and putting credentials that can drop a table into the\n\t * function's environment. A deliberate downgrade, not a default.\n\t */\n\troles?: boolean;\n\t/**\n\t * Extensions to create in this database, as the cluster master, before the\n\t * first migration — for the ones the owner role a migration runs as may not\n\t * create (PostGIS is not a trusted extension). They are created in\n\t * `public`, which joins this database's roles' `search_path`, so their\n\t * types resolve unqualified.\n\t *\n\t * Only attempted: the image has to ship them.\n\t */\n\textensions?: readonly string[];\n\t/**\n\t * End each query run inside a request with a comment naming what ran it —\n\t * `/*operation='POST /orders',request_id='…'*\\/` — so `pg_stat_activity`\n\t * and the server's logs can tie a query to its endpoint — and, inside a\n\t * trace, with the query span's `traceparent='00-…'` (sqlcommenter), so\n\t * they can tie it to the trace too. Defaults to on.\n\t */\n\tqueryTags?: boolean;\n}\n\n/**\n * Which Postgres the database runs: a major on the stock image, or an image\n * the project names. One or the other, never both — an image's tag already\n * says its major, and a second statement of it is one that can disagree.\n */\nexport type PostgresRuntime =\n\t| {\n\t\t\t/**\n\t\t\t * The Postgres major version to provision, on the stock image.\n\t\t\t *\n\t\t\t * Declared here so one statement reaches every target. It was\n\t\t\t * previously set in two unrelated places — a container tag locally,\n\t\t\t * nothing at all on AWS (so Aurora chose) — which is how local came to\n\t\t\t * run 18 while deployed ran 17.7 with nothing recording the difference.\n\t\t\t *\n\t\t\t * Defaults to {@link DEFAULT_POSTGRES_VERSION}.\n\t\t\t */\n\t\t\tversion?: PostgresVersion;\n\t\t\timage?: never;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * The container image to run, wherever a target runs one (local,\n\t\t\t * Dokploy), in place of `postgres:<version>`.\n\t\t\t *\n\t\t\t * Yours to choose and used as written: its tag is the major, and it\n\t\t\t * should ship every extension in `extensions`. AWS runs RDS, ignores\n\t\t\t * it, and provisions {@link DEFAULT_POSTGRES_VERSION}.\n\t\t\t *\n\t\t\t * ```ts\n\t\t\t * new KyselyDatabase<GeoDB>('Geo', {\n\t\t\t * image: 'postgis/postgis:18-3.6-alpine',\n\t\t\t * extensions: ['postgis'],\n\t\t\t * });\n\t\t\t * ```\n\t\t\t */\n\t\t\timage: string;\n\t\t\tversion?: never;\n\t };\n\n/**\n * Everything Kysely takes, plus what this construct declares — including\n * which Postgres it runs, as a version or an image.\n */\nexport type KyselyDatabaseOptions = KyselyDatabaseBaseOptions & PostgresRuntime;\n\n/** What makes a construct derived rather than a database in its own right. */\ninterface DerivedFrom {\n\tkind: 'database-reader' | 'database-schema';\n\tof: string;\n\tschema?: string;\n}\n\n/**\n * @typeParam DB - the database's schema.\n * @typeParam TName - the canonical id. TypeScript has no partial\n * type-argument inference, so `new KyselyDatabase<OrdersDB>('orders')` leaves\n * this at its default and the service key widens to `string`. `db` still types\n * through `.database()`, which infers from the service.\n */\nexport class KyselyDatabase<DB = unknown, TName extends string = string>\n\timplements Construct<TName, Kysely<DB>>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, Kysely<DB>>;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the key the\n\t * build publishes and the key the client reads cannot drift.\n\t */\n\tprivate readonly config: { url: string; ownerUrl: string };\n\tprivate readonly schemaName: string;\n\tprivate readonly roles: boolean;\n\tprivate readonly runtime: { version: PostgresVersion } | { image: string };\n\tprivate readonly derivedFrom?: DerivedFrom;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: KyselyDatabaseOptions = {},\n\t\tderivedFrom?: DerivedFrom,\n\t) {\n\t\t// Canonicalises, so `orders` and `Orders` are one construct rather than\n\t\t// two that collide. Throws on anything that cannot become a valid id.\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.config = {\n\t\t\turl: providedKeyFor(canonical, 'database', 'url'),\n\t\t\townerUrl: providedKeyFor(canonical, 'database', 'ownerUrl'),\n\t\t};\n\t\tthis.schemaName = options.schema ?? DEFAULT_SCHEMA;\n\t\tthis.roles = options.roles ?? true;\n\t\tthis.runtime = options.image\n\t\t\t? { image: options.image }\n\t\t\t: { version: options.version ?? DEFAULT_POSTGRES_VERSION };\n\t\tthis.derivedFrom = derivedFrom;\n\n\t\t// A field, not a getter: service discovery caches by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\t// Forwards the whole options object — cherry-picking `envParser` strips\n\t\t\t// `context` and with it the request-scoped logger.\n\t\t\tregister: (registerOptions) => this.connect(registerOptions),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\tif (this.derivedFrom) {\n\t\t\tconst { kind, of, schema } = this.derivedFrom;\n\n\t\t\treturn [\n\t\t\t\tkind === 'database-schema'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tid: this.id,\n\t\t\t\t\t\t\tof,\n\t\t\t\t\t\t\tschema: schema ?? this.schemaName,\n\t\t\t\t\t\t\t// The runtime key alone — see the note below on the parent.\n\t\t\t\t\t\t\tprovides: [this.config.url],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tid: this.id,\n\t\t\t\t\t\t\tof,\n\t\t\t\t\t\t\t// A reader has no owner URL of its own — nothing migrates\n\t\t\t\t\t\t\t// through a read-only endpoint — so this is the one key.\n\t\t\t\t\t\t\tprovides: [this.config.url],\n\t\t\t\t\t\t},\n\t\t\t];\n\t\t}\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'database',\n\t\t\t\tid: this.id,\n\t\t\t\tengine: 'postgres',\n\t\t\t\tschema: this.schemaName,\n\t\t\t\t// A version, or the image whose tag is one — never both.\n\t\t\t\t...this.runtime,\n\t\t\t\t...(this.options.extensions?.length\n\t\t\t\t\t? { extensions: [...new Set(this.options.extensions)] }\n\t\t\t\t\t: {}),\n\t\t\t\t// One key, the runtime role's. `config` also holds the owner key and\n\t\t\t\t// it is deliberately absent here: a key in `provides` is a key an\n\t\t\t\t// edge can name, and nothing should be able to depend on DDL rights.\n\t\t\t\tprovides: [this.config.url],\n\t\t\t\t...(this.roles ? {} : { roles: false }),\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * A read-only endpoint on this database.\n\t *\n\t * Read-only is enforced by the reader role's grants rather than by which\n\t * endpoint it resolves to, so falling back to the writer where no replica\n\t * exists is safe rather than a silently writable connection behind a name\n\t * that says reader. There is no `writer()`: the database *is* the writer, so\n\t * a replica can never be reached by accident.\n\t *\n\t * The return type is narrower than this class on purpose — see\n\t * {@link ReadOnlyDatabase}.\n\t */\n\treader(): ReadOnlyDatabase<DB, `${TName}Reader`> {\n\t\treturn new KyselyDatabase<DB, `${TName}Reader`>(\n\t\t\t`${this.id}Reader` as ConstructName<`${TName}Reader`>,\n\t\t\tthis.options,\n\t\t\t{ kind: 'database-reader', of: this.id },\n\t\t);\n\t}\n\n\t/**\n\t * A cache that lives in this database.\n\t *\n\t * The same strengthening `schema()` is over a second database: `new\n\t * Cache('Sessions')` says the app caches and leaves where to the deployment,\n\t * while this says it caches *here* — which is a fact about the application\n\t * and so belongs in its code.\n\t *\n\t * What it buys beyond being explicit: the table's schema and the role that\n\t * reaches it come from this database rather than from a second convention,\n\t * and the backend no longer has to guess which database \"the database\" meant\n\t * when an app declares two.\n\t *\n\t * A cache is not a `KyselyDatabase`, so this returns a `Cache` — the client\n\t * is a key/value store, not a query builder, and typing it as the parent\n\t * would be a convenience that lies.\n\t */\n\tcache<TCache extends string = `${TName}Cache`>(\n\t\tid: ConstructName<TCache> = `${this.id}Cache` as ConstructName<TCache>,\n\t\toptions: { table?: string } = {},\n\t): Cache<TCache> {\n\t\treturn new Cache<TCache>(id, {\n\t\t\tof: this.id,\n\t\t\t...(options.table ? { table: options.table } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * A second schema in this database, with its own role(s) and its own URL —\n\t * so this database's role holds no grant on those tables at all.\n\t *\n\t * Typed separately because a tenant has its own tables: the point is that\n\t * `auth.selectFrom('sessions')` type-checks and\n\t * `orders.selectFrom('sessions')` does not.\n\t */\n\tschema<TenantDB, TTenant extends string>(\n\t\tid: ConstructName<TTenant>,\n\t\toptions: KyselyDatabaseOptions = {},\n\t): KyselyDatabase<TenantDB, TTenant> {\n\t\treturn new KyselyDatabase<TenantDB, TTenant>(id, options, {\n\t\t\tkind: 'database-schema',\n\t\t\tof: this.id,\n\t\t\tschema: options.schema ?? (id as string).toLowerCase(),\n\t\t});\n\t}\n\n\t/**\n\t * A connection as the *owner* role — the one that may create, alter and drop.\n\t *\n\t * A `Service` rather than part of the construct, and deliberately so: a\n\t * construct is what `.dependsOn()` accepts, and nothing should be able to\n\t * depend on this. A migrator asks for it by name; a handler cannot ask at\n\t * all, which is the security property the role split exists for.\n\t *\n\t * Falls back to the runtime URL where no owner URL was published — the\n\t * `roles: false` downgrade, where there is only one credential and it is the\n\t * cluster master's.\n\t */\n\tget owner(): Service<`${Uncapitalize<TName>}Owner`, Kysely<DB>> {\n\t\treturn {\n\t\t\tserviceName:\n\t\t\t\t`${serviceKey(this.id)}Owner` as `${Uncapitalize<TName>}Owner`,\n\t\t\tregister: (options) => this.connect(options, { owner: true }),\n\t\t};\n\t}\n\n\t/**\n\t * What this database's clients are built with besides a dialect — the\n\t * plugins and logging it was declared with.\n\t *\n\t * Public so that whatever opens a connection to it outside \\`connect()\\` —\n\t * a test's transaction — builds the same client. A test that dropped the\n\t * plugins would write \\`createdAt\\` where production writes \\`created_at\\`.\n\t */\n\tget clientConfig(): Omit<KyselyConfig, 'dialect'> {\n\t\t// Split what the manifest declared from what Kysely takes, so neither\n\t\t// leaks into the other: \\`schema\\`, \\`roles\\`, \\`version\\`, \\`image\\`\n\t\t// and \\`extensions\\` describe infrastructure and mean nothing to a\n\t\t// client.\n\t\tconst {\n\t\t\tschema: _schema,\n\t\t\troles: _roles,\n\t\t\tversion: _version,\n\t\t\timage: _image,\n\t\t\textensions: _extensions,\n\t\t\tqueryTags: _queryTags,\n\t\t\t...kysely\n\t\t} = this.options;\n\t\treturn kysely;\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<Kysely<DB>> {\n\t\tconst { url, ownerUrl } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\turl: get(this.config.url).string(),\n\t\t\t\townerUrl: get(this.config.ownerUrl).string().optional(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\treturn new Kysely<DB>({\n\t\t\t...this.clientConfig,\n\t\t\tdialect: new PostgresDialect({\n\t\t\t\tpool: openPool(as.owner ? (ownerUrl ?? url) : url, {\n\t\t\t\t\tqueryTags: this.options.queryTags,\n\t\t\t\t}),\n\t\t\t}),\n\t\t});\n\t}\n}\n\n/**\n * A database you may read through, and derive nothing from.\n *\n * A reader is terminal in the graph, and this is that fact in the type system.\n * `DERIVES_FROM` gives `cache` and `database-schema` no `database-reader`\n * parent, and there is no reader of a reader — so `orders.reader().cache(…)`\n * has always been illegal, but it type-checked and failed later at\n * `assertDerivations`. That is a long way round to learn that a read-only\n * endpoint cannot own a table something writes to.\n *\n * Omitting the three deriving methods rather than making them throw keeps the\n * failure where it costs least: the editor, on the line that wrote it.\n *\n * The result is deliberately not assignable back to `KyselyDatabase` — a\n * reader is not one, and anything that genuinely needs the writer should say\n * so.\n */\nexport type ReadOnlyDatabase<DB, TName extends string> = Omit<\n\tKyselyDatabase<DB, TName>,\n\t'reader' | 'cache' | 'schema'\n>;\nexport { closeDatabasePools } from './pool';\n"],"mappings":";;;;;;;;;;AAgDA,MAAM,uBAAO,IAAI,IAAa;AAC9BA,iBAAAA,iBAAiB,mBAAmB,CAAC;;;;;;;;;;;AAYrC,SAAgB,SACf,KACA,UAA+B,CAAC,GACtB;CACV,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,aAAa,OAAO,aAAa,IAAI,aAAa;CACxD,OA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GACzD,MAAM;GACN,IAAI,KAAK;GACT,QAAQ,QAAQ,UAAW,GAAc,YAAY;EACtD,CAAC;CACF;;;;;;;;;;;;;CAcA,IAAI,QAA4D;EAC/D,OAAO;GACN,aACC,IAAA,GAAGD,oBAAAA,WAAAA,CAAW,KAAK,EAAE,EAAE;GACxB,WAAW,YAAY,KAAK,QAAQ,SAAS,EAAE,OAAO,KAAK,CAAC;EAC7D;CACD;;;;;;;;;CAUA,IAAI,eAA8C;EAKjD,MAAM,EACL,QAAQ,SACR,OAAO,QACP,SAAS,UACT,OAAO,QACP,YAAY,aACZ,WAAW,YACX,GAAGE,aACA,KAAK;EACT,OAAOA;CACR;CAEA,MAAc,QACb,SACA,KAA0B,CAAC,GACL;EACtB,MAAM,EAAE,KAAK,aAAa,QAAQ,UAChC,QAAQ,SAAS;GACjB,KAAK,IAAI,KAAK,OAAO,GAAG,CAAC,CAAC,OAAO;GACjC,UAAU,IAAI,KAAK,OAAO,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,SAAS;EACvD,EAAE,CAAC,CACF,MAAM;EAER,OAAO,IAAIC,OAAAA,OAAW;GACrB,GAAG,KAAK;GACR,SAAS,IAAIC,OAAAA,gBAAgB,EAC5B,MAAM,SAAS,GAAG,QAAS,YAAY,MAAO,KAAK,EAClD,WAAW,KAAK,QAAQ,UACzB,CAAC,EACF,CAAC;EACF,CAAC;CACF;AACD"}
|
package/dist/mobile-app.cjs
CHANGED
|
@@ -39,7 +39,7 @@ var MobileApp = class MobileApp {
|
|
|
39
39
|
this.config = config;
|
|
40
40
|
this.dependencies = dependencies;
|
|
41
41
|
this.id = (0, _geekmidas_manifest.canonicalId)(id);
|
|
42
|
-
this.keys = { scheme: (0, _geekmidas_manifest.
|
|
42
|
+
this.keys = { scheme: (0, _geekmidas_manifest.providedKeyFor)(this.id, "mobile-app", "scheme") };
|
|
43
43
|
}
|
|
44
44
|
/**
|
|
45
45
|
* What this app calls — the surfaces it is built with the URLs of, and the
|
package/dist/mobile-app.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mobile-app.cjs","names":["canonicalId","
|
|
1
|
+
{"version":3,"file":"mobile-app.cjs","names":["canonicalId","providedKeyFor","frontendEdgeTo"],"sources":["../src/mobile-app.ts"],"sourcesContent":["/**\n * `MobileApp` — an Expo app, declared like a site.\n *\n * Its edges are the point, as a site's are. One `.dependsOn([api, auth])` is\n * the fact behind everything a mobile app otherwise has written down by hand:\n *\n * - its `EXPO_PUBLIC_API_URL` and `EXPO_PUBLIC_AUTH_URL`, which locally are\n * the servers' own ports — reachable once the app swaps `localhost` for the\n * address Metro is served from, which is what makes a phone on the LAN work;\n * - with an `Email` among them, Mailpit's inbox on a local stage\n * (`EXPO_PUBLIC_<ID>_INBOX_URL`), so a sign-in link can be opened from the\n * app — unset deployed, where there is no inbox;\n * - its URL scheme (`shop`), the same on every stage;\n * - the scheme in the auth server's and the API's trusted origins — and, on a\n * local stage, the `exp://` origins Expo Go sends from;\n * - Better Auth's Expo plugin on the auth server, and sign-in links an app asks\n * for built on an address the phone can open.\n *\n * ```ts\n * export const app = new MobileApp('App', { path: 'apps/app' })\n * .dependsOn([api, auth]);\n * ```\n *\n * Like a site it has no `.service`: it is built by its own toolchain, and\n * consumes addresses rather than connections. Nothing deploys it — EAS and the\n * stores do — so the targets derive *for* it and never run it.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\ttype MobileAppDeclaration,\n\ttype MobileAppStage,\n\tprovidedKeyFor,\n} from '@geekmidas/manifest';\nimport { type Declarable, frontendEdgeTo } from './construct-interface';\n\nexport interface MobileAppConfig {\n\t/**\n\t * Where its source lives, relative to the workspace root — `'apps/app'`.\n\t * Required, the same field a site and a surface take.\n\t */\n\tpath: string;\n\t/**\n\t * The port Metro serves it on locally.\n\t *\n\t * Normally omitted: ports are assigned in a stable order, as a site's are,\n\t * and `gkm exec` hands it to Expo as `RCT_METRO_PORT`.\n\t */\n\tport?: number;\n\t/**\n\t * Modules to import when sniffing which env vars the app reads — its\n\t * values are inlined at build time, as a site's are.\n\t */\n\tconfig?: { client?: string; server?: string };\n\t/**\n\t * Which toolchain builds it — the same field a site names its framework\n\t * by. Expo is the one that ships, and the default.\n\t */\n\tvariant?: MobileAppDeclaration['variant'];\n\t/**\n\t * Its URL scheme.\n\t *\n\t * Normally omitted: it is the project's name — `shop` — on every stage.\n\t * Give one only when the app is known by another name.\n\t */\n\tscheme?: string;\n\t/**\n\t * How a deployed stage ships it, where that differs from the defaults: the\n\t * protected stage reads EAS's `production` environment and submits to\n\t * Play's `production` track, every other deployed stage `preview` and\n\t * `internal`, and every Android release is a `draft` until someone\n\t * releases it in Play Console.\n\t *\n\t * ```ts\n\t * stages: { beta: { environment: 'preview', android: { track: 'alpha' } } }\n\t * ```\n\t */\n\tstages?: Readonly<Record<string, MobileAppStage>>;\n}\n\nexport class MobileApp<TName extends string = string>\n\timplements Declarable<TName>\n{\n\treadonly id: TName;\n\t/** The key its scheme arrives under — what its `app.config.ts` reads. */\n\treadonly keys: { scheme: string };\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: MobileAppConfig,\n\t\t/** Internal: how `.dependsOn()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t) {\n\t\tthis.id = canonicalId(id as string) as TName;\n\t\tthis.keys = { scheme: providedKeyFor(this.id, 'mobile-app', 'scheme') };\n\t}\n\n\t/**\n\t * What this app calls — the surfaces it is built with the URLs of, and the\n\t * ones that come to trust its scheme.\n\t *\n\t * Immutable, like every other builder: it returns a new app rather than\n\t * changing this one.\n\t *\n\t * A plain edge to a `FileServer` is to its public face — the address its\n\t * objects are served on, inlined — never to the bucket a phone has no\n\t * business holding a key to.\n\t */\n\tdependsOn(constructs: readonly Declarable[]): MobileApp<TName> {\n\t\treturn new MobileApp<TName>(this.id as ConstructName<TName>, this.config, [\n\t\t\t...this.dependencies,\n\t\t\t...constructs.map(frontendEdgeTo),\n\t\t]);\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'mobile-app',\n\t\t\t\tid: this.id,\n\t\t\t\tvariant: this.config.variant ?? 'expo',\n\t\t\t\tapp: {\n\t\t\t\t\tpath: this.config.path,\n\t\t\t\t\t...(this.config.port ? { port: this.config.port } : {}),\n\t\t\t\t\t...(this.config.config ? { config: this.config.config } : {}),\n\t\t\t\t},\n\t\t\t\t...(this.config.scheme ? { scheme: this.config.scheme } : {}),\n\t\t\t\t...(this.config.stages ? { stages: this.config.stages } : {}),\n\t\t\t\tdependencies: this.dependencies,\n\t\t\t\tprovides: [this.keys.scheme],\n\t\t\t},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,IAAa,YAAb,MAAa,UAEb;CAOmB;CAEA;CARlB;;CAEA;CAEA,YACC,IACA,QAEA,eAAuD,CAAC,GACvD;EAHgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAEjB,KAAK,MAAA,GAAKA,oBAAAA,YAAAA,CAAY,EAAY;EAClC,KAAK,OAAO,EAAE,SAAA,GAAQC,oBAAAA,eAAAA,CAAe,KAAK,IAAI,cAAc,QAAQ,EAAE;CACvE;;;;;;;;;;;;CAaA,UAAU,YAAqD;EAC9D,OAAO,IAAI,UAAiB,KAAK,IAA4B,KAAK,QAAQ,CACzE,GAAG,KAAK,cACR,GAAG,WAAW,IAAIC,4BAAAA,cAAc,CACjC,CAAC;CACF;CAEA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,SAAS,KAAK,OAAO,WAAW;GAChC,KAAK;IACJ,MAAM,KAAK,OAAO;IAClB,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,KAAK,IAAI,CAAC;IACrD,GAAI,KAAK,OAAO,SAAS,EAAE,QAAQ,KAAK,OAAO,OAAO,IAAI,CAAC;GAC5D;GACA,GAAI,KAAK,OAAO,SAAS,EAAE,QAAQ,KAAK,OAAO,OAAO,IAAI,CAAC;GAC3D,GAAI,KAAK,OAAO,SAAS,EAAE,QAAQ,KAAK,OAAO,OAAO,IAAI,CAAC;GAC3D,cAAc,KAAK;GACnB,UAAU,CAAC,KAAK,KAAK,MAAM;EAC5B,CACD;CACD;AACD"}
|
package/dist/mobile-app.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { frontendEdgeTo } from "./construct-interface.mjs";
|
|
2
|
-
import { canonicalId,
|
|
2
|
+
import { canonicalId, providedKeyFor } from "@geekmidas/manifest";
|
|
3
3
|
//#region src/mobile-app.ts
|
|
4
4
|
/**
|
|
5
5
|
* `MobileApp` — an Expo app, declared like a site.
|
|
@@ -38,7 +38,7 @@ var MobileApp = class MobileApp {
|
|
|
38
38
|
this.config = config;
|
|
39
39
|
this.dependencies = dependencies;
|
|
40
40
|
this.id = canonicalId(id);
|
|
41
|
-
this.keys = { scheme:
|
|
41
|
+
this.keys = { scheme: providedKeyFor(this.id, "mobile-app", "scheme") };
|
|
42
42
|
}
|
|
43
43
|
/**
|
|
44
44
|
* What this app calls — the surfaces it is built with the URLs of, and the
|
package/dist/mobile-app.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mobile-app.mjs","names":[],"sources":["../src/mobile-app.ts"],"sourcesContent":["/**\n * `MobileApp` — an Expo app, declared like a site.\n *\n * Its edges are the point, as a site's are. One `.dependsOn([api, auth])` is\n * the fact behind everything a mobile app otherwise has written down by hand:\n *\n * - its `EXPO_PUBLIC_API_URL` and `EXPO_PUBLIC_AUTH_URL`, which locally are\n * the servers' own ports — reachable once the app swaps `localhost` for the\n * address Metro is served from, which is what makes a phone on the LAN work;\n * - with an `Email` among them, Mailpit's inbox on a local stage\n * (`EXPO_PUBLIC_<ID>_INBOX_URL`), so a sign-in link can be opened from the\n * app — unset deployed, where there is no inbox;\n * - its URL scheme (`shop`), the same on every stage;\n * - the scheme in the auth server's and the API's trusted origins — and, on a\n * local stage, the `exp://` origins Expo Go sends from;\n * - Better Auth's Expo plugin on the auth server, and sign-in links an app asks\n * for built on an address the phone can open.\n *\n * ```ts\n * export const app = new MobileApp('App', { path: 'apps/app' })\n * .dependsOn([api, auth]);\n * ```\n *\n * Like a site it has no `.service`: it is built by its own toolchain, and\n * consumes addresses rather than connections. Nothing deploys it — EAS and the\n * stores do — so the targets derive *for* it and never run it.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\ttype MobileAppDeclaration,\n\ttype MobileAppStage,\n\
|
|
1
|
+
{"version":3,"file":"mobile-app.mjs","names":[],"sources":["../src/mobile-app.ts"],"sourcesContent":["/**\n * `MobileApp` — an Expo app, declared like a site.\n *\n * Its edges are the point, as a site's are. One `.dependsOn([api, auth])` is\n * the fact behind everything a mobile app otherwise has written down by hand:\n *\n * - its `EXPO_PUBLIC_API_URL` and `EXPO_PUBLIC_AUTH_URL`, which locally are\n * the servers' own ports — reachable once the app swaps `localhost` for the\n * address Metro is served from, which is what makes a phone on the LAN work;\n * - with an `Email` among them, Mailpit's inbox on a local stage\n * (`EXPO_PUBLIC_<ID>_INBOX_URL`), so a sign-in link can be opened from the\n * app — unset deployed, where there is no inbox;\n * - its URL scheme (`shop`), the same on every stage;\n * - the scheme in the auth server's and the API's trusted origins — and, on a\n * local stage, the `exp://` origins Expo Go sends from;\n * - Better Auth's Expo plugin on the auth server, and sign-in links an app asks\n * for built on an address the phone can open.\n *\n * ```ts\n * export const app = new MobileApp('App', { path: 'apps/app' })\n * .dependsOn([api, auth]);\n * ```\n *\n * Like a site it has no `.service`: it is built by its own toolchain, and\n * consumes addresses rather than connections. Nothing deploys it — EAS and the\n * stores do — so the targets derive *for* it and never run it.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\ttype MobileAppDeclaration,\n\ttype MobileAppStage,\n\tprovidedKeyFor,\n} from '@geekmidas/manifest';\nimport { type Declarable, frontendEdgeTo } from './construct-interface';\n\nexport interface MobileAppConfig {\n\t/**\n\t * Where its source lives, relative to the workspace root — `'apps/app'`.\n\t * Required, the same field a site and a surface take.\n\t */\n\tpath: string;\n\t/**\n\t * The port Metro serves it on locally.\n\t *\n\t * Normally omitted: ports are assigned in a stable order, as a site's are,\n\t * and `gkm exec` hands it to Expo as `RCT_METRO_PORT`.\n\t */\n\tport?: number;\n\t/**\n\t * Modules to import when sniffing which env vars the app reads — its\n\t * values are inlined at build time, as a site's are.\n\t */\n\tconfig?: { client?: string; server?: string };\n\t/**\n\t * Which toolchain builds it — the same field a site names its framework\n\t * by. Expo is the one that ships, and the default.\n\t */\n\tvariant?: MobileAppDeclaration['variant'];\n\t/**\n\t * Its URL scheme.\n\t *\n\t * Normally omitted: it is the project's name — `shop` — on every stage.\n\t * Give one only when the app is known by another name.\n\t */\n\tscheme?: string;\n\t/**\n\t * How a deployed stage ships it, where that differs from the defaults: the\n\t * protected stage reads EAS's `production` environment and submits to\n\t * Play's `production` track, every other deployed stage `preview` and\n\t * `internal`, and every Android release is a `draft` until someone\n\t * releases it in Play Console.\n\t *\n\t * ```ts\n\t * stages: { beta: { environment: 'preview', android: { track: 'alpha' } } }\n\t * ```\n\t */\n\tstages?: Readonly<Record<string, MobileAppStage>>;\n}\n\nexport class MobileApp<TName extends string = string>\n\timplements Declarable<TName>\n{\n\treadonly id: TName;\n\t/** The key its scheme arrives under — what its `app.config.ts` reads. */\n\treadonly keys: { scheme: string };\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: MobileAppConfig,\n\t\t/** Internal: how `.dependsOn()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t) {\n\t\tthis.id = canonicalId(id as string) as TName;\n\t\tthis.keys = { scheme: providedKeyFor(this.id, 'mobile-app', 'scheme') };\n\t}\n\n\t/**\n\t * What this app calls — the surfaces it is built with the URLs of, and the\n\t * ones that come to trust its scheme.\n\t *\n\t * Immutable, like every other builder: it returns a new app rather than\n\t * changing this one.\n\t *\n\t * A plain edge to a `FileServer` is to its public face — the address its\n\t * objects are served on, inlined — never to the bucket a phone has no\n\t * business holding a key to.\n\t */\n\tdependsOn(constructs: readonly Declarable[]): MobileApp<TName> {\n\t\treturn new MobileApp<TName>(this.id as ConstructName<TName>, this.config, [\n\t\t\t...this.dependencies,\n\t\t\t...constructs.map(frontendEdgeTo),\n\t\t]);\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'mobile-app',\n\t\t\t\tid: this.id,\n\t\t\t\tvariant: this.config.variant ?? 'expo',\n\t\t\t\tapp: {\n\t\t\t\t\tpath: this.config.path,\n\t\t\t\t\t...(this.config.port ? { port: this.config.port } : {}),\n\t\t\t\t\t...(this.config.config ? { config: this.config.config } : {}),\n\t\t\t\t},\n\t\t\t\t...(this.config.scheme ? { scheme: this.config.scheme } : {}),\n\t\t\t\t...(this.config.stages ? { stages: this.config.stages } : {}),\n\t\t\t\tdependencies: this.dependencies,\n\t\t\t\tprovides: [this.keys.scheme],\n\t\t\t},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,IAAa,YAAb,MAAa,UAEb;CAOmB;CAEA;CARlB;;CAEA;CAEA,YACC,IACA,QAEA,eAAuD,CAAC,GACvD;EAHgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAEjB,KAAK,KAAK,YAAY,EAAY;EAClC,KAAK,OAAO,EAAE,QAAQ,eAAe,KAAK,IAAI,cAAc,QAAQ,EAAE;CACvE;;;;;;;;;;;;CAaA,UAAU,YAAqD;EAC9D,OAAO,IAAI,UAAiB,KAAK,IAA4B,KAAK,QAAQ,CACzE,GAAG,KAAK,cACR,GAAG,WAAW,IAAI,cAAc,CACjC,CAAC;CACF;CAEA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,SAAS,KAAK,OAAO,WAAW;GAChC,KAAK;IACJ,MAAM,KAAK,OAAO;IAClB,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,KAAK,IAAI,CAAC;IACrD,GAAI,KAAK,OAAO,SAAS,EAAE,QAAQ,KAAK,OAAO,OAAO,IAAI,CAAC;GAC5D;GACA,GAAI,KAAK,OAAO,SAAS,EAAE,QAAQ,KAAK,OAAO,OAAO,IAAI,CAAC;GAC3D,GAAI,KAAK,OAAO,SAAS,EAAE,QAAQ,KAAK,OAAO,OAAO,IAAI,CAAC;GAC3D,cAAc,KAAK;GACnB,UAAU,CAAC,KAAK,KAAK,MAAM;EAC5B,CACD;CACD;AACD"}
|
package/dist/object-storage.cjs
CHANGED
|
@@ -27,7 +27,7 @@ var ObjectStorage = class {
|
|
|
27
27
|
this.options = options;
|
|
28
28
|
const canonical = (0, _geekmidas_manifest.canonicalId)(id);
|
|
29
29
|
this.id = canonical;
|
|
30
|
-
this.keys = { connectionString: (0, _geekmidas_manifest.
|
|
30
|
+
this.keys = { connectionString: (0, _geekmidas_manifest.providedKeyFor)(canonical, "objects", "connectionString") };
|
|
31
31
|
this.expire = require_expire.expiryDays(canonical, options.expire);
|
|
32
32
|
this.service = {
|
|
33
33
|
serviceName: (0, _geekmidas_manifest.serviceKey)(canonical),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object-storage.cjs","names":["canonicalId","
|
|
1
|
+
{"version":3,"file":"object-storage.cjs","names":["canonicalId","providedKeyFor","expiryDays","serviceKey","createStorageClient"],"sources":["../src/object-storage.ts"],"sourcesContent":["/**\n * `ObjectStorage` — a declared bucket.\n *\n * Where the three packages meet: it implements the construct contract, derives\n * its env key through `@geekmidas/manifest`, and hands back a\n * `@geekmidas/storage` client. It names no cloud — `--target=aws` fills the\n * injected URL with S3's values, local dev with MinIO's.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tprovidedKeyFor,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { createStorageClient, type StorageClient } from '@geekmidas/storage';\nimport type { Construct } from './construct-interface';\nimport { expiryDays, type ObjectExpiry } from './expire';\n\nexport {\n\tExpiryDaysInvalid,\n\tExpiryPrefixInvalid,\n\ttype ObjectExpiry,\n} from './expire';\n\nexport interface ObjectStorageOptions {\n\t/** Keep previous versions of an object. */\n\tversioned?: boolean;\n\t/**\n\t * Delete the objects under each prefix this many days after they were\n\t * written — `{ 'quotes/': { days: 30 } }`.\n\t */\n\texpire?: ObjectExpiry;\n}\n\nexport class ObjectStorage<TName extends string = string>\n\timplements Construct<TName, StorageClient>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, StorageClient>;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the key the\n\t * build publishes and the key the client reads cannot drift — the whole point\n\t * of the construct owning both faces.\n\t */\n\tprivate readonly keys: { connectionString: string };\n\n\t/** Checked once, at declaration: prefix → days. */\n\tprivate readonly expire: Record<string, number> | undefined;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: ObjectStorageOptions = {},\n\t) {\n\t\t// Canonicalises, so `uploads` and `Uploads` are one construct rather than\n\t\t// two that collide. Throws on anything that cannot become a valid id.\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.keys = {\n\t\t\tconnectionString: providedKeyFor(\n\t\t\t\tcanonical,\n\t\t\t\t'objects',\n\t\t\t\t'connectionString',\n\t\t\t),\n\t\t};\n\t\tthis.expire = expiryDays(canonical, options.expire);\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (options) => this.connect(options),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'objects',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.keys.connectionString],\n\t\t\t\t...(this.options.versioned ? { versioned: true } : {}),\n\t\t\t\t...(this.expire ? { expire: this.expire } : {}),\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Builds the client from the connection string the adapter supplied.\n\t *\n\t * Its scheme selects the driver, so this construct imports no provider\n\t * and an app that never touches S3 never resolves the AWS SDK. Whoever\n\t * assembles the application registers the drivers its target needs.\n\t */\n\tprivate async connect({\n\t\tenvParser,\n\t}: ServiceRegisterOptions): Promise<StorageClient> {\n\t\tconst { connectionString } = envParser\n\t\t\t.create((get) => ({\n\t\t\t\tconnectionString: get(this.keys.connectionString).string(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\treturn createStorageClient(connectionString);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAqCA,IAAa,gBAAb,MAEA;CAgBmB;CAflB;CACA;;;;;;CAOA;;CAGA;CAEA,YACC,IACA,UAAiD,CAAC,GACjD;EADgB,KAAA,UAAA;EAIjB,MAAM,aAAA,GAAYA,oBAAAA,YAAAA,CAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,OAAO,EACX,mBAAA,GAAkBC,oBAAAA,eAAAA,CACjB,WACA,WACA,kBACD,EACD;EACA,KAAK,SAASC,eAAAA,WAAW,WAAW,QAAQ,MAAM;EAGlD,KAAK,UAAU;GACd,cAAA,GAAaC,oBAAAA,WAAAA,CAAW,SAAS;GACjC,WAAW,YAAY,KAAK,QAAQ,OAAO;EAC5C;CACD;CAEA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,UAAU,CAAC,KAAK,KAAK,gBAAgB;GACrC,GAAI,KAAK,QAAQ,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;GACpD,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;EAC9C,CACD;CACD;;;;;;;;CASA,MAAc,QAAQ,EACrB,aACkD;EAClD,MAAM,EAAE,qBAAqB,UAC3B,QAAQ,SAAS,EACjB,kBAAkB,IAAI,KAAK,KAAK,gBAAgB,CAAC,CAAC,OAAO,EAC1D,EAAE,CAAC,CACF,MAAM;EAER,QAAA,GAAOC,mBAAAA,oBAAAA,CAAoB,gBAAgB;CAC5C;AACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object-storage.d.cts","names":[],"sources":["../src/object-storage.ts"],"mappings":";;;;;;iBA2BiB;;EAEhB;;;;;EAKA,SAAS;;qBAGG,cAAc,0CACf,UAAU,OAAO;mBAiBV;WAfT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ;;;;;;mBAO9B;;mBAGA;EAEjB,YACC,IAAI,cAAc,QACD,UAAS;
|
|
1
|
+
{"version":3,"file":"object-storage.d.cts","names":[],"sources":["../src/object-storage.ts"],"mappings":";;;;;;iBA2BiB;;EAEhB;;;;;EAKA,SAAS;;qBAGG,cAAc,0CACf,UAAU,OAAO;mBAiBV;WAfT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ;;;;;;mBAO9B;;mBAGA;EAEjB,YACC,IAAI,cAAc,QACD,UAAS;EAuB3B,WAAW;;;;;;;;UAmBG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object-storage.d.mts","names":[],"sources":["../src/object-storage.ts"],"mappings":";;;;;;iBA2BiB;;EAEhB;;;;;EAKA,SAAS;;qBAGG,cAAc,0CACf,UAAU,OAAO;mBAiBV;WAfT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ;;;;;;mBAO9B;;mBAGA;EAEjB,YACC,IAAI,cAAc,QACD,UAAS;
|
|
1
|
+
{"version":3,"file":"object-storage.d.mts","names":[],"sources":["../src/object-storage.ts"],"mappings":";;;;;;iBA2BiB;;EAEhB;;;;;EAKA,SAAS;;qBAGG,cAAc,0CACf,UAAU,OAAO;mBAiBV;WAfT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ;;;;;;mBAO9B;;mBAGA;EAEjB,YACC,IAAI,cAAc,QACD,UAAS;EAuB3B,WAAW;;;;;;;;UAmBG"}
|
package/dist/object-storage.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as ExpiryPrefixInvalid, r as expiryDays, t as ExpiryDaysInvalid } from "./expire-CpzUAfr9.mjs";
|
|
2
|
-
import { canonicalId,
|
|
2
|
+
import { canonicalId, providedKeyFor, serviceKey } from "@geekmidas/manifest";
|
|
3
3
|
import { createStorageClient } from "@geekmidas/storage";
|
|
4
4
|
//#region src/object-storage.ts
|
|
5
5
|
/**
|
|
@@ -26,7 +26,7 @@ var ObjectStorage = class {
|
|
|
26
26
|
this.options = options;
|
|
27
27
|
const canonical = canonicalId(id);
|
|
28
28
|
this.id = canonical;
|
|
29
|
-
this.keys = { connectionString:
|
|
29
|
+
this.keys = { connectionString: providedKeyFor(canonical, "objects", "connectionString") };
|
|
30
30
|
this.expire = expiryDays(canonical, options.expire);
|
|
31
31
|
this.service = {
|
|
32
32
|
serviceName: serviceKey(canonical),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object-storage.mjs","names":[],"sources":["../src/object-storage.ts"],"sourcesContent":["/**\n * `ObjectStorage` — a declared bucket.\n *\n * Where the three packages meet: it implements the construct contract, derives\n * its env key through `@geekmidas/manifest`, and hands back a\n * `@geekmidas/storage` client. It names no cloud — `--target=aws` fills the\n * injected URL with S3's values, local dev with MinIO's.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\
|
|
1
|
+
{"version":3,"file":"object-storage.mjs","names":[],"sources":["../src/object-storage.ts"],"sourcesContent":["/**\n * `ObjectStorage` — a declared bucket.\n *\n * Where the three packages meet: it implements the construct contract, derives\n * its env key through `@geekmidas/manifest`, and hands back a\n * `@geekmidas/storage` client. It names no cloud — `--target=aws` fills the\n * injected URL with S3's values, local dev with MinIO's.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tprovidedKeyFor,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { createStorageClient, type StorageClient } from '@geekmidas/storage';\nimport type { Construct } from './construct-interface';\nimport { expiryDays, type ObjectExpiry } from './expire';\n\nexport {\n\tExpiryDaysInvalid,\n\tExpiryPrefixInvalid,\n\ttype ObjectExpiry,\n} from './expire';\n\nexport interface ObjectStorageOptions {\n\t/** Keep previous versions of an object. */\n\tversioned?: boolean;\n\t/**\n\t * Delete the objects under each prefix this many days after they were\n\t * written — `{ 'quotes/': { days: 30 } }`.\n\t */\n\texpire?: ObjectExpiry;\n}\n\nexport class ObjectStorage<TName extends string = string>\n\timplements Construct<TName, StorageClient>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, StorageClient>;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the key the\n\t * build publishes and the key the client reads cannot drift — the whole point\n\t * of the construct owning both faces.\n\t */\n\tprivate readonly keys: { connectionString: string };\n\n\t/** Checked once, at declaration: prefix → days. */\n\tprivate readonly expire: Record<string, number> | undefined;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: ObjectStorageOptions = {},\n\t) {\n\t\t// Canonicalises, so `uploads` and `Uploads` are one construct rather than\n\t\t// two that collide. Throws on anything that cannot become a valid id.\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.keys = {\n\t\t\tconnectionString: providedKeyFor(\n\t\t\t\tcanonical,\n\t\t\t\t'objects',\n\t\t\t\t'connectionString',\n\t\t\t),\n\t\t};\n\t\tthis.expire = expiryDays(canonical, options.expire);\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (options) => this.connect(options),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'objects',\n\t\t\t\tid: this.id,\n\t\t\t\tprovides: [this.keys.connectionString],\n\t\t\t\t...(this.options.versioned ? { versioned: true } : {}),\n\t\t\t\t...(this.expire ? { expire: this.expire } : {}),\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Builds the client from the connection string the adapter supplied.\n\t *\n\t * Its scheme selects the driver, so this construct imports no provider\n\t * and an app that never touches S3 never resolves the AWS SDK. Whoever\n\t * assembles the application registers the drivers its target needs.\n\t */\n\tprivate async connect({\n\t\tenvParser,\n\t}: ServiceRegisterOptions): Promise<StorageClient> {\n\t\tconst { connectionString } = envParser\n\t\t\t.create((get) => ({\n\t\t\t\tconnectionString: get(this.keys.connectionString).string(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\treturn createStorageClient(connectionString);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AAqCA,IAAa,gBAAb,MAEA;CAgBmB;CAflB;CACA;;;;;;CAOA;;CAGA;CAEA,YACC,IACA,UAAiD,CAAC,GACjD;EADgB,KAAA,UAAA;EAIjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,OAAO,EACX,kBAAkB,eACjB,WACA,WACA,kBACD,EACD;EACA,KAAK,SAAS,WAAW,WAAW,QAAQ,MAAM;EAGlD,KAAK,UAAU;GACd,aAAa,WAAW,SAAS;GACjC,WAAW,YAAY,KAAK,QAAQ,OAAO;EAC5C;CACD;CAEA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,UAAU,CAAC,KAAK,KAAK,gBAAgB;GACrC,GAAI,KAAK,QAAQ,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;GACpD,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;EAC9C,CACD;CACD;;;;;;;;CASA,MAAc,QAAQ,EACrB,aACkD;EAClD,MAAM,EAAE,qBAAqB,UAC3B,QAAQ,SAAS,EACjB,kBAAkB,IAAI,KAAK,KAAK,gBAAgB,CAAC,CAAC,OAAO,EAC1D,EAAE,CAAC,CACF,MAAM;EAER,OAAO,oBAAoB,gBAAgB;CAC5C;AACD"}
|
package/dist/queue/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_Queue = require("../Queue-
|
|
3
|
-
const require_QueueBuilder = require("../QueueBuilder-
|
|
2
|
+
const require_Queue = require("../Queue-W1wueijP.cjs");
|
|
3
|
+
const require_QueueBuilder = require("../QueueBuilder-BDcv9B71.cjs");
|
|
4
4
|
exports.Queue = require_Queue.Queue;
|
|
5
5
|
exports.QueueNeedsMessage = require_QueueBuilder.QueueNeedsMessage;
|
|
6
6
|
exports.QueueNeedsName = require_QueueBuilder.QueueNeedsName;
|
package/dist/queue/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { t as Queue } from "../Queue-
|
|
2
|
-
import { n as QueueNeedsMessage, r as QueueNeedsName } from "../QueueBuilder-
|
|
1
|
+
import { t as Queue } from "../Queue-9Hh20ZCk.mjs";
|
|
2
|
+
import { n as QueueNeedsMessage, r as QueueNeedsName } from "../QueueBuilder-CrZL8HHs.mjs";
|
|
3
3
|
export { Queue, QueueNeedsMessage, QueueNeedsName };
|
package/dist/rest-api.cjs
CHANGED
|
@@ -62,10 +62,15 @@ var RestApi = class RestApi {
|
|
|
62
62
|
this.authenticator = authenticator;
|
|
63
63
|
const canonical = (0, _geekmidas_manifest.canonicalId)(id);
|
|
64
64
|
this.id = canonical;
|
|
65
|
+
(0, _geekmidas_manifest.assertHostLabels)({
|
|
66
|
+
id: canonical,
|
|
67
|
+
...config.subdomain ? { subdomain: config.subdomain } : {},
|
|
68
|
+
...config.aliases ? { aliases: config.aliases } : {}
|
|
69
|
+
});
|
|
65
70
|
this.keys = {
|
|
66
|
-
url: (0, _geekmidas_manifest.
|
|
67
|
-
trustedOrigins: (0, _geekmidas_manifest.
|
|
68
|
-
cookieDomain: (0, _geekmidas_manifest.
|
|
71
|
+
url: (0, _geekmidas_manifest.providedKeyFor)(canonical, "rest-api", "url"),
|
|
72
|
+
trustedOrigins: (0, _geekmidas_manifest.providedKeyFor)(canonical, "rest-api", "trustedOrigins"),
|
|
73
|
+
cookieDomain: (0, _geekmidas_manifest.providedKeyFor)(canonical, "rest-api", "cookieDomain")
|
|
69
74
|
};
|
|
70
75
|
const url = this.keys.url;
|
|
71
76
|
this.service = {
|
|
@@ -183,6 +188,7 @@ var RestApi = class RestApi {
|
|
|
183
188
|
id: this.id,
|
|
184
189
|
path: this.config.path,
|
|
185
190
|
...this.config.subdomain ? { subdomain: this.config.subdomain } : {},
|
|
191
|
+
...this.config.aliases?.length ? { aliases: [...this.config.aliases] } : {},
|
|
186
192
|
...this.config.telescope ? { telescope: true } : {},
|
|
187
193
|
...this.config.cors ? { cors: this.config.cors } : {},
|
|
188
194
|
...this.authenticator ? { auth: require_construct_interface.edgeTo(this.authenticator) } : {},
|
|
@@ -199,6 +205,12 @@ var RestApi = class RestApi {
|
|
|
199
205
|
}
|
|
200
206
|
};
|
|
201
207
|
//#endregion
|
|
208
|
+
Object.defineProperty(exports, "InvalidHostLabel", {
|
|
209
|
+
enumerable: true,
|
|
210
|
+
get: function() {
|
|
211
|
+
return _geekmidas_manifest.InvalidHostLabel;
|
|
212
|
+
}
|
|
213
|
+
});
|
|
202
214
|
exports.RestApi = RestApi;
|
|
203
215
|
|
|
204
216
|
//# sourceMappingURL=rest-api.cjs.map
|