@shware/workflow 7.0.0 → 9.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +125 -35
- package/dist/aws/engine-step.cjs +4 -1
- package/dist/aws/engine-step.cjs.map +1 -1
- package/dist/aws/engine-step.d.cts.map +1 -1
- package/dist/aws/engine-step.d.mts.map +1 -1
- package/dist/aws/engine-step.mjs +4 -1
- package/dist/aws/engine-step.mjs.map +1 -1
- package/dist/aws/index.cjs +3 -3
- package/dist/aws/index.cjs.map +1 -1
- package/dist/aws/index.mjs +3 -3
- package/dist/aws/index.mjs.map +1 -1
- package/dist/client.cjs +66 -41
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +72 -22
- package/dist/client.d.cts.map +1 -1
- package/dist/client.d.mts +72 -22
- package/dist/client.d.mts.map +1 -1
- package/dist/client.mjs +66 -42
- package/dist/client.mjs.map +1 -1
- package/dist/cloudflare/index.d.cts +5 -4
- package/dist/cloudflare/index.d.mts +5 -4
- package/dist/cloudflare/runner.cjs +3 -1
- package/dist/cloudflare/runner.cjs.map +1 -1
- package/dist/cloudflare/runner.d.cts.map +1 -1
- package/dist/cloudflare/runner.d.mts.map +1 -1
- package/dist/cloudflare/runner.mjs +3 -1
- package/dist/cloudflare/runner.mjs.map +1 -1
- package/dist/cloudflare/worker.cjs +12 -1
- package/dist/cloudflare/worker.cjs.map +1 -1
- package/dist/cloudflare/worker.d.cts +9 -1
- package/dist/cloudflare/worker.d.cts.map +1 -1
- package/dist/cloudflare/worker.d.mts +9 -1
- package/dist/cloudflare/worker.d.mts.map +1 -1
- package/dist/cloudflare/worker.mjs +12 -1
- package/dist/cloudflare/worker.mjs.map +1 -1
- package/dist/contract.cjs.map +1 -1
- package/dist/contract.d.cts +4 -4
- package/dist/contract.d.mts +4 -4
- package/dist/contract.mjs.map +1 -1
- package/dist/dsl/trigger.cjs +2 -1
- package/dist/dsl/trigger.cjs.map +1 -1
- package/dist/dsl/trigger.d.cts +6 -0
- package/dist/dsl/trigger.d.cts.map +1 -1
- package/dist/dsl/trigger.d.mts +6 -0
- package/dist/dsl/trigger.d.mts.map +1 -1
- package/dist/dsl/trigger.mjs +2 -1
- package/dist/dsl/trigger.mjs.map +1 -1
- package/dist/engine/condition.cjs +3 -3
- package/dist/engine/condition.cjs.map +1 -1
- package/dist/engine/condition.d.cts +3 -3
- package/dist/engine/condition.d.mts +3 -3
- package/dist/engine/condition.mjs +3 -3
- package/dist/engine/condition.mjs.map +1 -1
- package/dist/engine/interpreter.cjs +9 -5
- package/dist/engine/interpreter.cjs.map +1 -1
- package/dist/engine/interpreter.d.cts.map +1 -1
- package/dist/engine/interpreter.d.mts.map +1 -1
- package/dist/engine/interpreter.mjs +9 -5
- package/dist/engine/interpreter.mjs.map +1 -1
- package/dist/engine/ports.d.cts +2 -0
- package/dist/engine/ports.d.cts.map +1 -1
- package/dist/engine/ports.d.mts +2 -0
- package/dist/engine/ports.d.mts.map +1 -1
- package/dist/host/batch.cjs +172 -0
- package/dist/host/batch.cjs.map +1 -0
- package/dist/host/batch.d.cts +88 -0
- package/dist/host/batch.d.cts.map +1 -0
- package/dist/host/batch.d.mts +88 -0
- package/dist/host/batch.d.mts.map +1 -0
- package/dist/host/batch.mjs +163 -0
- package/dist/host/batch.mjs.map +1 -0
- package/dist/host/execute.cjs +10 -6
- package/dist/host/execute.cjs.map +1 -1
- package/dist/host/execute.mjs +10 -6
- package/dist/host/execute.mjs.map +1 -1
- package/dist/host/http.cjs +30 -89
- package/dist/host/http.cjs.map +1 -1
- package/dist/host/http.d.cts +1 -1
- package/dist/host/http.d.cts.map +1 -1
- package/dist/host/http.d.mts +1 -1
- package/dist/host/http.d.mts.map +1 -1
- package/dist/host/http.mjs +24 -83
- package/dist/host/http.mjs.map +1 -1
- package/dist/host/ingest.cjs +84 -35
- package/dist/host/ingest.cjs.map +1 -1
- package/dist/host/ingest.d.cts +29 -16
- package/dist/host/ingest.d.cts.map +1 -1
- package/dist/host/ingest.d.mts +29 -16
- package/dist/host/ingest.d.mts.map +1 -1
- package/dist/host/ingest.mjs +83 -36
- package/dist/host/ingest.mjs.map +1 -1
- package/dist/host/journey-host.cjs +6 -0
- package/dist/host/journey-host.cjs.map +1 -1
- package/dist/host/journey-host.d.cts +5 -2
- package/dist/host/journey-host.d.cts.map +1 -1
- package/dist/host/journey-host.d.mts +5 -2
- package/dist/host/journey-host.d.mts.map +1 -1
- package/dist/host/journey-host.mjs +6 -0
- package/dist/host/journey-host.mjs.map +1 -1
- package/dist/host/platform.cjs.map +1 -1
- package/dist/host/platform.d.cts +2 -0
- package/dist/host/platform.d.cts.map +1 -1
- package/dist/host/platform.d.mts +2 -0
- package/dist/host/platform.d.mts.map +1 -1
- package/dist/host/platform.mjs.map +1 -1
- package/dist/ir.cjs +2 -1
- package/dist/ir.cjs.map +1 -1
- package/dist/ir.d.cts +3 -0
- package/dist/ir.d.cts.map +1 -1
- package/dist/ir.d.mts +3 -0
- package/dist/ir.d.mts.map +1 -1
- package/dist/ir.mjs +2 -1
- package/dist/ir.mjs.map +1 -1
- package/dist/store/condition-sql.cjs +144 -0
- package/dist/store/condition-sql.cjs.map +1 -0
- package/dist/store/condition-sql.d.cts +38 -0
- package/dist/store/condition-sql.d.cts.map +1 -0
- package/dist/store/condition-sql.d.mts +38 -0
- package/dist/store/condition-sql.d.mts.map +1 -0
- package/dist/store/condition-sql.mjs +143 -0
- package/dist/store/condition-sql.mjs.map +1 -0
- package/dist/store/facts.cjs +13 -9
- package/dist/store/facts.cjs.map +1 -1
- package/dist/store/facts.d.cts +6 -2
- package/dist/store/facts.d.cts.map +1 -1
- package/dist/store/facts.d.mts +6 -2
- package/dist/store/facts.d.mts.map +1 -1
- package/dist/store/facts.mjs +13 -9
- package/dist/store/facts.mjs.map +1 -1
- package/dist/store/identity.cjs +34 -0
- package/dist/store/identity.cjs.map +1 -0
- package/dist/store/identity.d.cts +13 -0
- package/dist/store/identity.d.cts.map +1 -0
- package/dist/store/identity.d.mts +13 -0
- package/dist/store/identity.d.mts.map +1 -0
- package/dist/store/identity.mjs +30 -0
- package/dist/store/identity.mjs.map +1 -0
- package/dist/store/index.cjs +5 -0
- package/dist/store/index.cjs.map +1 -1
- package/dist/store/index.d.cts +67 -21
- package/dist/store/index.d.cts.map +1 -1
- package/dist/store/index.d.mts +67 -21
- package/dist/store/index.d.mts.map +1 -1
- package/dist/store/index.mjs +2 -1
- package/dist/store/index.mjs.map +1 -1
- package/dist/store/postgres.cjs +248 -54
- package/dist/store/postgres.cjs.map +1 -1
- package/dist/store/postgres.d.cts +25 -7
- package/dist/store/postgres.d.cts.map +1 -1
- package/dist/store/postgres.d.mts +25 -7
- package/dist/store/postgres.d.mts.map +1 -1
- package/dist/store/postgres.mjs +249 -55
- package/dist/store/postgres.mjs.map +1 -1
- package/dist/store/tables.cjs +24 -6
- package/dist/store/tables.cjs.map +1 -1
- package/dist/store/tables.d.cts +1 -0
- package/dist/store/tables.d.cts.map +1 -1
- package/dist/store/tables.d.mts +1 -0
- package/dist/store/tables.d.mts.map +1 -1
- package/dist/store/tables.mjs +24 -6
- package/dist/store/tables.mjs.map +1 -1
- package/dist/webpush.cjs.map +1 -1
- package/dist/webpush.d.cts +1 -1
- package/dist/webpush.d.mts +1 -1
- package/dist/webpush.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tables.d.cts","names":[],"sources":["../../src/store/tables.ts"],"mappings":";;;;;;;;;;;;YAaY;iBAEK;EACf,MAAM;;EAEN;;EAEA;;;;;;;iBAQe,qBAAqB;EACpC,kBAAkB;EAClB;;iBAGe,UAAU;;EAEzB;EACA;;EAEA,SAAS,OAAO,GAAG;;EAEnB,sBAAsB;;EAEtB,SAAS;EACT,mCAAmC;;EAEnC,6BAA6B,qBAAqB;EAClD,6BAA6B;;EAE7B;IACE,kBAAkB;IAClB;IACA;;;qBAoBS
|
|
1
|
+
{"version":3,"file":"tables.d.cts","names":[],"sources":["../../src/store/tables.ts"],"mappings":";;;;;;;;;;;;YAaY;iBAEK;EACf,MAAM;;EAEN;;EAEA;;;;;;;iBAQe,qBAAqB;EACpC,kBAAkB;EAClB;;iBAGe,UAAU;;EAEzB;EACA;;EAEA,SAAS,OAAO,GAAG;;EAEnB,sBAAsB;;EAEtB,SAAS;EACT,mCAAmC;;EAEnC,6BAA6B,qBAAqB;EAClD,6BAA6B;;EAE7B;IACE,kBAAkB;IAClB;IACA;;;qBAoBS;;;;;;;;;;;;;;;;;;;;;;;;YAuUD,wBAAwB;;qBAGvB;;wBAGG,WAAW;;wBAOX,qBAAqB,MAAM,WAAW,QAAQ;;wBAK9C,UAAU,MAAM,WAAW;;;;;;wBAkB3B,kBAAkB;;;;;;;;wBAqHlB,oBAAoB"}
|
package/dist/store/tables.d.mts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tables.d.mts","names":[],"sources":["../../src/store/tables.ts"],"mappings":";;;;;;;;;;;;YAaY;iBAEK;EACf,MAAM;;EAEN;;EAEA;;;;;;;iBAQe,qBAAqB;EACpC,kBAAkB;EAClB;;iBAGe,UAAU;;EAEzB;EACA;;EAEA,SAAS,OAAO,GAAG;;EAEnB,sBAAsB;;EAEtB,SAAS;EACT,mCAAmC;;EAEnC,6BAA6B,qBAAqB;EAClD,6BAA6B;;EAE7B;IACE,kBAAkB;IAClB;IACA;;;qBAoBS
|
|
1
|
+
{"version":3,"file":"tables.d.mts","names":[],"sources":["../../src/store/tables.ts"],"mappings":";;;;;;;;;;;;YAaY;iBAEK;EACf,MAAM;;EAEN;;EAEA;;;;;;;iBAQe,qBAAqB;EACpC,kBAAkB;EAClB;;iBAGe,UAAU;;EAEzB;EACA;;EAEA,SAAS,OAAO,GAAG;;EAEnB,sBAAsB;;EAEtB,SAAS;EACT,mCAAmC;;EAEnC,6BAA6B,qBAAqB;EAClD,6BAA6B;;EAE7B;IACE,kBAAkB;IAClB;IACA;;;qBAoBS;;;;;;;;;;;;;;;;;;;;;;;;YAuUD,wBAAwB;;qBAGvB;;wBAGG,WAAW;;wBAOX,qBAAqB,MAAM,WAAW,QAAQ;;wBAK9C,UAAU,MAAM,WAAW;;;;;;wBAkB3B,kBAAkB;;;;;;;;wBAqHlB,oBAAoB"}
|
package/dist/store/tables.mjs
CHANGED
|
@@ -36,24 +36,41 @@ const TABLES = {
|
|
|
36
36
|
}),
|
|
37
37
|
profile: table({
|
|
38
38
|
name: "profile",
|
|
39
|
-
doc: "Identified properties per user (`/
|
|
39
|
+
doc: "Identified properties per user (`/ingest` merges into `props`; a null value means unset).",
|
|
40
40
|
columns: {
|
|
41
41
|
userId: text,
|
|
42
|
-
props: jsonb
|
|
42
|
+
props: jsonb,
|
|
43
|
+
propsAt: nullable(jsonb, "When each property was last written, epoch ms by key (a cleared one too): an older patch cannot overwrite it. Null for a row older than this column.")
|
|
43
44
|
},
|
|
44
45
|
primaryKey: ["userId"]
|
|
45
46
|
}),
|
|
46
47
|
device: table({
|
|
47
48
|
name: "device",
|
|
48
|
-
doc: "Push devices,
|
|
49
|
+
doc: "Push devices, one row per device, holding only who it belongs to now (`JourneyClient.registerDevice`): a signed-in `user_id`, or a `visitor_id` alone before sign-in. Signing out clears both rather than removing the row; a token APNs / FCM reports as gone is removed.",
|
|
49
50
|
columns: {
|
|
50
|
-
|
|
51
|
+
deviceId: nullable(text, "The device across token rotations: a new token replaces the old one. Null when the producer sent none."),
|
|
51
52
|
userId: nullable(text),
|
|
53
|
+
visitorId: nullable(text, "The visitor on the device now, kept once signed in: it tells one of a user's devices from another."),
|
|
54
|
+
token: text,
|
|
52
55
|
platform: text,
|
|
53
|
-
ts
|
|
56
|
+
createdAt: ts,
|
|
57
|
+
updatedAt: ts
|
|
54
58
|
},
|
|
55
59
|
primaryKey: ["token"],
|
|
56
|
-
|
|
60
|
+
uniqueIndexes: [["deviceId"]],
|
|
61
|
+
indexes: [["userId"], ["visitorId"]]
|
|
62
|
+
}),
|
|
63
|
+
visitor: table({
|
|
64
|
+
name: "visitor",
|
|
65
|
+
doc: "Visitors the engine has heard from. `user_id` is who they became (`linkVisitor`): a late event of the visitor reaches the user, and the row outlives the user's erasure, so such an event finds the tombstone instead of starting a new visitor. One that never signs in is pruned once idle.",
|
|
66
|
+
columns: {
|
|
67
|
+
visitorId: text,
|
|
68
|
+
userId: nullable(text),
|
|
69
|
+
createdAt: ts,
|
|
70
|
+
updatedAt: ts
|
|
71
|
+
},
|
|
72
|
+
primaryKey: ["visitorId"],
|
|
73
|
+
indexes: [["userId"], ["updatedAt"]]
|
|
57
74
|
}),
|
|
58
75
|
erasure: table({
|
|
59
76
|
name: "erasure",
|
|
@@ -102,6 +119,7 @@ const TABLES = {
|
|
|
102
119
|
event: text,
|
|
103
120
|
where: nullable(jsonb),
|
|
104
121
|
filter: nullable(jsonb),
|
|
122
|
+
visitors: nullable({ type: "boolean" }, "Whether a visitor not signed in may enter (`trigger.event(e.x, { visitors: true })`); signed-in users only otherwise."),
|
|
105
123
|
version: nullable(text, "The code version whose compiled bundle put this route here (null after a forced deploy): an instance it starts runs on that version, so its IR and its code always match.")
|
|
106
124
|
},
|
|
107
125
|
primaryKey: ["workflow"],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tables.mjs","names":[],"sources":["../../src/store/tables.ts"],"sourcesContent":["/**\n * The engine's Postgres tables, declared once. Everything that needs their shape derives it from\n * here: the drizzle schema file a host generates and migrates with its own tooling\n * (`renderDrizzleSchema`), the plain DDL (`renderPostgresDdl`), the store's table names, and the\n * check a deploy runs against the live database (`checkPostgresSchema`).\n *\n * The house rules hold for every table: no database defaults (the store writes every value,\n * timestamps included), timestamptz for time, and a UUID v7 row id — generated by the store and\n * guarded by a CHECK — wherever a table has a surrogate key. All tables live in one Postgres\n * schema of their own (`workflow` unless the config names another), so their short names never\n * meet the app's.\n */\n\nexport type ColumnType = 'uuid' | 'text' | 'jsonb' | 'timestamptz' | 'integer' | 'boolean';\n\nexport interface ColumnSpec {\n type: ColumnType;\n /** Columns are NOT NULL unless marked. */\n nullable?: boolean;\n /** One line for the generated file. */\n doc?: string;\n}\n\n/**\n * A unique constraint whose key may hold nulls, with `NULLS NOT DISTINCT` (Postgres 15+) so two\n * rows null in the same column still collide — the identity of a table whose key has an\n * optional part, where a primary key (NOT NULL throughout) cannot be.\n */\nexport interface UniqueConstraintSpec<K extends string = string> {\n columns: readonly K[];\n nullsNotDistinct: true;\n}\n\nexport interface TableSpec<K extends string = string> {\n /** Physical table name inside the schema. */\n name: string;\n doc: string;\n /** Keyed by the drizzle property name; the column name is its snake_case. */\n columns: Record<K, ColumnSpec>;\n /** Absent for a table whose identity is a `uniqueConstraints` entry (a nullable key part). */\n primaryKey?: readonly K[];\n /** A uuid column whose values must be version 7. */\n uuidV7?: K;\n uniqueIndexes?: readonly (readonly K[])[];\n /** Named `<table>_<columns>_unique`, as drizzle names an unnamed `unique()`. */\n uniqueConstraints?: readonly UniqueConstraintSpec<K>[];\n indexes?: readonly (readonly K[])[];\n /** Foreign keys, to another table's logical key. */\n references?: readonly {\n columns: readonly K[];\n table: string;\n foreignColumns: readonly string[];\n }[];\n}\n\nfunction table<K extends string>(spec: TableSpec<K>): TableSpec<K> {\n return spec;\n}\n\nconst uuid = { type: 'uuid' } as const;\nconst text = { type: 'text' } as const;\nconst jsonb = { type: 'jsonb' } as const;\nconst ts = { type: 'timestamptz' } as const;\nconst integer = { type: 'integer' } as const;\nconst boolean = { type: 'boolean' } as const;\nconst nullable = <C extends ColumnSpec>(column: C, doc?: string): ColumnSpec => ({\n ...column,\n nullable: true,\n ...(doc === undefined ? {} : { doc }),\n});\n\nexport const TABLES = {\n event: table({\n name: 'event',\n doc: \"Every ingested event, the fact base for `performed(...)` conditions. `event_id` is the occurrence's identity as the sender chose it (a retrying producer sends the same one again), scoped to the user: the (user_id, event_id) unique index makes a second delivery a no-op, and one sender's id can never block another user's event.\",\n columns: { id: uuid, eventId: text, userId: text, name: text, ts, payload: jsonb },\n primaryKey: ['id'],\n uuidV7: 'id',\n uniqueIndexes: [['userId', 'eventId']],\n indexes: [['userId', 'name', 'ts']],\n }),\n profile: table({\n name: 'profile',\n doc: 'Identified properties per user (`/identify` merges into `props`; a null value means unset).',\n columns: { userId: text, props: jsonb },\n primaryKey: ['userId'],\n }),\n device: table({\n name: 'device',\n doc: 'Push devices, registered through the Worker (`JourneyClient.registerDevice`). Signing out unbinds a device (`user_id` null) rather than removing it; a token APNs / FCM reports as gone is removed.',\n columns: { token: text, userId: nullable(text), platform: text, ts },\n primaryKey: ['token'],\n indexes: [['userId']],\n }),\n erasure: table({\n name: 'erasure',\n doc: \"Erasure tombstones (`forgetUser`): every write about a user is conditional on no row here. While `erased_at` is null the user's data stays until every running instance is stopped, and the scheduled sweep retries what is left; once set, the data is gone and the row stays so the user id is never written again.\",\n columns: {\n userId: text,\n requestedAt: ts,\n erasedAt: nullable(ts, 'When the data was erased; null while the erasure is under way.'),\n },\n primaryKey: ['userId'],\n }),\n suppression: table({\n name: 'suppression',\n doc: 'What a user opted out of: a topic on a channel (an email unsubscribe from one topic, a push topic switched off in the app), or the whole channel when `topic` is null — the engine sends nothing there, and `reachable(channel)` is false. One row per (user, channel, topic), nulls included.',\n columns: {\n userId: text,\n channel: text,\n topic: nullable(\n text,\n 'The subscription topic opted out of; null for the whole channel (every row from before topics existed).'\n ),\n ts,\n },\n uniqueConstraints: [{ columns: ['userId', 'channel', 'topic'], nullsNotDistinct: true }],\n }),\n segment: table({\n name: 'segment',\n doc: 'Deployed segment definitions, resolved by name at evaluation time.',\n columns: { id: text, condition: jsonb, hash: text },\n primaryKey: ['id'],\n }),\n trigger: table({\n name: 'trigger',\n doc: 'Event-trigger routes: `where` gates on the event payload, `filter` on the profile.',\n columns: {\n workflow: text,\n hash: text,\n event: text,\n where: nullable(jsonb),\n filter: nullable(jsonb),\n version: nullable(\n text,\n 'The code version whose compiled bundle put this route here (null after a forced deploy): an instance it starts runs on that version, so its IR and its code always match.'\n ),\n },\n primaryKey: ['workflow'],\n indexes: [['event']],\n }),\n segmentTrigger: table({\n name: 'segment_trigger',\n doc: 'Segment-entry trigger routes.',\n columns: {\n workflow: text,\n hash: text,\n segment: text,\n version: nullable(\n text,\n 'The code version whose compiled bundle put this route here (null after a forced deploy): an instance it starts runs on that version, so its IR and its code always match.'\n ),\n },\n primaryKey: ['workflow'],\n indexes: [['segment']],\n }),\n segmentMember: table({\n name: 'segment_member',\n doc: 'Who is in each deployed segment and since when: kept by the scheduled sweep, and for trigger-routed segments on every event too.',\n columns: { segment: text, userId: text, ts },\n primaryKey: ['segment', 'userId'],\n }),\n segmentStart: table({\n name: 'segment_start',\n doc: 'Workflows a segment entry still has to start for a member: written with the membership, removed as each one starts, so a failed start is retried by the next evaluation instead of being hidden behind the membership.',\n columns: { segment: text, workflow: text, userId: text, ts },\n primaryKey: ['segment', 'workflow', 'userId'],\n }),\n segmentSnapshot: table({\n name: 'segment_snapshot',\n doc: \"Each segment's size at every sweep, the Studio's sparklines.\",\n columns: { segment: text, takenAt: ts, size: integer },\n primaryKey: ['segment', 'takenAt'],\n }),\n entry: table({\n name: 'entry',\n doc: 'Entry ledger: the (workflow, user) primary key is the once policy.',\n columns: {\n workflow: text,\n userId: text,\n instanceId: text,\n hash: text,\n status: text,\n ts,\n admittedAt: nullable(\n ts,\n 'When the runner admitted itself (`admitInstance`), before its first observable effect; null until then, so an erasure knows nothing of the instance has run yet.'\n ),\n claimedAt: nullable(\n ts,\n \"When this attempt claimed the entry (insert or reclaim), by the host's clock. `ts` is the triggering event's own time, which a producer may set far in the past, so only this tells how long an entry has waited for its instance; maintenance fails an entry left unadmitted with no instance behind it. Null on rows written before the column existed.\"\n ),\n },\n primaryKey: ['workflow', 'userId'],\n // admittedAt: maintenance looks up the few entries still unadmitted (`IS NULL` uses it)\n indexes: [['instanceId'], ['admittedAt']],\n }),\n subscription: table({\n name: 'subscription',\n doc: 'wait_until wake routing; the primary key makes repeated subscribes idempotent.',\n columns: { userId: text, event: text, wakeHandle: text, ts },\n primaryKey: ['wakeHandle', 'event'],\n indexes: [['userId', 'event']],\n }),\n execution: table({\n name: 'execution',\n doc: 'Durable executions whose start is an asynchronous submit (AWS Lambda durable functions): written with the entry, so a lost submit response is retried with the same name, target and payload instead of starting a second execution; and the wake callback the instance is parked on now. Unused on Cloudflare.',\n columns: {\n instanceId: text,\n workflow: text,\n userId: text,\n name: text,\n target: text,\n input: text,\n createdAt: ts,\n submittedAt: nullable(\n ts,\n 'The runtime accepted the start; null while it may still have to be retried.'\n ),\n arn: nullable(text),\n unresolvedAt: nullable(\n ts,\n 'Retries ran out before the runtime confirmed the start: whether it runs is unknown, and nothing retries it.'\n ),\n callbackId: nullable(text, 'The callback the current wait parks on; a wake completes it.'),\n generation: integer,\n deadlineAt: nullable(ts),\n checkedAt: nullable(\n ts,\n \"When maintenance last compared the runtime's status with the ledger.\"\n ),\n stoppedAt: nullable(\n ts,\n 'When it was stopped (an erasure): an invocation already running goes on to its next checkpoint, so the data waits until it has drained.'\n ),\n },\n primaryKey: ['instanceId'],\n indexes: [['workflow', 'userId'], ['submittedAt'], ['userId']],\n }),\n deployment: table({\n name: 'deployment',\n doc: \"The Worker version whose compiled bundle the routes came from, one row (`scope` = 'routes'): journeyWorker applies its own bundle only over an older version, so one still serving during a rollout cannot put its routes back. A forced `POST /bundle/deploy` records the version that served it; a hand-posted `POST /deploy` leaves it as it is.\",\n columns: { scope: text, versionId: text, versionCreatedAt: ts, appliedAt: ts },\n primaryKey: ['scope'],\n }),\n ir: table({\n name: 'ir',\n doc: 'Workflow bodies (WorkflowIR), content-addressed.',\n columns: { contentHash: text, ir: jsonb },\n primaryKey: ['contentHash'],\n }),\n instance: table({\n name: 'instance',\n doc: 'One row per journey instance, written when it enters: the node it sits on or last passed (none when a guard ended it before the first), and how it ended (`running` until then; `goal` is a conversion, at `finished_at`).',\n columns: {\n instanceId: text,\n workflow: text,\n userId: text,\n enteredAt: ts,\n nodeId: nullable(text),\n nodeAt: nullable(ts),\n status: text,\n finishedAt: nullable(ts),\n convertedAt: nullable(\n ts,\n 'When the goal was met, whatever the status: with `exitOnMatch: false` a converted instance ends `completed`.'\n ),\n },\n primaryKey: ['instanceId'],\n indexes: [\n ['workflow', 'status'],\n ['workflow', 'finishedAt'],\n ],\n }),\n message: table({\n name: 'message',\n doc: \"One row per message copy (a push fans out per device). The idempotency key is the engine's copy identity, so a retried step finds the row it wrote; `channel` is where the copy landed (`email`, `push_ios`, `push_android`).\",\n columns: {\n id: uuid,\n idempotencyKey: text,\n workflow: text,\n instanceId: text,\n nodeId: text,\n template: text,\n channel: text,\n userId: text,\n topic: nullable(\n text,\n \"An email or push copy: its template's subscription topic (what an email's unsubscribe link opts out of); null for a transactional message, and for every other channel.\"\n ),\n sentAt: ts,\n deliveredAt: nullable(ts, 'The transport accepted it.'),\n deviceDeliveredAt: nullable(\n ts,\n \"A push: the device reported it received (iOS's notification service extension, a browser's service worker).\"\n ),\n undeliveredReason: nullable(\n text,\n 'The transport settled it without delivering (a dead push token).'\n ),\n openedAt: nullable(ts, 'First open of any kind, by a person or a machine.'),\n humanOpenedAt: nullable(ts, 'First open a person made.'),\n clickedAt: nullable(ts),\n humanClickedAt: nullable(ts),\n unsubscribedAt: nullable(ts),\n },\n primaryKey: ['id'],\n uuidV7: 'id',\n uniqueIndexes: [['idempotencyKey']],\n indexes: [['workflow', 'sentAt'], ['instanceId']],\n }),\n messageLink: table({\n name: 'message_link',\n doc: \"A sent email's links in document order: the tracked URL names a message and a position, and the redirect goes only to the URL recorded here.\",\n columns: { messageId: uuid, position: integer, url: text },\n primaryKey: ['messageId', 'position'],\n references: [{ columns: ['messageId'], table: 'message', foreignColumns: ['id'] }],\n }),\n messageOpen: table({\n name: 'message_open',\n doc: \"Every open-pixel load or push tap, classified when recorded: `machine` when no person caused it, with the deciding rule in `reason`; the request's network (never its address) kept for revisiting the rules.\",\n columns: {\n id: uuid,\n messageId: uuid,\n openedAt: ts,\n machine: boolean,\n reason: nullable(text),\n userAgent: nullable(text),\n asn: nullable(integer),\n asOrganization: nullable(text),\n country: nullable(text),\n },\n primaryKey: ['id'],\n uuidV7: 'id',\n indexes: [['messageId']],\n references: [{ columns: ['messageId'], table: 'message', foreignColumns: ['id'] }],\n }),\n messageClick: table({\n name: 'message_click',\n doc: 'Every click on a tracked link, classified like opens.',\n columns: {\n id: uuid,\n messageId: uuid,\n position: integer,\n url: text,\n clickedAt: ts,\n machine: boolean,\n reason: nullable(text),\n userAgent: nullable(text),\n asn: nullable(integer),\n asOrganization: nullable(text),\n country: nullable(text),\n },\n primaryKey: ['id'],\n uuidV7: 'id',\n indexes: [['messageId']],\n references: [{ columns: ['messageId'], table: 'message', foreignColumns: ['id'] }],\n }),\n} satisfies Record<string, TableSpec>;\n\nexport type TableKey = keyof typeof TABLES;\n\n/** The engine's schema when the config names none. */\nexport const DEFAULT_SCHEMA = 'workflow';\n\n/** `eventId` → `event_id`. */\nexport function columnName(key: string): string {\n return key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);\n}\n\nconst quote = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\n\n/** `<table>_<columns>_unique`: drizzle's name for an unnamed `unique()`, and the index behind it. */\nexport function uniqueConstraintName(spec: TableSpec, unique: UniqueConstraintSpec): string {\n return `${spec.name}_${unique.columns.map(columnName).join('_')}_unique`;\n}\n\n/** `<table>_<columns>_index`: the name drizzle-kit and `renderPostgresDdl` both give an unnamed index. */\nexport function indexName(spec: TableSpec, keys: readonly string[]): string {\n return `${spec.name}_${keys.map(columnName).join('_')}_index`;\n}\n\nconst SQL_TYPES: Record<ColumnType, string> = {\n uuid: 'uuid',\n text: 'text',\n jsonb: 'jsonb',\n timestamptz: 'timestamptz',\n integer: 'integer',\n boolean: 'boolean',\n};\n\n/**\n * Plain Postgres DDL for every table — for a host without a migration tool, and the tests. A\n * host that migrates with drizzle generates `renderDrizzleSchema` instead and lets drizzle-kit\n * write the migration.\n */\nexport function renderPostgresDdl(schema = DEFAULT_SCHEMA): string {\n const s = quote(schema);\n const out = [`CREATE SCHEMA IF NOT EXISTS ${s};`];\n for (const spec of Object.values(TABLES)) {\n const lines = Object.entries(spec.columns).map(\n ([key, column]) =>\n ` ${quote(columnName(key))} ${SQL_TYPES[column.type]}${column.nullable ? '' : ' NOT NULL'}`\n );\n if (spec.primaryKey !== undefined) {\n lines.push(` PRIMARY KEY (${spec.primaryKey.map((k) => quote(columnName(k))).join(', ')})`);\n }\n for (const unique of spec.uniqueConstraints ?? []) {\n const cols = unique.columns.map(columnName);\n lines.push(\n ` CONSTRAINT ${quote(uniqueConstraintName(spec, unique))} UNIQUE NULLS NOT DISTINCT (${cols.map(quote).join(', ')})`\n );\n }\n if (spec.uuidV7 !== undefined) {\n lines.push(\n ` CONSTRAINT ${quote(`${spec.name}_uuid_v7`)} CHECK (substring(${quote(columnName(spec.uuidV7))}::text, 15, 1) = '7')`\n );\n }\n for (const ref of spec.references ?? []) {\n const target = TABLES[ref.table as TableKey];\n lines.push(\n ` FOREIGN KEY (${ref.columns.map((k) => quote(columnName(k))).join(', ')}) REFERENCES ${s}.${quote(target.name)} (${ref.foreignColumns.map((k) => quote(columnName(k))).join(', ')})`\n );\n }\n out.push(`CREATE TABLE IF NOT EXISTS ${s}.${quote(spec.name)} (\\n${lines.join(',\\n')}\\n);`);\n const index = (unique: boolean) => (keys: readonly string[]) => {\n const cols = keys.map(columnName);\n out.push(\n `CREATE ${unique ? 'UNIQUE ' : ''}INDEX IF NOT EXISTS ${quote(indexName(spec, keys))} ON ${s}.${quote(spec.name)} (${cols.map(quote).join(', ')});`\n );\n };\n (spec.uniqueIndexes ?? []).forEach(index(true));\n (spec.indexes ?? []).forEach(index(false));\n }\n return `${out.join('\\n')}\\n`;\n}\n\nconst TIMESTAMP_OPTIONS = \"{ mode: 'string', withTimezone: true }\";\n\nconst DRIZZLE_TYPES: Record<ColumnType, (column: string) => string> = {\n uuid: (c) => `uuid('${c}')`,\n text: (c) => `text('${c}')`,\n jsonb: (c) => `jsonb('${c}')`,\n timestamptz: (c) => `timestamp('${c}', ${TIMESTAMP_OPTIONS})`,\n integer: (c) => `integer('${c}')`,\n boolean: (c) => `boolean('${c}')`,\n};\n\n/** The line width the generated file is laid out for: the formatters' common default. */\nconst PRINT_WIDTH = 100;\n\n/**\n * One `workflowSchema.table(...)` statement, laid out the way a prettier-compatible formatter\n * (prettier, oxfmt, biome) at `PRINT_WIDTH` lays it out, so that formatting the generated file\n * changes nothing and a regeneration shows only real changes: on one line when it fits; else\n * with the last argument \"hugged\" (the columns object, or the constraints arrow when the columns\n * fit on the first line) and its items one per line; else every argument on its own line, the\n * constraints array still collapsed when it fits. A column with a doc comment keeps the columns\n * object expanded, as a comment does for a formatter.\n */\n/** A column line past the width: a formatter breaks the timestamp options object, so this does too. */\nfunction wrapColumn(text: string, indent: string): string {\n if (`${indent}${text},`.length <= PRINT_WIDTH || !text.includes(TIMESTAMP_OPTIONS)) return text;\n return text.replace(\n TIMESTAMP_OPTIONS,\n `{\\n${indent} mode: 'string',\\n${indent} withTimezone: true,\\n${indent}}`\n );\n}\n\nfunction renderTable(\n name: string,\n table: string,\n columns: { doc: string | undefined; text: string }[],\n extras: string[]\n): string {\n const head = `export const ${name} = workflowSchema.table(`;\n const flatColumns = columns.some((c) => c.doc !== undefined)\n ? undefined\n : `{ ${columns.map((c) => c.text).join(', ')} }`;\n const expandedColumns = (indent: string) =>\n `{\\n${columns\n .map(\n (c) =>\n `${c.doc === undefined ? '' : `${indent} /** ${c.doc} */\\n`}${indent} ${wrapColumn(c.text, `${indent} `)},`\n )\n .join('\\n')}\\n${indent}}`;\n const flatExtras = `(table) => [${extras.join(', ')}]`;\n const expandedExtras = (indent: string) =>\n `(table) => [\\n${extras.map((e) => `${indent} ${e},`).join('\\n')}\\n${indent}]`;\n const fits = (line: string) => line.length <= PRINT_WIDTH;\n\n if (flatColumns !== undefined) {\n const oneLine = `${head}'${table}', ${flatColumns}${extras.length === 0 ? '' : `, ${flatExtras}`});`;\n if (fits(oneLine)) return oneLine;\n }\n if (extras.length === 0) return `${head}'${table}', ${expandedColumns('')});`;\n if (flatColumns !== undefined) {\n const first = `${head}'${table}', ${flatColumns}, (table) => [`;\n if (fits(first)) return `${first}\\n${extras.map((e) => ` ${e},`).join('\\n')}\\n]);`;\n }\n const third = fits(` ${flatExtras}`) ? flatExtras : expandedExtras(' ');\n return `${head}\\n '${table}',\\n ${expandedColumns(' ')},\\n ${third}\\n);`;\n}\n\nconst exportName = (key: string) => `workflow${key.charAt(0).toUpperCase()}${key.slice(1)}`;\n\n/**\n * The tables as one drizzle file: `export const workflowSchema = pgSchema(<schema>)` and every\n * table as `workflowSchema.table(...)`. The host re-exports it from its drizzle schema and\n * generates the migration with drizzle-kit, so the migration history stays the host's. The\n * output is deterministic — regenerate and diff it in CI to catch an SDK upgrade that changed the\n * tables.\n */\nexport function renderDrizzleSchema(schema = DEFAULT_SCHEMA): string {\n const specs = Object.entries(TABLES) as [TableKey, TableSpec][];\n const used = new Set<string>(['pgSchema']);\n const body: string[] = [];\n let needsSql = false;\n for (const [key, spec] of specs) {\n const columns = Object.entries(spec.columns).map(([prop, column]) => {\n used.add(column.type === 'timestamptz' ? 'timestamp' : column.type);\n const key =\n spec.primaryKey?.length === 1 && spec.primaryKey[0] === prop ? '.primaryKey()' : '';\n return {\n doc: column.doc,\n text: `${prop}: ${DRIZZLE_TYPES[column.type](columnName(prop))}${key}${column.nullable ? '' : '.notNull()'}`,\n };\n });\n const extras: string[] = [];\n if (spec.primaryKey !== undefined && spec.primaryKey.length > 1) {\n used.add('primaryKey');\n extras.push(\n `primaryKey({ columns: [${spec.primaryKey.map((k) => `table.${k}`).join(', ')}] })`\n );\n }\n for (const keys of spec.uniqueIndexes ?? []) {\n used.add('uniqueIndex');\n extras.push(`uniqueIndex().on(${keys.map((k) => `table.${k}`).join(', ')})`);\n }\n for (const unique of spec.uniqueConstraints ?? []) {\n used.add('unique');\n extras.push(\n `unique().on(${unique.columns.map((k) => `table.${k}`).join(', ')}).nullsNotDistinct()`\n );\n }\n for (const keys of spec.indexes ?? []) {\n used.add('index');\n extras.push(`index().on(${keys.map((k) => `table.${k}`).join(', ')})`);\n }\n for (const ref of spec.references ?? []) {\n used.add('foreignKey');\n extras.push(\n `foreignKey({ columns: [${ref.columns.map((k) => `table.${k}`).join(', ')}], foreignColumns: [${ref.foreignColumns.map((k) => `${exportName(ref.table)}.${k}`).join(', ')}] })`\n );\n }\n if (spec.uuidV7 !== undefined) {\n used.add('check');\n needsSql = true;\n extras.push(\n `check('${spec.name}_uuid_v7', sql\\`substring(\\${table.${spec.uuidV7}}::text, 15, 1) = '7'\\`)`\n );\n }\n body.push(`/** ${spec.doc} */\\n${renderTable(exportName(key), spec.name, columns, extras)}`);\n }\n const imports = [...used].sort();\n return [\n '// Generated by `workflow-ui generate` from @shware/workflow — do not edit; regenerate after',\n '// upgrading the SDK and let drizzle-kit write the migration.',\n ...(needsSql ? [\"import { sql } from 'drizzle-orm';\"] : []),\n `import {\\n${imports.map((name) => ` ${name},`).join('\\n')}\\n} from 'drizzle-orm/pg-core';`,\n '',\n `export const workflowSchema = pgSchema('${schema}');`,\n '',\n body.join('\\n\\n'),\n '',\n ].join('\\n');\n}\n"],"mappings":";AAuDA,SAAS,MAAwB,MAAkC;CACjE,OAAO;AACT;AAEA,MAAM,OAAO,EAAE,MAAM,OAAO;AAC5B,MAAM,OAAO,EAAE,MAAM,OAAO;AAC5B,MAAM,QAAQ,EAAE,MAAM,QAAQ;AAC9B,MAAM,KAAK,EAAE,MAAM,cAAc;AACjC,MAAM,UAAU,EAAE,MAAM,UAAU;AAClC,MAAM,UAAU,EAAE,MAAM,UAAU;AAClC,MAAM,YAAkC,QAAW,SAA8B;CAC/E,GAAG;CACH,UAAU;CACV,GAAI,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,IAAI;AACrC;AAEA,MAAa,SAAS;CACpB,OAAO,MAAM;EACX,MAAM;EACN,KAAK;EACL,SAAS;GAAE,IAAI;GAAM,SAAS;GAAM,QAAQ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ACA,KAAK,KAAK,MAAM;EAChB;CACF,CAAC,CAAC,KAAK,IAAI;AACb"}
|
|
1
|
+
{"version":3,"file":"tables.mjs","names":[],"sources":["../../src/store/tables.ts"],"sourcesContent":["/**\n * The engine's Postgres tables, declared once. Everything that needs their shape derives it from\n * here: the drizzle schema file a host generates and migrates with its own tooling\n * (`renderDrizzleSchema`), the plain DDL (`renderPostgresDdl`), the store's table names, and the\n * check a deploy runs against the live database (`checkPostgresSchema`).\n *\n * The house rules hold for every table: no database defaults (the store writes every value,\n * timestamps included), timestamptz for time, and a UUID v7 row id — generated by the store and\n * guarded by a CHECK — wherever a table has a surrogate key. All tables live in one Postgres\n * schema of their own (`workflow` unless the config names another), so their short names never\n * meet the app's.\n */\n\nexport type ColumnType = 'uuid' | 'text' | 'jsonb' | 'timestamptz' | 'integer' | 'boolean';\n\nexport interface ColumnSpec {\n type: ColumnType;\n /** Columns are NOT NULL unless marked. */\n nullable?: boolean;\n /** One line for the generated file. */\n doc?: string;\n}\n\n/**\n * A unique constraint whose key may hold nulls, with `NULLS NOT DISTINCT` (Postgres 15+) so two\n * rows null in the same column still collide — the identity of a table whose key has an\n * optional part, where a primary key (NOT NULL throughout) cannot be.\n */\nexport interface UniqueConstraintSpec<K extends string = string> {\n columns: readonly K[];\n nullsNotDistinct: true;\n}\n\nexport interface TableSpec<K extends string = string> {\n /** Physical table name inside the schema. */\n name: string;\n doc: string;\n /** Keyed by the drizzle property name; the column name is its snake_case. */\n columns: Record<K, ColumnSpec>;\n /** Absent for a table whose identity is a `uniqueConstraints` entry (a nullable key part). */\n primaryKey?: readonly K[];\n /** A uuid column whose values must be version 7. */\n uuidV7?: K;\n uniqueIndexes?: readonly (readonly K[])[];\n /** Named `<table>_<columns>_unique`, as drizzle names an unnamed `unique()`. */\n uniqueConstraints?: readonly UniqueConstraintSpec<K>[];\n indexes?: readonly (readonly K[])[];\n /** Foreign keys, to another table's logical key. */\n references?: readonly {\n columns: readonly K[];\n table: string;\n foreignColumns: readonly string[];\n }[];\n}\n\nfunction table<K extends string>(spec: TableSpec<K>): TableSpec<K> {\n return spec;\n}\n\nconst uuid = { type: 'uuid' } as const;\nconst text = { type: 'text' } as const;\nconst jsonb = { type: 'jsonb' } as const;\nconst ts = { type: 'timestamptz' } as const;\nconst integer = { type: 'integer' } as const;\nconst boolean = { type: 'boolean' } as const;\nconst nullable = <C extends ColumnSpec>(column: C, doc?: string): ColumnSpec => ({\n ...column,\n nullable: true,\n ...(doc === undefined ? {} : { doc }),\n});\n\nexport const TABLES = {\n event: table({\n name: 'event',\n doc: \"Every ingested event, the fact base for `performed(...)` conditions. `event_id` is the occurrence's identity as the sender chose it (a retrying producer sends the same one again), scoped to the user: the (user_id, event_id) unique index makes a second delivery a no-op, and one sender's id can never block another user's event.\",\n columns: { id: uuid, eventId: text, userId: text, name: text, ts, payload: jsonb },\n primaryKey: ['id'],\n uuidV7: 'id',\n uniqueIndexes: [['userId', 'eventId']],\n indexes: [['userId', 'name', 'ts']],\n }),\n profile: table({\n name: 'profile',\n doc: 'Identified properties per user (`/ingest` merges into `props`; a null value means unset).',\n columns: {\n userId: text,\n props: jsonb,\n propsAt: nullable(\n jsonb,\n 'When each property was last written, epoch ms by key (a cleared one too): an older patch cannot overwrite it. Null for a row older than this column.'\n ),\n },\n primaryKey: ['userId'],\n }),\n device: table({\n name: 'device',\n doc: 'Push devices, one row per device, holding only who it belongs to now (`JourneyClient.registerDevice`): a signed-in `user_id`, or a `visitor_id` alone before sign-in. Signing out clears both rather than removing the row; a token APNs / FCM reports as gone is removed.',\n columns: {\n deviceId: nullable(\n text,\n 'The device across token rotations: a new token replaces the old one. Null when the producer sent none.'\n ),\n userId: nullable(text),\n visitorId: nullable(\n text,\n \"The visitor on the device now, kept once signed in: it tells one of a user's devices from another.\"\n ),\n token: text,\n platform: text,\n createdAt: ts,\n updatedAt: ts,\n },\n primaryKey: ['token'],\n uniqueIndexes: [['deviceId']],\n indexes: [['userId'], ['visitorId']],\n }),\n visitor: table({\n name: 'visitor',\n doc: \"Visitors the engine has heard from. `user_id` is who they became (`linkVisitor`): a late event of the visitor reaches the user, and the row outlives the user's erasure, so such an event finds the tombstone instead of starting a new visitor. One that never signs in is pruned once idle.\",\n columns: {\n visitorId: text,\n userId: nullable(text),\n createdAt: ts,\n updatedAt: ts,\n },\n primaryKey: ['visitorId'],\n indexes: [['userId'], ['updatedAt']],\n }),\n erasure: table({\n name: 'erasure',\n doc: \"Erasure tombstones (`forgetUser`): every write about a user is conditional on no row here. While `erased_at` is null the user's data stays until every running instance is stopped, and the scheduled sweep retries what is left; once set, the data is gone and the row stays so the user id is never written again.\",\n columns: {\n userId: text,\n requestedAt: ts,\n erasedAt: nullable(ts, 'When the data was erased; null while the erasure is under way.'),\n },\n primaryKey: ['userId'],\n }),\n suppression: table({\n name: 'suppression',\n doc: 'What a user opted out of: a topic on a channel (an email unsubscribe from one topic, a push topic switched off in the app), or the whole channel when `topic` is null — the engine sends nothing there, and `reachable(channel)` is false. One row per (user, channel, topic), nulls included.',\n columns: {\n userId: text,\n channel: text,\n topic: nullable(\n text,\n 'The subscription topic opted out of; null for the whole channel (every row from before topics existed).'\n ),\n ts,\n },\n uniqueConstraints: [{ columns: ['userId', 'channel', 'topic'], nullsNotDistinct: true }],\n }),\n segment: table({\n name: 'segment',\n doc: 'Deployed segment definitions, resolved by name at evaluation time.',\n columns: { id: text, condition: jsonb, hash: text },\n primaryKey: ['id'],\n }),\n trigger: table({\n name: 'trigger',\n doc: 'Event-trigger routes: `where` gates on the event payload, `filter` on the profile.',\n columns: {\n workflow: text,\n hash: text,\n event: text,\n where: nullable(jsonb),\n filter: nullable(jsonb),\n visitors: nullable(\n { type: 'boolean' },\n 'Whether a visitor not signed in may enter (`trigger.event(e.x, { visitors: true })`); signed-in users only otherwise.'\n ),\n version: nullable(\n text,\n 'The code version whose compiled bundle put this route here (null after a forced deploy): an instance it starts runs on that version, so its IR and its code always match.'\n ),\n },\n primaryKey: ['workflow'],\n indexes: [['event']],\n }),\n segmentTrigger: table({\n name: 'segment_trigger',\n doc: 'Segment-entry trigger routes.',\n columns: {\n workflow: text,\n hash: text,\n segment: text,\n version: nullable(\n text,\n 'The code version whose compiled bundle put this route here (null after a forced deploy): an instance it starts runs on that version, so its IR and its code always match.'\n ),\n },\n primaryKey: ['workflow'],\n indexes: [['segment']],\n }),\n segmentMember: table({\n name: 'segment_member',\n doc: 'Who is in each deployed segment and since when: kept by the scheduled sweep, and for trigger-routed segments on every event too.',\n columns: { segment: text, userId: text, ts },\n primaryKey: ['segment', 'userId'],\n }),\n segmentStart: table({\n name: 'segment_start',\n doc: 'Workflows a segment entry still has to start for a member: written with the membership, removed as each one starts, so a failed start is retried by the next evaluation instead of being hidden behind the membership.',\n columns: { segment: text, workflow: text, userId: text, ts },\n primaryKey: ['segment', 'workflow', 'userId'],\n }),\n segmentSnapshot: table({\n name: 'segment_snapshot',\n doc: \"Each segment's size at every sweep, the Studio's sparklines.\",\n columns: { segment: text, takenAt: ts, size: integer },\n primaryKey: ['segment', 'takenAt'],\n }),\n entry: table({\n name: 'entry',\n doc: 'Entry ledger: the (workflow, user) primary key is the once policy.',\n columns: {\n workflow: text,\n userId: text,\n instanceId: text,\n hash: text,\n status: text,\n ts,\n admittedAt: nullable(\n ts,\n 'When the runner admitted itself (`admitInstance`), before its first observable effect; null until then, so an erasure knows nothing of the instance has run yet.'\n ),\n claimedAt: nullable(\n ts,\n \"When this attempt claimed the entry (insert or reclaim), by the host's clock. `ts` is the triggering event's own time, which a producer may set far in the past, so only this tells how long an entry has waited for its instance; maintenance fails an entry left unadmitted with no instance behind it. Null on rows written before the column existed.\"\n ),\n },\n primaryKey: ['workflow', 'userId'],\n // admittedAt: maintenance looks up the few entries still unadmitted (`IS NULL` uses it)\n indexes: [['instanceId'], ['admittedAt']],\n }),\n subscription: table({\n name: 'subscription',\n doc: 'wait_until wake routing; the primary key makes repeated subscribes idempotent.',\n columns: { userId: text, event: text, wakeHandle: text, ts },\n primaryKey: ['wakeHandle', 'event'],\n indexes: [['userId', 'event']],\n }),\n execution: table({\n name: 'execution',\n doc: 'Durable executions whose start is an asynchronous submit (AWS Lambda durable functions): written with the entry, so a lost submit response is retried with the same name, target and payload instead of starting a second execution; and the wake callback the instance is parked on now. Unused on Cloudflare.',\n columns: {\n instanceId: text,\n workflow: text,\n userId: text,\n name: text,\n target: text,\n input: text,\n createdAt: ts,\n submittedAt: nullable(\n ts,\n 'The runtime accepted the start; null while it may still have to be retried.'\n ),\n arn: nullable(text),\n unresolvedAt: nullable(\n ts,\n 'Retries ran out before the runtime confirmed the start: whether it runs is unknown, and nothing retries it.'\n ),\n callbackId: nullable(text, 'The callback the current wait parks on; a wake completes it.'),\n generation: integer,\n deadlineAt: nullable(ts),\n checkedAt: nullable(\n ts,\n \"When maintenance last compared the runtime's status with the ledger.\"\n ),\n stoppedAt: nullable(\n ts,\n 'When it was stopped (an erasure): an invocation already running goes on to its next checkpoint, so the data waits until it has drained.'\n ),\n },\n primaryKey: ['instanceId'],\n indexes: [['workflow', 'userId'], ['submittedAt'], ['userId']],\n }),\n deployment: table({\n name: 'deployment',\n doc: \"The Worker version whose compiled bundle the routes came from, one row (`scope` = 'routes'): journeyWorker applies its own bundle only over an older version, so one still serving during a rollout cannot put its routes back. A forced `POST /bundle/deploy` records the version that served it; a hand-posted `POST /deploy` leaves it as it is.\",\n columns: { scope: text, versionId: text, versionCreatedAt: ts, appliedAt: ts },\n primaryKey: ['scope'],\n }),\n ir: table({\n name: 'ir',\n doc: 'Workflow bodies (WorkflowIR), content-addressed.',\n columns: { contentHash: text, ir: jsonb },\n primaryKey: ['contentHash'],\n }),\n instance: table({\n name: 'instance',\n doc: 'One row per journey instance, written when it enters: the node it sits on or last passed (none when a guard ended it before the first), and how it ended (`running` until then; `goal` is a conversion, at `finished_at`).',\n columns: {\n instanceId: text,\n workflow: text,\n userId: text,\n enteredAt: ts,\n nodeId: nullable(text),\n nodeAt: nullable(ts),\n status: text,\n finishedAt: nullable(ts),\n convertedAt: nullable(\n ts,\n 'When the goal was met, whatever the status: with `exitOnMatch: false` a converted instance ends `completed`.'\n ),\n },\n primaryKey: ['instanceId'],\n indexes: [\n ['workflow', 'status'],\n ['workflow', 'finishedAt'],\n ],\n }),\n message: table({\n name: 'message',\n doc: \"One row per message copy (a push fans out per device). The idempotency key is the engine's copy identity, so a retried step finds the row it wrote; `channel` is where the copy landed (`email`, `push_ios`, `push_android`).\",\n columns: {\n id: uuid,\n idempotencyKey: text,\n workflow: text,\n instanceId: text,\n nodeId: text,\n template: text,\n channel: text,\n userId: text,\n topic: nullable(\n text,\n \"An email or push copy: its template's subscription topic (what an email's unsubscribe link opts out of); null for a transactional message, and for every other channel.\"\n ),\n sentAt: ts,\n deliveredAt: nullable(ts, 'The transport accepted it.'),\n deviceDeliveredAt: nullable(\n ts,\n \"A push: the device reported it received (iOS's notification service extension, a browser's service worker).\"\n ),\n undeliveredReason: nullable(\n text,\n 'The transport settled it without delivering (a dead push token).'\n ),\n openedAt: nullable(ts, 'First open of any kind, by a person or a machine.'),\n humanOpenedAt: nullable(ts, 'First open a person made.'),\n clickedAt: nullable(ts),\n humanClickedAt: nullable(ts),\n unsubscribedAt: nullable(ts),\n },\n primaryKey: ['id'],\n uuidV7: 'id',\n uniqueIndexes: [['idempotencyKey']],\n indexes: [['workflow', 'sentAt'], ['instanceId']],\n }),\n messageLink: table({\n name: 'message_link',\n doc: \"A sent email's links in document order: the tracked URL names a message and a position, and the redirect goes only to the URL recorded here.\",\n columns: { messageId: uuid, position: integer, url: text },\n primaryKey: ['messageId', 'position'],\n references: [{ columns: ['messageId'], table: 'message', foreignColumns: ['id'] }],\n }),\n messageOpen: table({\n name: 'message_open',\n doc: \"Every open-pixel load or push tap, classified when recorded: `machine` when no person caused it, with the deciding rule in `reason`; the request's network (never its address) kept for revisiting the rules.\",\n columns: {\n id: uuid,\n messageId: uuid,\n openedAt: ts,\n machine: boolean,\n reason: nullable(text),\n userAgent: nullable(text),\n asn: nullable(integer),\n asOrganization: nullable(text),\n country: nullable(text),\n },\n primaryKey: ['id'],\n uuidV7: 'id',\n indexes: [['messageId']],\n references: [{ columns: ['messageId'], table: 'message', foreignColumns: ['id'] }],\n }),\n messageClick: table({\n name: 'message_click',\n doc: 'Every click on a tracked link, classified like opens.',\n columns: {\n id: uuid,\n messageId: uuid,\n position: integer,\n url: text,\n clickedAt: ts,\n machine: boolean,\n reason: nullable(text),\n userAgent: nullable(text),\n asn: nullable(integer),\n asOrganization: nullable(text),\n country: nullable(text),\n },\n primaryKey: ['id'],\n uuidV7: 'id',\n indexes: [['messageId']],\n references: [{ columns: ['messageId'], table: 'message', foreignColumns: ['id'] }],\n }),\n} satisfies Record<string, TableSpec>;\n\nexport type TableKey = keyof typeof TABLES;\n\n/** The engine's schema when the config names none. */\nexport const DEFAULT_SCHEMA = 'workflow';\n\n/** `eventId` → `event_id`. */\nexport function columnName(key: string): string {\n return key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);\n}\n\nconst quote = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\n\n/** `<table>_<columns>_unique`: drizzle's name for an unnamed `unique()`, and the index behind it. */\nexport function uniqueConstraintName(spec: TableSpec, unique: UniqueConstraintSpec): string {\n return `${spec.name}_${unique.columns.map(columnName).join('_')}_unique`;\n}\n\n/** `<table>_<columns>_index`: the name drizzle-kit and `renderPostgresDdl` both give an unnamed index. */\nexport function indexName(spec: TableSpec, keys: readonly string[]): string {\n return `${spec.name}_${keys.map(columnName).join('_')}_index`;\n}\n\nconst SQL_TYPES: Record<ColumnType, string> = {\n uuid: 'uuid',\n text: 'text',\n jsonb: 'jsonb',\n timestamptz: 'timestamptz',\n integer: 'integer',\n boolean: 'boolean',\n};\n\n/**\n * Plain Postgres DDL for every table — for a host without a migration tool, and the tests. A\n * host that migrates with drizzle generates `renderDrizzleSchema` instead and lets drizzle-kit\n * write the migration.\n */\nexport function renderPostgresDdl(schema = DEFAULT_SCHEMA): string {\n const s = quote(schema);\n const out = [`CREATE SCHEMA IF NOT EXISTS ${s};`];\n for (const spec of Object.values(TABLES)) {\n const lines = Object.entries(spec.columns).map(\n ([key, column]) =>\n ` ${quote(columnName(key))} ${SQL_TYPES[column.type]}${column.nullable ? '' : ' NOT NULL'}`\n );\n if (spec.primaryKey !== undefined) {\n lines.push(` PRIMARY KEY (${spec.primaryKey.map((k) => quote(columnName(k))).join(', ')})`);\n }\n for (const unique of spec.uniqueConstraints ?? []) {\n const cols = unique.columns.map(columnName);\n lines.push(\n ` CONSTRAINT ${quote(uniqueConstraintName(spec, unique))} UNIQUE NULLS NOT DISTINCT (${cols.map(quote).join(', ')})`\n );\n }\n if (spec.uuidV7 !== undefined) {\n lines.push(\n ` CONSTRAINT ${quote(`${spec.name}_uuid_v7`)} CHECK (substring(${quote(columnName(spec.uuidV7))}::text, 15, 1) = '7')`\n );\n }\n for (const ref of spec.references ?? []) {\n const target = TABLES[ref.table as TableKey];\n lines.push(\n ` FOREIGN KEY (${ref.columns.map((k) => quote(columnName(k))).join(', ')}) REFERENCES ${s}.${quote(target.name)} (${ref.foreignColumns.map((k) => quote(columnName(k))).join(', ')})`\n );\n }\n out.push(`CREATE TABLE IF NOT EXISTS ${s}.${quote(spec.name)} (\\n${lines.join(',\\n')}\\n);`);\n const index = (unique: boolean) => (keys: readonly string[]) => {\n const cols = keys.map(columnName);\n out.push(\n `CREATE ${unique ? 'UNIQUE ' : ''}INDEX IF NOT EXISTS ${quote(indexName(spec, keys))} ON ${s}.${quote(spec.name)} (${cols.map(quote).join(', ')});`\n );\n };\n (spec.uniqueIndexes ?? []).forEach(index(true));\n (spec.indexes ?? []).forEach(index(false));\n }\n return `${out.join('\\n')}\\n`;\n}\n\nconst TIMESTAMP_OPTIONS = \"{ mode: 'string', withTimezone: true }\";\n\nconst DRIZZLE_TYPES: Record<ColumnType, (column: string) => string> = {\n uuid: (c) => `uuid('${c}')`,\n text: (c) => `text('${c}')`,\n jsonb: (c) => `jsonb('${c}')`,\n timestamptz: (c) => `timestamp('${c}', ${TIMESTAMP_OPTIONS})`,\n integer: (c) => `integer('${c}')`,\n boolean: (c) => `boolean('${c}')`,\n};\n\n/** The line width the generated file is laid out for: the formatters' common default. */\nconst PRINT_WIDTH = 100;\n\n/**\n * One `workflowSchema.table(...)` statement, laid out the way a prettier-compatible formatter\n * (prettier, oxfmt, biome) at `PRINT_WIDTH` lays it out, so that formatting the generated file\n * changes nothing and a regeneration shows only real changes: on one line when it fits; else\n * with the last argument \"hugged\" (the columns object, or the constraints arrow when the columns\n * fit on the first line) and its items one per line; else every argument on its own line, the\n * constraints array still collapsed when it fits. A column with a doc comment keeps the columns\n * object expanded, as a comment does for a formatter.\n */\n/** A column line past the width: a formatter breaks the timestamp options object, so this does too. */\nfunction wrapColumn(text: string, indent: string): string {\n if (`${indent}${text},`.length <= PRINT_WIDTH || !text.includes(TIMESTAMP_OPTIONS)) return text;\n return text.replace(\n TIMESTAMP_OPTIONS,\n `{\\n${indent} mode: 'string',\\n${indent} withTimezone: true,\\n${indent}}`\n );\n}\n\nfunction renderTable(\n name: string,\n table: string,\n columns: { doc: string | undefined; text: string }[],\n extras: string[]\n): string {\n const head = `export const ${name} = workflowSchema.table(`;\n const flatColumns = columns.some((c) => c.doc !== undefined)\n ? undefined\n : `{ ${columns.map((c) => c.text).join(', ')} }`;\n const expandedColumns = (indent: string) =>\n `{\\n${columns\n .map(\n (c) =>\n `${c.doc === undefined ? '' : `${indent} /** ${c.doc} */\\n`}${indent} ${wrapColumn(c.text, `${indent} `)},`\n )\n .join('\\n')}\\n${indent}}`;\n const flatExtras = `(table) => [${extras.join(', ')}]`;\n const expandedExtras = (indent: string) =>\n `(table) => [\\n${extras.map((e) => `${indent} ${e},`).join('\\n')}\\n${indent}]`;\n const fits = (line: string) => line.length <= PRINT_WIDTH;\n\n if (flatColumns !== undefined) {\n const oneLine = `${head}'${table}', ${flatColumns}${extras.length === 0 ? '' : `, ${flatExtras}`});`;\n if (fits(oneLine)) return oneLine;\n }\n if (extras.length === 0) return `${head}'${table}', ${expandedColumns('')});`;\n if (flatColumns !== undefined) {\n const first = `${head}'${table}', ${flatColumns}, (table) => [`;\n if (fits(first)) return `${first}\\n${extras.map((e) => ` ${e},`).join('\\n')}\\n]);`;\n }\n const third = fits(` ${flatExtras}`) ? flatExtras : expandedExtras(' ');\n return `${head}\\n '${table}',\\n ${expandedColumns(' ')},\\n ${third}\\n);`;\n}\n\nconst exportName = (key: string) => `workflow${key.charAt(0).toUpperCase()}${key.slice(1)}`;\n\n/**\n * The tables as one drizzle file: `export const workflowSchema = pgSchema(<schema>)` and every\n * table as `workflowSchema.table(...)`. The host re-exports it from its drizzle schema and\n * generates the migration with drizzle-kit, so the migration history stays the host's. The\n * output is deterministic — regenerate and diff it in CI to catch an SDK upgrade that changed the\n * tables.\n */\nexport function renderDrizzleSchema(schema = DEFAULT_SCHEMA): string {\n const specs = Object.entries(TABLES) as [TableKey, TableSpec][];\n const used = new Set<string>(['pgSchema']);\n const body: string[] = [];\n let needsSql = false;\n for (const [key, spec] of specs) {\n const columns = Object.entries(spec.columns).map(([prop, column]) => {\n used.add(column.type === 'timestamptz' ? 'timestamp' : column.type);\n const key =\n spec.primaryKey?.length === 1 && spec.primaryKey[0] === prop ? '.primaryKey()' : '';\n return {\n doc: column.doc,\n text: `${prop}: ${DRIZZLE_TYPES[column.type](columnName(prop))}${key}${column.nullable ? '' : '.notNull()'}`,\n };\n });\n const extras: string[] = [];\n if (spec.primaryKey !== undefined && spec.primaryKey.length > 1) {\n used.add('primaryKey');\n extras.push(\n `primaryKey({ columns: [${spec.primaryKey.map((k) => `table.${k}`).join(', ')}] })`\n );\n }\n for (const keys of spec.uniqueIndexes ?? []) {\n used.add('uniqueIndex');\n extras.push(`uniqueIndex().on(${keys.map((k) => `table.${k}`).join(', ')})`);\n }\n for (const unique of spec.uniqueConstraints ?? []) {\n used.add('unique');\n extras.push(\n `unique().on(${unique.columns.map((k) => `table.${k}`).join(', ')}).nullsNotDistinct()`\n );\n }\n for (const keys of spec.indexes ?? []) {\n used.add('index');\n extras.push(`index().on(${keys.map((k) => `table.${k}`).join(', ')})`);\n }\n for (const ref of spec.references ?? []) {\n used.add('foreignKey');\n extras.push(\n `foreignKey({ columns: [${ref.columns.map((k) => `table.${k}`).join(', ')}], foreignColumns: [${ref.foreignColumns.map((k) => `${exportName(ref.table)}.${k}`).join(', ')}] })`\n );\n }\n if (spec.uuidV7 !== undefined) {\n used.add('check');\n needsSql = true;\n extras.push(\n `check('${spec.name}_uuid_v7', sql\\`substring(\\${table.${spec.uuidV7}}::text, 15, 1) = '7'\\`)`\n );\n }\n body.push(`/** ${spec.doc} */\\n${renderTable(exportName(key), spec.name, columns, extras)}`);\n }\n const imports = [...used].sort();\n return [\n '// Generated by `workflow-ui generate` from @shware/workflow — do not edit; regenerate after',\n '// upgrading the SDK and let drizzle-kit write the migration.',\n ...(needsSql ? [\"import { sql } from 'drizzle-orm';\"] : []),\n `import {\\n${imports.map((name) => ` ${name},`).join('\\n')}\\n} from 'drizzle-orm/pg-core';`,\n '',\n `export const workflowSchema = pgSchema('${schema}');`,\n '',\n body.join('\\n\\n'),\n '',\n ].join('\\n');\n}\n"],"mappings":";AAuDA,SAAS,MAAwB,MAAkC;CACjE,OAAO;AACT;AAEA,MAAM,OAAO,EAAE,MAAM,OAAO;AAC5B,MAAM,OAAO,EAAE,MAAM,OAAO;AAC5B,MAAM,QAAQ,EAAE,MAAM,QAAQ;AAC9B,MAAM,KAAK,EAAE,MAAM,cAAc;AACjC,MAAM,UAAU,EAAE,MAAM,UAAU;AAClC,MAAM,UAAU,EAAE,MAAM,UAAU;AAClC,MAAM,YAAkC,QAAW,SAA8B;CAC/E,GAAG;CACH,UAAU;CACV,GAAI,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,IAAI;AACrC;AAEA,MAAa,SAAS;CACpB,OAAO,MAAM;EACX,MAAM;EACN,KAAK;EACL,SAAS;GAAE,IAAI;GAAM,SAAS;GAAM,QAAQ;GAAM,MAAM;GA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AAK,qCAAqC,KAAK,OAAO,yBACvE;EACF;EACA,KAAK,KAAK,OAAO,KAAK,IAAI,OAAO,YAAY,WAAW,GAAG,GAAG,KAAK,MAAM,SAAS,MAAM,GAAG;CAC7F;CACA,MAAM,UAAU,CAAC,GAAG,IAAI,CAAC,CAAC,KAAK;CAC/B,OAAO;EACL;EACA;EACA,GAAI,WAAW,CAAC,oCAAoC,IAAI,CAAC;EACzD,aAAa,QAAQ,KAAK,SAAS,KAAK,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE;EAC5D;EACA,2CAA2C,OAAO;EAClD;EACA,KAAK,KAAK,MAAM;EAChB;CACF,CAAC,CAAC,KAAK,IAAI;AACb"}
|
package/dist/webpush.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpush.cjs","names":["base64url","Buffer","PermanentError","isRetryableStatus"],"sources":["../src/webpush.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport type { MessageSender, OutboundMessage, SendResult } from './engine';\nimport { PermanentError, isRetryableStatus } from './engine/retry';\nimport { base64url } from './jwt';\nimport type { PushRenderer } from './push';\n\n/**\n * `@shware/workflow/webpush` — browser push through the standard Web Push protocol: VAPID\n * (RFC 8292) identifies the sender, the payload is encrypted for the subscription (RFC 8291,\n * `aes128gcm`, RFC 8188). One sender reaches Chrome, Edge, Firefox and Safari 16+ — each\n * browser's push service accepts the same request, over HTTP/1.1 — with nothing but WebCrypto.\n *\n * The recipient is a browser's `PushSubscription` as JSON (`JSON.stringify(subscription)`),\n * registered like an app token (`registerDevice(userId, { token, platform: 'web' })`). The\n * service worker receives `{ title, body, image?, url?, template, …tracking data }` as the push\n * event's JSON.\n */\n\n/** A VAPID key pair: the uncompressed P-256 public key and the private scalar, base64url. */\nexport interface VapidKeys {\n publicKey: string;\n privateKey: string;\n}\n\nexport interface VapidSignerOptions extends VapidKeys {\n /** Who to contact about this sender: `mailto:` or an `https:` URL (RFC 8292). */\n subject: string;\n}\n\nexport interface WebPushOptions {\n /** The VAPID signer the requests are authorized with — shared by every sender on the same key pair. */\n credentials: VapidSigner;\n render: PushRenderer;\n /** Seconds the push service keeps an undelivered message; a day by default. */\n ttl?: number;\n /** Fetch implementation (defaults to the global one). */\n fetch?: typeof fetch;\n}\n\n/**\n * How a push service's answer is classified (RFC 8030 §7 and §8.1, with the browsers' services\n * answering as documented there):\n *\n * - dead subscription: 404 and 410 — the browser unsubscribed or the subscription expired\n * (RFC 8030 §7.3: 410 Gone for an expired subscription) — and a subscription the sender\n * cannot parse (`InvalidSubscription`). The copy settles undelivered and the host forgets it.\n * - transient: 429 Too Many Requests (§8.4) and 5xx.\n * - everything else is this request or this sender: 400 (a bad header or body), 401 / 403 (the\n * VAPID key pair or subject, §8.2 of RFC 8292), 413 (the payload, RFC 8030 §7.2) and any other\n * 4xx are a `PermanentError`.\n */\nexport const DEAD_TOKEN_REASONS: ReadonlySet<string> = new Set([\n 'Gone',\n 'NotFound',\n 'InvalidSubscription',\n]);\n\ninterface Subscription {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n}\n\n/** A fresh VAPID key pair (once per project; the private key is a secret). */\nexport async function generateVapidKeys(): Promise<VapidKeys> {\n const pair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]);\n const raw = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey));\n const jwk = await crypto.subtle.exportKey('jwk', pair.privateKey);\n return { publicKey: base64url(raw), privateKey: jwk.d ?? '' };\n}\n\n/** The record size the header announces: RFC 8291 §4 fixes it at 4096 and one record per push. */\nconst RECORD_SIZE = 4096;\n/**\n * The largest plaintext one record carries. A push message body is at most 4096 octets (RFC 8030\n * §7.2); the aes128gcm header takes 86 of them (16 salt + 4 rs + 1 idlen + 65 key), the record its\n * 16-octet tag and the 1-octet delimiter — 3993 octets of plaintext (RFC 8291 §4). Anything past\n * that is either an invalid record or a 413 from the push service.\n */\nexport const MAX_PLAINTEXT_BYTES = 3993;\n/** Bytes WebCrypto accepts (backed by a plain ArrayBuffer). */\ntype Bytes = Uint8Array<ArrayBuffer>;\nconst encoder = new TextEncoder();\nconst utf8 = (text: string): Bytes => encoder.encode(text);\n\nexport function fromBase64url(text: string): Bytes {\n return new Uint8Array(Buffer.from(text, 'base64url'));\n}\n\nconst concat = (...parts: Uint8Array[]): Bytes => new Uint8Array(Buffer.concat(parts));\n\n/** HKDF-SHA256 (RFC 5869), as WebCrypto provides it. */\nasync function hkdf(salt: Bytes, ikm: Bytes, info: Bytes, length: number): Promise<Bytes> {\n const key = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);\n return new Uint8Array(\n await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, key, length * 8)\n );\n}\n\n/**\n * The `aes128gcm` body for one subscription (RFC 8291 §3.4): salt, record size, the sender's\n * ephemeral public key, then the payload sealed under a key both sides derive from ECDH and the\n * subscription's auth secret.\n */\nexport async function encryptPayload(\n payload: Bytes,\n p256dh: Bytes,\n authSecret: Bytes,\n salt: Bytes = crypto.getRandomValues(new Uint8Array(16))\n): Promise<Bytes> {\n const ephemeral = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [\n 'deriveBits',\n ]);\n const senderPublic = new Uint8Array(await crypto.subtle.exportKey('raw', ephemeral.publicKey));\n const receiver = await crypto.subtle.importKey(\n 'raw',\n p256dh,\n { name: 'ECDH', namedCurve: 'P-256' },\n false,\n []\n );\n const shared = new Uint8Array(\n await crypto.subtle.deriveBits({ name: 'ECDH', public: receiver }, ephemeral.privateKey, 256)\n );\n const ikm = await hkdf(\n authSecret,\n shared,\n concat(utf8('WebPush: info\\0'), p256dh, senderPublic),\n 32\n );\n const cek = await hkdf(salt, ikm, utf8('Content-Encoding: aes128gcm\\0'), 16);\n const nonce = await hkdf(salt, ikm, utf8('Content-Encoding: nonce\\0'), 12);\n const key = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);\n // The single, last record: the payload and the 0x02 delimiter, no padding\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: nonce },\n key,\n concat(payload, new Uint8Array([2]))\n )\n );\n const header = new Uint8Array(16 + 4 + 1);\n header.set(salt, 0);\n new DataView(header.buffer).setUint32(16, RECORD_SIZE);\n header[20] = senderPublic.length;\n return concat(header, senderPublic, sealed);\n}\n\n/** How long a VAPID token is good for: RFC 8292 §2 allows at most 24 hours. */\nconst VAPID_EXP_S = 24 * 3600;\n/** How long a signed token is reused: half its life, so it is never sent near expiry. */\nconst VAPID_TTL_MS = 12 * 3600_000;\n\n/**\n * The VAPID `Authorization` header (RFC 8292 §3) for one key pair. The private key is imported\n * once; the JWT is signed per push service (its `aud` is the service's origin) and reused for\n * `VAPID_TTL_MS`. Concurrent callers for one origin share the one signing in flight, and a signing\n * that failed is not kept. One instance serves every sender built on the pair — a host keeps it\n * across runs, and builds the senders per run.\n */\nexport class VapidSigner {\n private key: Promise<CryptoKey> | undefined;\n private readonly signed = new Map<string, { value: string; issuedAt: number }>();\n private readonly signing = new Map<string, Promise<string>>();\n\n constructor(private readonly options: VapidSignerOptions) {}\n\n /** The header value for the push service at `audience` — its origin, or any URL on it. */\n async authorization(audience: string, now = Date.now()): Promise<string> {\n const origin = new URL(audience).origin;\n const current = this.signed.get(origin);\n if (current !== undefined && now - current.issuedAt < VAPID_TTL_MS) return current.value;\n let pending = this.signing.get(origin);\n if (pending === undefined) {\n pending = this.sign(origin, now)\n .then((value) => {\n this.signed.set(origin, { value, issuedAt: now });\n return value;\n })\n .finally(() => {\n this.signing.delete(origin);\n });\n this.signing.set(origin, pending);\n }\n return pending;\n }\n\n private privateKey(): Promise<CryptoKey> {\n if (this.key === undefined) {\n const publicKey = fromBase64url(this.options.publicKey);\n this.key = crypto.subtle\n .importKey(\n 'jwk',\n {\n kty: 'EC',\n crv: 'P-256',\n d: this.options.privateKey,\n x: base64url(publicKey.slice(1, 33)),\n y: base64url(publicKey.slice(33, 65)),\n ext: true,\n },\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign']\n )\n .catch((error: unknown) => {\n this.key = undefined;\n throw error;\n });\n }\n return this.key;\n }\n\n private async sign(origin: string, now: number): Promise<string> {\n const key = await this.privateKey();\n const header = base64url(JSON.stringify({ typ: 'JWT', alg: 'ES256' }));\n const claims = base64url(\n JSON.stringify({\n aud: origin,\n exp: Math.floor(now / 1000) + VAPID_EXP_S,\n sub: this.options.subject,\n })\n );\n const signature = new Uint8Array(\n await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, utf8(`${header}.${claims}`))\n );\n return `vapid t=${header}.${claims}.${base64url(signature)}, k=${this.options.publicKey}`;\n }\n}\n\n/**\n * A browser subscription as a sender can use it: an https endpoint, a 65-byte uncompressed P-256\n * key and a 16-byte auth secret. Anything else — not JSON, missing keys, a key of the wrong size,\n * an endpoint that is not https — is undefined.\n */\nfunction parseSubscription(\n token: string\n): { endpoint: string; p256dh: Bytes; auth: Bytes } | undefined {\n try {\n const value = JSON.parse(token) as Partial<Subscription>;\n if (typeof value.endpoint !== 'string' || new URL(value.endpoint).protocol !== 'https:') {\n return undefined;\n }\n const p256dh = fromBase64url(value.keys?.p256dh ?? '');\n const auth = fromBase64url(value.keys?.auth ?? '');\n if (p256dh.length !== 65 || p256dh[0] !== 4 || auth.length !== 16) return undefined;\n return { endpoint: value.endpoint, p256dh, auth };\n } catch {\n return undefined;\n }\n}\n\nexport class WebPushSender implements MessageSender {\n constructor(private readonly options: WebPushOptions) {}\n\n async send(message: OutboundMessage): Promise<void | SendResult> {\n if (message.channel !== 'push') {\n throw new Error(`WebPushSender: unsupported channel '${message.channel}'`);\n }\n if (message.recipient === undefined) {\n throw new Error(`WebPushSender: no subscription for user '${message.userId}'`);\n }\n const subscription = parseSubscription(message.recipient);\n if (subscription === undefined) {\n // Not a usable subscription: nothing will ever deliver to it, so do not retry into it\n return { delivered: false, reason: 'InvalidSubscription' };\n }\n const content = await this.options.render(message.template, message.props);\n const payload = utf8(\n JSON.stringify({\n ...content,\n template: message.template,\n idempotencyKey: message.idempotencyKey,\n ...message.tracking?.data,\n })\n );\n if (payload.length > MAX_PLAINTEXT_BYTES) {\n // The same template renders the same size on every attempt: settle it before encrypting\n throw new PermanentError(\n `[webpush] payload for template '${message.template}' is ${payload.length} bytes; a push message carries at most ${MAX_PLAINTEXT_BYTES}`\n );\n }\n const body = await encryptPayload(payload, subscription.p256dh, subscription.auth);\n const doFetch = this.options.fetch ?? fetch;\n const response = await doFetch(subscription.endpoint, {\n method: 'POST',\n headers: {\n authorization: await this.options.credentials.authorization(subscription.endpoint),\n 'content-encoding': 'aes128gcm',\n 'content-type': 'application/octet-stream',\n ttl: String(this.options.ttl ?? 86_400),\n urgency: 'normal',\n // A resend of the same copy replaces the first one while it is still queued (RFC 8030\n // §5.4), so an at-least-once retry does not show the notification twice\n topic: await webPushTopic(message.idempotencyKey),\n },\n body,\n });\n if (response.ok) return;\n const { status } = response;\n if (status === 404 || status === 410) {\n // The browser unsubscribed or the subscription expired: it will never deliver again\n console.warn(`[webpush] subscription gone for user ${message.userId}: ${status}`);\n return { delivered: false, reason: status === 410 ? 'Gone' : 'NotFound' };\n }\n const text = await response.text();\n if (isRetryableStatus(status)) throw new Error(`[webpush] ${status}: ${text}`);\n throw new PermanentError(`[webpush] push service refused the request: ${status} ${text}`);\n }\n}\n\n/**\n * The `Topic` header for one copy: RFC 8030 §5.4 allows at most 32 characters of the URL-safe\n * base64 alphabet, so the idempotency key goes through SHA-256 and is cut to size.\n */\nexport async function webPushTopic(idempotencyKey: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', utf8(idempotencyKey));\n return base64url(new Uint8Array(digest)).slice(0, 32);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmDA,MAAa,qCAA0C,IAAI,IAAI;CAC7D;CACA;CACA;AACF,CAAC;;AAQD,eAAsB,oBAAwC;CAC5D,MAAM,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AAI;EAEjF,MAAM,WAAW,OADD,KAAK,QAAQ,SAAS,MAAA,CACP,aAAa,UAAU;GACpD,QAAQ;GACR,SAAS;IACP,eAAe,MAAM,KAAK,QAAQ,YAAY,cAAc,aAAa,QAAQ;IACjF,oBAAoB;IACpB,gBAAgB;IAChB,KAAK,OAAO,KAAK,QAAQ,OAAO,KAAM;IACtC,SAAS;IAGT,OAAO,MAAM,aAAa,QAAQ,cAAc;GAClD;GACA;EACF,CAAC;EACD,IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,IAAI,WAAW,OAAO,WAAW,KAAK;GAEpC,QAAQ,KAAK,wCAAwC,QAAQ,OAAO,IAAI,QAAQ;GAChF,OAAO;IAAE,WAAW;IAAO,QAAQ,WAAW,MAAM,SAAS;GAAW;EAC1E;EACA,MAAM,OAAO,MAAM,SAAS,KAAK;EACjC,IAAIC,qBAAAA,kBAAkB,MAAM,GAAG,MAAM,IAAI,MAAM,aAAa,OAAO,IAAI,MAAM;EAC7E,MAAM,IAAID,qBAAAA,eAAe,+CAA+C,OAAO,GAAG,MAAM;CAC1F;AACF;;;;;AAMA,eAAsB,aAAa,gBAAyC;CAC1E,MAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,cAAc,CAAC;CACzE,OAAOF,YAAAA,UAAU,IAAI,WAAW,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,EAAE;AACtD"}
|
|
1
|
+
{"version":3,"file":"webpush.cjs","names":["base64url","Buffer","PermanentError","isRetryableStatus"],"sources":["../src/webpush.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport type { MessageSender, OutboundMessage, SendResult } from './engine';\nimport { PermanentError, isRetryableStatus } from './engine/retry';\nimport { base64url } from './jwt';\nimport type { PushRenderer } from './push';\n\n/**\n * `@shware/workflow/webpush` — browser push through the standard Web Push protocol: VAPID\n * (RFC 8292) identifies the sender, the payload is encrypted for the subscription (RFC 8291,\n * `aes128gcm`, RFC 8188). One sender reaches Chrome, Edge, Firefox and Safari 16+ — each\n * browser's push service accepts the same request, over HTTP/1.1 — with nothing but WebCrypto.\n *\n * The recipient is a browser's `PushSubscription` as JSON (`JSON.stringify(subscription)`),\n * registered like an app token (`registerDevice({ userId, token, platform: 'web' })`). The\n * service worker receives `{ title, body, image?, url?, template, …tracking data }` as the push\n * event's JSON.\n */\n\n/** A VAPID key pair: the uncompressed P-256 public key and the private scalar, base64url. */\nexport interface VapidKeys {\n publicKey: string;\n privateKey: string;\n}\n\nexport interface VapidSignerOptions extends VapidKeys {\n /** Who to contact about this sender: `mailto:` or an `https:` URL (RFC 8292). */\n subject: string;\n}\n\nexport interface WebPushOptions {\n /** The VAPID signer the requests are authorized with — shared by every sender on the same key pair. */\n credentials: VapidSigner;\n render: PushRenderer;\n /** Seconds the push service keeps an undelivered message; a day by default. */\n ttl?: number;\n /** Fetch implementation (defaults to the global one). */\n fetch?: typeof fetch;\n}\n\n/**\n * How a push service's answer is classified (RFC 8030 §7 and §8.1, with the browsers' services\n * answering as documented there):\n *\n * - dead subscription: 404 and 410 — the browser unsubscribed or the subscription expired\n * (RFC 8030 §7.3: 410 Gone for an expired subscription) — and a subscription the sender\n * cannot parse (`InvalidSubscription`). The copy settles undelivered and the host forgets it.\n * - transient: 429 Too Many Requests (§8.4) and 5xx.\n * - everything else is this request or this sender: 400 (a bad header or body), 401 / 403 (the\n * VAPID key pair or subject, §8.2 of RFC 8292), 413 (the payload, RFC 8030 §7.2) and any other\n * 4xx are a `PermanentError`.\n */\nexport const DEAD_TOKEN_REASONS: ReadonlySet<string> = new Set([\n 'Gone',\n 'NotFound',\n 'InvalidSubscription',\n]);\n\ninterface Subscription {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n}\n\n/** A fresh VAPID key pair (once per project; the private key is a secret). */\nexport async function generateVapidKeys(): Promise<VapidKeys> {\n const pair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]);\n const raw = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey));\n const jwk = await crypto.subtle.exportKey('jwk', pair.privateKey);\n return { publicKey: base64url(raw), privateKey: jwk.d ?? '' };\n}\n\n/** The record size the header announces: RFC 8291 §4 fixes it at 4096 and one record per push. */\nconst RECORD_SIZE = 4096;\n/**\n * The largest plaintext one record carries. A push message body is at most 4096 octets (RFC 8030\n * §7.2); the aes128gcm header takes 86 of them (16 salt + 4 rs + 1 idlen + 65 key), the record its\n * 16-octet tag and the 1-octet delimiter — 3993 octets of plaintext (RFC 8291 §4). Anything past\n * that is either an invalid record or a 413 from the push service.\n */\nexport const MAX_PLAINTEXT_BYTES = 3993;\n/** Bytes WebCrypto accepts (backed by a plain ArrayBuffer). */\ntype Bytes = Uint8Array<ArrayBuffer>;\nconst encoder = new TextEncoder();\nconst utf8 = (text: string): Bytes => encoder.encode(text);\n\nexport function fromBase64url(text: string): Bytes {\n return new Uint8Array(Buffer.from(text, 'base64url'));\n}\n\nconst concat = (...parts: Uint8Array[]): Bytes => new Uint8Array(Buffer.concat(parts));\n\n/** HKDF-SHA256 (RFC 5869), as WebCrypto provides it. */\nasync function hkdf(salt: Bytes, ikm: Bytes, info: Bytes, length: number): Promise<Bytes> {\n const key = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);\n return new Uint8Array(\n await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, key, length * 8)\n );\n}\n\n/**\n * The `aes128gcm` body for one subscription (RFC 8291 §3.4): salt, record size, the sender's\n * ephemeral public key, then the payload sealed under a key both sides derive from ECDH and the\n * subscription's auth secret.\n */\nexport async function encryptPayload(\n payload: Bytes,\n p256dh: Bytes,\n authSecret: Bytes,\n salt: Bytes = crypto.getRandomValues(new Uint8Array(16))\n): Promise<Bytes> {\n const ephemeral = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [\n 'deriveBits',\n ]);\n const senderPublic = new Uint8Array(await crypto.subtle.exportKey('raw', ephemeral.publicKey));\n const receiver = await crypto.subtle.importKey(\n 'raw',\n p256dh,\n { name: 'ECDH', namedCurve: 'P-256' },\n false,\n []\n );\n const shared = new Uint8Array(\n await crypto.subtle.deriveBits({ name: 'ECDH', public: receiver }, ephemeral.privateKey, 256)\n );\n const ikm = await hkdf(\n authSecret,\n shared,\n concat(utf8('WebPush: info\\0'), p256dh, senderPublic),\n 32\n );\n const cek = await hkdf(salt, ikm, utf8('Content-Encoding: aes128gcm\\0'), 16);\n const nonce = await hkdf(salt, ikm, utf8('Content-Encoding: nonce\\0'), 12);\n const key = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);\n // The single, last record: the payload and the 0x02 delimiter, no padding\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: nonce },\n key,\n concat(payload, new Uint8Array([2]))\n )\n );\n const header = new Uint8Array(16 + 4 + 1);\n header.set(salt, 0);\n new DataView(header.buffer).setUint32(16, RECORD_SIZE);\n header[20] = senderPublic.length;\n return concat(header, senderPublic, sealed);\n}\n\n/** How long a VAPID token is good for: RFC 8292 §2 allows at most 24 hours. */\nconst VAPID_EXP_S = 24 * 3600;\n/** How long a signed token is reused: half its life, so it is never sent near expiry. */\nconst VAPID_TTL_MS = 12 * 3600_000;\n\n/**\n * The VAPID `Authorization` header (RFC 8292 §3) for one key pair. The private key is imported\n * once; the JWT is signed per push service (its `aud` is the service's origin) and reused for\n * `VAPID_TTL_MS`. Concurrent callers for one origin share the one signing in flight, and a signing\n * that failed is not kept. One instance serves every sender built on the pair — a host keeps it\n * across runs, and builds the senders per run.\n */\nexport class VapidSigner {\n private key: Promise<CryptoKey> | undefined;\n private readonly signed = new Map<string, { value: string; issuedAt: number }>();\n private readonly signing = new Map<string, Promise<string>>();\n\n constructor(private readonly options: VapidSignerOptions) {}\n\n /** The header value for the push service at `audience` — its origin, or any URL on it. */\n async authorization(audience: string, now = Date.now()): Promise<string> {\n const origin = new URL(audience).origin;\n const current = this.signed.get(origin);\n if (current !== undefined && now - current.issuedAt < VAPID_TTL_MS) return current.value;\n let pending = this.signing.get(origin);\n if (pending === undefined) {\n pending = this.sign(origin, now)\n .then((value) => {\n this.signed.set(origin, { value, issuedAt: now });\n return value;\n })\n .finally(() => {\n this.signing.delete(origin);\n });\n this.signing.set(origin, pending);\n }\n return pending;\n }\n\n private privateKey(): Promise<CryptoKey> {\n if (this.key === undefined) {\n const publicKey = fromBase64url(this.options.publicKey);\n this.key = crypto.subtle\n .importKey(\n 'jwk',\n {\n kty: 'EC',\n crv: 'P-256',\n d: this.options.privateKey,\n x: base64url(publicKey.slice(1, 33)),\n y: base64url(publicKey.slice(33, 65)),\n ext: true,\n },\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign']\n )\n .catch((error: unknown) => {\n this.key = undefined;\n throw error;\n });\n }\n return this.key;\n }\n\n private async sign(origin: string, now: number): Promise<string> {\n const key = await this.privateKey();\n const header = base64url(JSON.stringify({ typ: 'JWT', alg: 'ES256' }));\n const claims = base64url(\n JSON.stringify({\n aud: origin,\n exp: Math.floor(now / 1000) + VAPID_EXP_S,\n sub: this.options.subject,\n })\n );\n const signature = new Uint8Array(\n await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, utf8(`${header}.${claims}`))\n );\n return `vapid t=${header}.${claims}.${base64url(signature)}, k=${this.options.publicKey}`;\n }\n}\n\n/**\n * A browser subscription as a sender can use it: an https endpoint, a 65-byte uncompressed P-256\n * key and a 16-byte auth secret. Anything else — not JSON, missing keys, a key of the wrong size,\n * an endpoint that is not https — is undefined.\n */\nfunction parseSubscription(\n token: string\n): { endpoint: string; p256dh: Bytes; auth: Bytes } | undefined {\n try {\n const value = JSON.parse(token) as Partial<Subscription>;\n if (typeof value.endpoint !== 'string' || new URL(value.endpoint).protocol !== 'https:') {\n return undefined;\n }\n const p256dh = fromBase64url(value.keys?.p256dh ?? '');\n const auth = fromBase64url(value.keys?.auth ?? '');\n if (p256dh.length !== 65 || p256dh[0] !== 4 || auth.length !== 16) return undefined;\n return { endpoint: value.endpoint, p256dh, auth };\n } catch {\n return undefined;\n }\n}\n\nexport class WebPushSender implements MessageSender {\n constructor(private readonly options: WebPushOptions) {}\n\n async send(message: OutboundMessage): Promise<void | SendResult> {\n if (message.channel !== 'push') {\n throw new Error(`WebPushSender: unsupported channel '${message.channel}'`);\n }\n if (message.recipient === undefined) {\n throw new Error(`WebPushSender: no subscription for user '${message.userId}'`);\n }\n const subscription = parseSubscription(message.recipient);\n if (subscription === undefined) {\n // Not a usable subscription: nothing will ever deliver to it, so do not retry into it\n return { delivered: false, reason: 'InvalidSubscription' };\n }\n const content = await this.options.render(message.template, message.props);\n const payload = utf8(\n JSON.stringify({\n ...content,\n template: message.template,\n idempotencyKey: message.idempotencyKey,\n ...message.tracking?.data,\n })\n );\n if (payload.length > MAX_PLAINTEXT_BYTES) {\n // The same template renders the same size on every attempt: settle it before encrypting\n throw new PermanentError(\n `[webpush] payload for template '${message.template}' is ${payload.length} bytes; a push message carries at most ${MAX_PLAINTEXT_BYTES}`\n );\n }\n const body = await encryptPayload(payload, subscription.p256dh, subscription.auth);\n const doFetch = this.options.fetch ?? fetch;\n const response = await doFetch(subscription.endpoint, {\n method: 'POST',\n headers: {\n authorization: await this.options.credentials.authorization(subscription.endpoint),\n 'content-encoding': 'aes128gcm',\n 'content-type': 'application/octet-stream',\n ttl: String(this.options.ttl ?? 86_400),\n urgency: 'normal',\n // A resend of the same copy replaces the first one while it is still queued (RFC 8030\n // §5.4), so an at-least-once retry does not show the notification twice\n topic: await webPushTopic(message.idempotencyKey),\n },\n body,\n });\n if (response.ok) return;\n const { status } = response;\n if (status === 404 || status === 410) {\n // The browser unsubscribed or the subscription expired: it will never deliver again\n console.warn(`[webpush] subscription gone for user ${message.userId}: ${status}`);\n return { delivered: false, reason: status === 410 ? 'Gone' : 'NotFound' };\n }\n const text = await response.text();\n if (isRetryableStatus(status)) throw new Error(`[webpush] ${status}: ${text}`);\n throw new PermanentError(`[webpush] push service refused the request: ${status} ${text}`);\n }\n}\n\n/**\n * The `Topic` header for one copy: RFC 8030 §5.4 allows at most 32 characters of the URL-safe\n * base64 alphabet, so the idempotency key goes through SHA-256 and is cut to size.\n */\nexport async function webPushTopic(idempotencyKey: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', utf8(idempotencyKey));\n return base64url(new Uint8Array(digest)).slice(0, 32);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmDA,MAAa,qCAA0C,IAAI,IAAI;CAC7D;CACA;CACA;AACF,CAAC;;AAQD,eAAsB,oBAAwC;CAC5D,MAAM,OAAO,MAAM,OAAO,OAAO,YAAY;EAAE,MAAM;EAAS,YAAY;CAAQ,GAAG,MAAM,CACzF,QACA,QACF,CAAC;CACD,MAAM,MAAM,IAAI,WAAW,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,SAAS,CAAC;CAC/E,MAAM,MAAM,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,UAAU;CAChE,OAAO;EAAE,WAAWA,YAAAA,UAAU,GAAG;EAAG,YAAY,IAAI,KAAK;CAAG;AAC9D;;AAGA,MAAM,cAAc;;;;;;;AAOpB,MAAa,sBAAsB;AAGnC,MAAM,UAAU,IAAI,YAAY;AAChC,MAAM,QAAQ,SAAwB,QAAQ,OAAO,IAAI;AAEzD,SAAgB,cAAc,MAAqB;CACjD,OAAO,IAAI,WAAWC,YAAAA,OAAO,KAAK,MAAM,WAAW,CAAC;AACtD;AAEA,MAAM,UAAU,GAAG,UAA+B,IAAI,WAAWA,YAAAA,OAAO,OAAO,KAAK,CAAC;;AAGrF,eAAe,KAAK,MAAa,KAAY,MAAa,QAAgC;CACxF,MAAM,MAAM,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,QAAQ,OAAO,CAAC,YAAY,CAAC;CACnF,OAAO,IAAI,WACT,MAAM,OAAO,OAAO,WAAW;EAAE,MAAM;EAAQ,MAAM;EAAW;EAAM;CAAK,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M,CAAC,CAAC,CAAC,MAAM,GAAG,EAAE;AACtD"}
|
package/dist/webpush.d.cts
CHANGED
|
@@ -8,7 +8,7 @@ import { PushRenderer } from "./push.cjs";
|
|
|
8
8
|
* browser's push service accepts the same request, over HTTP/1.1 — with nothing but WebCrypto.
|
|
9
9
|
*
|
|
10
10
|
* The recipient is a browser's `PushSubscription` as JSON (`JSON.stringify(subscription)`),
|
|
11
|
-
* registered like an app token (`registerDevice(userId,
|
|
11
|
+
* registered like an app token (`registerDevice({ userId, token, platform: 'web' })`). The
|
|
12
12
|
* service worker receives `{ title, body, image?, url?, template, …tracking data }` as the push
|
|
13
13
|
* event's JSON.
|
|
14
14
|
*/
|
package/dist/webpush.d.mts
CHANGED
|
@@ -8,7 +8,7 @@ import { PushRenderer } from "./push.mjs";
|
|
|
8
8
|
* browser's push service accepts the same request, over HTTP/1.1 — with nothing but WebCrypto.
|
|
9
9
|
*
|
|
10
10
|
* The recipient is a browser's `PushSubscription` as JSON (`JSON.stringify(subscription)`),
|
|
11
|
-
* registered like an app token (`registerDevice(userId,
|
|
11
|
+
* registered like an app token (`registerDevice({ userId, token, platform: 'web' })`). The
|
|
12
12
|
* service worker receives `{ title, body, image?, url?, template, …tracking data }` as the push
|
|
13
13
|
* event's JSON.
|
|
14
14
|
*/
|
package/dist/webpush.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpush.mjs","names":[],"sources":["../src/webpush.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport type { MessageSender, OutboundMessage, SendResult } from './engine';\nimport { PermanentError, isRetryableStatus } from './engine/retry';\nimport { base64url } from './jwt';\nimport type { PushRenderer } from './push';\n\n/**\n * `@shware/workflow/webpush` — browser push through the standard Web Push protocol: VAPID\n * (RFC 8292) identifies the sender, the payload is encrypted for the subscription (RFC 8291,\n * `aes128gcm`, RFC 8188). One sender reaches Chrome, Edge, Firefox and Safari 16+ — each\n * browser's push service accepts the same request, over HTTP/1.1 — with nothing but WebCrypto.\n *\n * The recipient is a browser's `PushSubscription` as JSON (`JSON.stringify(subscription)`),\n * registered like an app token (`registerDevice(userId, { token, platform: 'web' })`). The\n * service worker receives `{ title, body, image?, url?, template, …tracking data }` as the push\n * event's JSON.\n */\n\n/** A VAPID key pair: the uncompressed P-256 public key and the private scalar, base64url. */\nexport interface VapidKeys {\n publicKey: string;\n privateKey: string;\n}\n\nexport interface VapidSignerOptions extends VapidKeys {\n /** Who to contact about this sender: `mailto:` or an `https:` URL (RFC 8292). */\n subject: string;\n}\n\nexport interface WebPushOptions {\n /** The VAPID signer the requests are authorized with — shared by every sender on the same key pair. */\n credentials: VapidSigner;\n render: PushRenderer;\n /** Seconds the push service keeps an undelivered message; a day by default. */\n ttl?: number;\n /** Fetch implementation (defaults to the global one). */\n fetch?: typeof fetch;\n}\n\n/**\n * How a push service's answer is classified (RFC 8030 §7 and §8.1, with the browsers' services\n * answering as documented there):\n *\n * - dead subscription: 404 and 410 — the browser unsubscribed or the subscription expired\n * (RFC 8030 §7.3: 410 Gone for an expired subscription) — and a subscription the sender\n * cannot parse (`InvalidSubscription`). The copy settles undelivered and the host forgets it.\n * - transient: 429 Too Many Requests (§8.4) and 5xx.\n * - everything else is this request or this sender: 400 (a bad header or body), 401 / 403 (the\n * VAPID key pair or subject, §8.2 of RFC 8292), 413 (the payload, RFC 8030 §7.2) and any other\n * 4xx are a `PermanentError`.\n */\nexport const DEAD_TOKEN_REASONS: ReadonlySet<string> = new Set([\n 'Gone',\n 'NotFound',\n 'InvalidSubscription',\n]);\n\ninterface Subscription {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n}\n\n/** A fresh VAPID key pair (once per project; the private key is a secret). */\nexport async function generateVapidKeys(): Promise<VapidKeys> {\n const pair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]);\n const raw = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey));\n const jwk = await crypto.subtle.exportKey('jwk', pair.privateKey);\n return { publicKey: base64url(raw), privateKey: jwk.d ?? '' };\n}\n\n/** The record size the header announces: RFC 8291 §4 fixes it at 4096 and one record per push. */\nconst RECORD_SIZE = 4096;\n/**\n * The largest plaintext one record carries. A push message body is at most 4096 octets (RFC 8030\n * §7.2); the aes128gcm header takes 86 of them (16 salt + 4 rs + 1 idlen + 65 key), the record its\n * 16-octet tag and the 1-octet delimiter — 3993 octets of plaintext (RFC 8291 §4). Anything past\n * that is either an invalid record or a 413 from the push service.\n */\nexport const MAX_PLAINTEXT_BYTES = 3993;\n/** Bytes WebCrypto accepts (backed by a plain ArrayBuffer). */\ntype Bytes = Uint8Array<ArrayBuffer>;\nconst encoder = new TextEncoder();\nconst utf8 = (text: string): Bytes => encoder.encode(text);\n\nexport function fromBase64url(text: string): Bytes {\n return new Uint8Array(Buffer.from(text, 'base64url'));\n}\n\nconst concat = (...parts: Uint8Array[]): Bytes => new Uint8Array(Buffer.concat(parts));\n\n/** HKDF-SHA256 (RFC 5869), as WebCrypto provides it. */\nasync function hkdf(salt: Bytes, ikm: Bytes, info: Bytes, length: number): Promise<Bytes> {\n const key = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);\n return new Uint8Array(\n await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, key, length * 8)\n );\n}\n\n/**\n * The `aes128gcm` body for one subscription (RFC 8291 §3.4): salt, record size, the sender's\n * ephemeral public key, then the payload sealed under a key both sides derive from ECDH and the\n * subscription's auth secret.\n */\nexport async function encryptPayload(\n payload: Bytes,\n p256dh: Bytes,\n authSecret: Bytes,\n salt: Bytes = crypto.getRandomValues(new Uint8Array(16))\n): Promise<Bytes> {\n const ephemeral = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [\n 'deriveBits',\n ]);\n const senderPublic = new Uint8Array(await crypto.subtle.exportKey('raw', ephemeral.publicKey));\n const receiver = await crypto.subtle.importKey(\n 'raw',\n p256dh,\n { name: 'ECDH', namedCurve: 'P-256' },\n false,\n []\n );\n const shared = new Uint8Array(\n await crypto.subtle.deriveBits({ name: 'ECDH', public: receiver }, ephemeral.privateKey, 256)\n );\n const ikm = await hkdf(\n authSecret,\n shared,\n concat(utf8('WebPush: info\\0'), p256dh, senderPublic),\n 32\n );\n const cek = await hkdf(salt, ikm, utf8('Content-Encoding: aes128gcm\\0'), 16);\n const nonce = await hkdf(salt, ikm, utf8('Content-Encoding: nonce\\0'), 12);\n const key = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);\n // The single, last record: the payload and the 0x02 delimiter, no padding\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: nonce },\n key,\n concat(payload, new Uint8Array([2]))\n )\n );\n const header = new Uint8Array(16 + 4 + 1);\n header.set(salt, 0);\n new DataView(header.buffer).setUint32(16, RECORD_SIZE);\n header[20] = senderPublic.length;\n return concat(header, senderPublic, sealed);\n}\n\n/** How long a VAPID token is good for: RFC 8292 §2 allows at most 24 hours. */\nconst VAPID_EXP_S = 24 * 3600;\n/** How long a signed token is reused: half its life, so it is never sent near expiry. */\nconst VAPID_TTL_MS = 12 * 3600_000;\n\n/**\n * The VAPID `Authorization` header (RFC 8292 §3) for one key pair. The private key is imported\n * once; the JWT is signed per push service (its `aud` is the service's origin) and reused for\n * `VAPID_TTL_MS`. Concurrent callers for one origin share the one signing in flight, and a signing\n * that failed is not kept. One instance serves every sender built on the pair — a host keeps it\n * across runs, and builds the senders per run.\n */\nexport class VapidSigner {\n private key: Promise<CryptoKey> | undefined;\n private readonly signed = new Map<string, { value: string; issuedAt: number }>();\n private readonly signing = new Map<string, Promise<string>>();\n\n constructor(private readonly options: VapidSignerOptions) {}\n\n /** The header value for the push service at `audience` — its origin, or any URL on it. */\n async authorization(audience: string, now = Date.now()): Promise<string> {\n const origin = new URL(audience).origin;\n const current = this.signed.get(origin);\n if (current !== undefined && now - current.issuedAt < VAPID_TTL_MS) return current.value;\n let pending = this.signing.get(origin);\n if (pending === undefined) {\n pending = this.sign(origin, now)\n .then((value) => {\n this.signed.set(origin, { value, issuedAt: now });\n return value;\n })\n .finally(() => {\n this.signing.delete(origin);\n });\n this.signing.set(origin, pending);\n }\n return pending;\n }\n\n private privateKey(): Promise<CryptoKey> {\n if (this.key === undefined) {\n const publicKey = fromBase64url(this.options.publicKey);\n this.key = crypto.subtle\n .importKey(\n 'jwk',\n {\n kty: 'EC',\n crv: 'P-256',\n d: this.options.privateKey,\n x: base64url(publicKey.slice(1, 33)),\n y: base64url(publicKey.slice(33, 65)),\n ext: true,\n },\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign']\n )\n .catch((error: unknown) => {\n this.key = undefined;\n throw error;\n });\n }\n return this.key;\n }\n\n private async sign(origin: string, now: number): Promise<string> {\n const key = await this.privateKey();\n const header = base64url(JSON.stringify({ typ: 'JWT', alg: 'ES256' }));\n const claims = base64url(\n JSON.stringify({\n aud: origin,\n exp: Math.floor(now / 1000) + VAPID_EXP_S,\n sub: this.options.subject,\n })\n );\n const signature = new Uint8Array(\n await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, utf8(`${header}.${claims}`))\n );\n return `vapid t=${header}.${claims}.${base64url(signature)}, k=${this.options.publicKey}`;\n }\n}\n\n/**\n * A browser subscription as a sender can use it: an https endpoint, a 65-byte uncompressed P-256\n * key and a 16-byte auth secret. Anything else — not JSON, missing keys, a key of the wrong size,\n * an endpoint that is not https — is undefined.\n */\nfunction parseSubscription(\n token: string\n): { endpoint: string; p256dh: Bytes; auth: Bytes } | undefined {\n try {\n const value = JSON.parse(token) as Partial<Subscription>;\n if (typeof value.endpoint !== 'string' || new URL(value.endpoint).protocol !== 'https:') {\n return undefined;\n }\n const p256dh = fromBase64url(value.keys?.p256dh ?? '');\n const auth = fromBase64url(value.keys?.auth ?? '');\n if (p256dh.length !== 65 || p256dh[0] !== 4 || auth.length !== 16) return undefined;\n return { endpoint: value.endpoint, p256dh, auth };\n } catch {\n return undefined;\n }\n}\n\nexport class WebPushSender implements MessageSender {\n constructor(private readonly options: WebPushOptions) {}\n\n async send(message: OutboundMessage): Promise<void | SendResult> {\n if (message.channel !== 'push') {\n throw new Error(`WebPushSender: unsupported channel '${message.channel}'`);\n }\n if (message.recipient === undefined) {\n throw new Error(`WebPushSender: no subscription for user '${message.userId}'`);\n }\n const subscription = parseSubscription(message.recipient);\n if (subscription === undefined) {\n // Not a usable subscription: nothing will ever deliver to it, so do not retry into it\n return { delivered: false, reason: 'InvalidSubscription' };\n }\n const content = await this.options.render(message.template, message.props);\n const payload = utf8(\n JSON.stringify({\n ...content,\n template: message.template,\n idempotencyKey: message.idempotencyKey,\n ...message.tracking?.data,\n })\n );\n if (payload.length > MAX_PLAINTEXT_BYTES) {\n // The same template renders the same size on every attempt: settle it before encrypting\n throw new PermanentError(\n `[webpush] payload for template '${message.template}' is ${payload.length} bytes; a push message carries at most ${MAX_PLAINTEXT_BYTES}`\n );\n }\n const body = await encryptPayload(payload, subscription.p256dh, subscription.auth);\n const doFetch = this.options.fetch ?? fetch;\n const response = await doFetch(subscription.endpoint, {\n method: 'POST',\n headers: {\n authorization: await this.options.credentials.authorization(subscription.endpoint),\n 'content-encoding': 'aes128gcm',\n 'content-type': 'application/octet-stream',\n ttl: String(this.options.ttl ?? 86_400),\n urgency: 'normal',\n // A resend of the same copy replaces the first one while it is still queued (RFC 8030\n // §5.4), so an at-least-once retry does not show the notification twice\n topic: await webPushTopic(message.idempotencyKey),\n },\n body,\n });\n if (response.ok) return;\n const { status } = response;\n if (status === 404 || status === 410) {\n // The browser unsubscribed or the subscription expired: it will never deliver again\n console.warn(`[webpush] subscription gone for user ${message.userId}: ${status}`);\n return { delivered: false, reason: status === 410 ? 'Gone' : 'NotFound' };\n }\n const text = await response.text();\n if (isRetryableStatus(status)) throw new Error(`[webpush] ${status}: ${text}`);\n throw new PermanentError(`[webpush] push service refused the request: ${status} ${text}`);\n }\n}\n\n/**\n * The `Topic` header for one copy: RFC 8030 §5.4 allows at most 32 characters of the URL-safe\n * base64 alphabet, so the idempotency key goes through SHA-256 and is cut to size.\n */\nexport async function webPushTopic(idempotencyKey: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', utf8(idempotencyKey));\n return base64url(new Uint8Array(digest)).slice(0, 32);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmDA,MAAa,qCAA0C,IAAI,IAAI;CAC7D;CACA;CACA;AACF,CAAC;;AAQD,eAAsB,oBAAwC;CAC5D,MAAM,OAAO,MAAM,OAAO,OAAO,YAAY;EAAE,MAAM;EAAS,YAAY;CAAQ,GAAG,MAAM,CACzF,QACA,QACF,CAAC;CACD,MAAM,MAAM,IAAI,WAAW,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,SAAS,CAAC;CAC/E,MAAM,MAAM,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,UAAU;CAChE,OAAO;EAAE,WAAW,UAAU,GAAG;EAAG,YAAY,IAAI,KAAK;CAAG;AAC9D;;AAGA,MAAM,cAAc;;;;;;;AAOpB,MAAa,sBAAsB;AAGnC,MAAM,UAAU,IAAI,YAAY;AAChC,MAAM,QAAQ,SAAwB,QAAQ,OAAO,IAAI;AAEzD,SAAgB,cAAc,MAAqB;CACjD,OAAO,IAAI,WAAW,OAAO,KAAK,MAAM,WAAW,CAAC;AACtD;AAEA,MAAM,UAAU,GAAG,UAA+B,IAAI,WAAW,OAAO,OAAO,KAAK,CAAC;;AAGrF,eAAe,KAAK,MAAa,KAAY,MAAa,QAAgC;CACxF,MAAM,MAAM,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,QAAQ,OAAO,CAAC,YAAY,CAAC;CACnF,OAAO,IAAI,WACT,MAAM,OAAO,OAAO,WAAW;EAAE,MAAM;EAAQ,MAAM;EAAW;EAAM;CAAK,GAAG,KAAK,SAAS,CAAC,CAC/F;AACF;;;;;;AAOA,eAAsB,eACpB,SACA,QACA,YACA,OAAc,OAAO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AK,UAAU;GACb,GAAG;GACH,UAAU,QAAQ;GAClB,gBAAgB,QAAQ;GACxB,GAAG,QAAQ,UAAU;EACvB,CAAC,CACH;EACA,IAAI,QAAQ,SAAA,MAEV,MAAM,IAAI,eACR,mCAAmC,QAAQ,SAAS,OAAO,QAAQ,OAAO,yCAAyC,qBACrH;EAEF,MAAM,OAAO,MAAM,eAAe,SAAS,aAAa,QAAQ,aAAa,IAAI;EAEjF,MAAM,WAAW,OADD,KAAK,QAAQ,SAAS,MAAA,CACP,aAAa,UAAU;GACpD,QAAQ;GACR,SAAS;IACP,eAAe,MAAM,KAAK,QAAQ,YAAY,cAAc,aAAa,QAAQ;IACjF,oBAAoB;IACpB,gBAAgB;IAChB,KAAK,OAAO,KAAK,QAAQ,OAAO,KAAM;IACtC,SAAS;IAGT,OAAO,MAAM,aAAa,QAAQ,cAAc;GAClD;GACA;EACF,CAAC;EACD,IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,IAAI,WAAW,OAAO,WAAW,KAAK;GAEpC,QAAQ,KAAK,wCAAwC,QAAQ,OAAO,IAAI,QAAQ;GAChF,OAAO;IAAE,WAAW;IAAO,QAAQ,WAAW,MAAM,SAAS;GAAW;EAC1E;EACA,MAAM,OAAO,MAAM,SAAS,KAAK;EACjC,IAAI,kBAAkB,MAAM,GAAG,MAAM,IAAI,MAAM,aAAa,OAAO,IAAI,MAAM;EAC7E,MAAM,IAAI,eAAe,+CAA+C,OAAO,GAAG,MAAM;CAC1F;AACF;;;;;AAMA,eAAsB,aAAa,gBAAyC;CAC1E,MAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,cAAc,CAAC;CACzE,OAAO,UAAU,IAAI,WAAW,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,EAAE;AACtD"}
|
|
1
|
+
{"version":3,"file":"webpush.mjs","names":[],"sources":["../src/webpush.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport type { MessageSender, OutboundMessage, SendResult } from './engine';\nimport { PermanentError, isRetryableStatus } from './engine/retry';\nimport { base64url } from './jwt';\nimport type { PushRenderer } from './push';\n\n/**\n * `@shware/workflow/webpush` — browser push through the standard Web Push protocol: VAPID\n * (RFC 8292) identifies the sender, the payload is encrypted for the subscription (RFC 8291,\n * `aes128gcm`, RFC 8188). One sender reaches Chrome, Edge, Firefox and Safari 16+ — each\n * browser's push service accepts the same request, over HTTP/1.1 — with nothing but WebCrypto.\n *\n * The recipient is a browser's `PushSubscription` as JSON (`JSON.stringify(subscription)`),\n * registered like an app token (`registerDevice({ userId, token, platform: 'web' })`). The\n * service worker receives `{ title, body, image?, url?, template, …tracking data }` as the push\n * event's JSON.\n */\n\n/** A VAPID key pair: the uncompressed P-256 public key and the private scalar, base64url. */\nexport interface VapidKeys {\n publicKey: string;\n privateKey: string;\n}\n\nexport interface VapidSignerOptions extends VapidKeys {\n /** Who to contact about this sender: `mailto:` or an `https:` URL (RFC 8292). */\n subject: string;\n}\n\nexport interface WebPushOptions {\n /** The VAPID signer the requests are authorized with — shared by every sender on the same key pair. */\n credentials: VapidSigner;\n render: PushRenderer;\n /** Seconds the push service keeps an undelivered message; a day by default. */\n ttl?: number;\n /** Fetch implementation (defaults to the global one). */\n fetch?: typeof fetch;\n}\n\n/**\n * How a push service's answer is classified (RFC 8030 §7 and §8.1, with the browsers' services\n * answering as documented there):\n *\n * - dead subscription: 404 and 410 — the browser unsubscribed or the subscription expired\n * (RFC 8030 §7.3: 410 Gone for an expired subscription) — and a subscription the sender\n * cannot parse (`InvalidSubscription`). The copy settles undelivered and the host forgets it.\n * - transient: 429 Too Many Requests (§8.4) and 5xx.\n * - everything else is this request or this sender: 400 (a bad header or body), 401 / 403 (the\n * VAPID key pair or subject, §8.2 of RFC 8292), 413 (the payload, RFC 8030 §7.2) and any other\n * 4xx are a `PermanentError`.\n */\nexport const DEAD_TOKEN_REASONS: ReadonlySet<string> = new Set([\n 'Gone',\n 'NotFound',\n 'InvalidSubscription',\n]);\n\ninterface Subscription {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n}\n\n/** A fresh VAPID key pair (once per project; the private key is a secret). */\nexport async function generateVapidKeys(): Promise<VapidKeys> {\n const pair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]);\n const raw = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey));\n const jwk = await crypto.subtle.exportKey('jwk', pair.privateKey);\n return { publicKey: base64url(raw), privateKey: jwk.d ?? '' };\n}\n\n/** The record size the header announces: RFC 8291 §4 fixes it at 4096 and one record per push. */\nconst RECORD_SIZE = 4096;\n/**\n * The largest plaintext one record carries. A push message body is at most 4096 octets (RFC 8030\n * §7.2); the aes128gcm header takes 86 of them (16 salt + 4 rs + 1 idlen + 65 key), the record its\n * 16-octet tag and the 1-octet delimiter — 3993 octets of plaintext (RFC 8291 §4). Anything past\n * that is either an invalid record or a 413 from the push service.\n */\nexport const MAX_PLAINTEXT_BYTES = 3993;\n/** Bytes WebCrypto accepts (backed by a plain ArrayBuffer). */\ntype Bytes = Uint8Array<ArrayBuffer>;\nconst encoder = new TextEncoder();\nconst utf8 = (text: string): Bytes => encoder.encode(text);\n\nexport function fromBase64url(text: string): Bytes {\n return new Uint8Array(Buffer.from(text, 'base64url'));\n}\n\nconst concat = (...parts: Uint8Array[]): Bytes => new Uint8Array(Buffer.concat(parts));\n\n/** HKDF-SHA256 (RFC 5869), as WebCrypto provides it. */\nasync function hkdf(salt: Bytes, ikm: Bytes, info: Bytes, length: number): Promise<Bytes> {\n const key = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);\n return new Uint8Array(\n await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, key, length * 8)\n );\n}\n\n/**\n * The `aes128gcm` body for one subscription (RFC 8291 §3.4): salt, record size, the sender's\n * ephemeral public key, then the payload sealed under a key both sides derive from ECDH and the\n * subscription's auth secret.\n */\nexport async function encryptPayload(\n payload: Bytes,\n p256dh: Bytes,\n authSecret: Bytes,\n salt: Bytes = crypto.getRandomValues(new Uint8Array(16))\n): Promise<Bytes> {\n const ephemeral = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [\n 'deriveBits',\n ]);\n const senderPublic = new Uint8Array(await crypto.subtle.exportKey('raw', ephemeral.publicKey));\n const receiver = await crypto.subtle.importKey(\n 'raw',\n p256dh,\n { name: 'ECDH', namedCurve: 'P-256' },\n false,\n []\n );\n const shared = new Uint8Array(\n await crypto.subtle.deriveBits({ name: 'ECDH', public: receiver }, ephemeral.privateKey, 256)\n );\n const ikm = await hkdf(\n authSecret,\n shared,\n concat(utf8('WebPush: info\\0'), p256dh, senderPublic),\n 32\n );\n const cek = await hkdf(salt, ikm, utf8('Content-Encoding: aes128gcm\\0'), 16);\n const nonce = await hkdf(salt, ikm, utf8('Content-Encoding: nonce\\0'), 12);\n const key = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);\n // The single, last record: the payload and the 0x02 delimiter, no padding\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv: nonce },\n key,\n concat(payload, new Uint8Array([2]))\n )\n );\n const header = new Uint8Array(16 + 4 + 1);\n header.set(salt, 0);\n new DataView(header.buffer).setUint32(16, RECORD_SIZE);\n header[20] = senderPublic.length;\n return concat(header, senderPublic, sealed);\n}\n\n/** How long a VAPID token is good for: RFC 8292 §2 allows at most 24 hours. */\nconst VAPID_EXP_S = 24 * 3600;\n/** How long a signed token is reused: half its life, so it is never sent near expiry. */\nconst VAPID_TTL_MS = 12 * 3600_000;\n\n/**\n * The VAPID `Authorization` header (RFC 8292 §3) for one key pair. The private key is imported\n * once; the JWT is signed per push service (its `aud` is the service's origin) and reused for\n * `VAPID_TTL_MS`. Concurrent callers for one origin share the one signing in flight, and a signing\n * that failed is not kept. One instance serves every sender built on the pair — a host keeps it\n * across runs, and builds the senders per run.\n */\nexport class VapidSigner {\n private key: Promise<CryptoKey> | undefined;\n private readonly signed = new Map<string, { value: string; issuedAt: number }>();\n private readonly signing = new Map<string, Promise<string>>();\n\n constructor(private readonly options: VapidSignerOptions) {}\n\n /** The header value for the push service at `audience` — its origin, or any URL on it. */\n async authorization(audience: string, now = Date.now()): Promise<string> {\n const origin = new URL(audience).origin;\n const current = this.signed.get(origin);\n if (current !== undefined && now - current.issuedAt < VAPID_TTL_MS) return current.value;\n let pending = this.signing.get(origin);\n if (pending === undefined) {\n pending = this.sign(origin, now)\n .then((value) => {\n this.signed.set(origin, { value, issuedAt: now });\n return value;\n })\n .finally(() => {\n this.signing.delete(origin);\n });\n this.signing.set(origin, pending);\n }\n return pending;\n }\n\n private privateKey(): Promise<CryptoKey> {\n if (this.key === undefined) {\n const publicKey = fromBase64url(this.options.publicKey);\n this.key = crypto.subtle\n .importKey(\n 'jwk',\n {\n kty: 'EC',\n crv: 'P-256',\n d: this.options.privateKey,\n x: base64url(publicKey.slice(1, 33)),\n y: base64url(publicKey.slice(33, 65)),\n ext: true,\n },\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign']\n )\n .catch((error: unknown) => {\n this.key = undefined;\n throw error;\n });\n }\n return this.key;\n }\n\n private async sign(origin: string, now: number): Promise<string> {\n const key = await this.privateKey();\n const header = base64url(JSON.stringify({ typ: 'JWT', alg: 'ES256' }));\n const claims = base64url(\n JSON.stringify({\n aud: origin,\n exp: Math.floor(now / 1000) + VAPID_EXP_S,\n sub: this.options.subject,\n })\n );\n const signature = new Uint8Array(\n await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, utf8(`${header}.${claims}`))\n );\n return `vapid t=${header}.${claims}.${base64url(signature)}, k=${this.options.publicKey}`;\n }\n}\n\n/**\n * A browser subscription as a sender can use it: an https endpoint, a 65-byte uncompressed P-256\n * key and a 16-byte auth secret. Anything else — not JSON, missing keys, a key of the wrong size,\n * an endpoint that is not https — is undefined.\n */\nfunction parseSubscription(\n token: string\n): { endpoint: string; p256dh: Bytes; auth: Bytes } | undefined {\n try {\n const value = JSON.parse(token) as Partial<Subscription>;\n if (typeof value.endpoint !== 'string' || new URL(value.endpoint).protocol !== 'https:') {\n return undefined;\n }\n const p256dh = fromBase64url(value.keys?.p256dh ?? '');\n const auth = fromBase64url(value.keys?.auth ?? '');\n if (p256dh.length !== 65 || p256dh[0] !== 4 || auth.length !== 16) return undefined;\n return { endpoint: value.endpoint, p256dh, auth };\n } catch {\n return undefined;\n }\n}\n\nexport class WebPushSender implements MessageSender {\n constructor(private readonly options: WebPushOptions) {}\n\n async send(message: OutboundMessage): Promise<void | SendResult> {\n if (message.channel !== 'push') {\n throw new Error(`WebPushSender: unsupported channel '${message.channel}'`);\n }\n if (message.recipient === undefined) {\n throw new Error(`WebPushSender: no subscription for user '${message.userId}'`);\n }\n const subscription = parseSubscription(message.recipient);\n if (subscription === undefined) {\n // Not a usable subscription: nothing will ever deliver to it, so do not retry into it\n return { delivered: false, reason: 'InvalidSubscription' };\n }\n const content = await this.options.render(message.template, message.props);\n const payload = utf8(\n JSON.stringify({\n ...content,\n template: message.template,\n idempotencyKey: message.idempotencyKey,\n ...message.tracking?.data,\n })\n );\n if (payload.length > MAX_PLAINTEXT_BYTES) {\n // The same template renders the same size on every attempt: settle it before encrypting\n throw new PermanentError(\n `[webpush] payload for template '${message.template}' is ${payload.length} bytes; a push message carries at most ${MAX_PLAINTEXT_BYTES}`\n );\n }\n const body = await encryptPayload(payload, subscription.p256dh, subscription.auth);\n const doFetch = this.options.fetch ?? fetch;\n const response = await doFetch(subscription.endpoint, {\n method: 'POST',\n headers: {\n authorization: await this.options.credentials.authorization(subscription.endpoint),\n 'content-encoding': 'aes128gcm',\n 'content-type': 'application/octet-stream',\n ttl: String(this.options.ttl ?? 86_400),\n urgency: 'normal',\n // A resend of the same copy replaces the first one while it is still queued (RFC 8030\n // §5.4), so an at-least-once retry does not show the notification twice\n topic: await webPushTopic(message.idempotencyKey),\n },\n body,\n });\n if (response.ok) return;\n const { status } = response;\n if (status === 404 || status === 410) {\n // The browser unsubscribed or the subscription expired: it will never deliver again\n console.warn(`[webpush] subscription gone for user ${message.userId}: ${status}`);\n return { delivered: false, reason: status === 410 ? 'Gone' : 'NotFound' };\n }\n const text = await response.text();\n if (isRetryableStatus(status)) throw new Error(`[webpush] ${status}: ${text}`);\n throw new PermanentError(`[webpush] push service refused the request: ${status} ${text}`);\n }\n}\n\n/**\n * The `Topic` header for one copy: RFC 8030 §5.4 allows at most 32 characters of the URL-safe\n * base64 alphabet, so the idempotency key goes through SHA-256 and is cut to size.\n */\nexport async function webPushTopic(idempotencyKey: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', utf8(idempotencyKey));\n return base64url(new Uint8Array(digest)).slice(0, 32);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmDA,MAAa,qCAA0C,IAAI,IAAI;CAC7D;CACA;CACA;AACF,CAAC;;AAQD,eAAsB,oBAAwC;CAC5D,MAAM,OAAO,MAAM,OAAO,OAAO,YAAY;EAAE,MAAM;EAAS,YAAY;CAAQ,GAAG,MAAM,CACzF,QACA,QACF,CAAC;CACD,MAAM,MAAM,IAAI,WAAW,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,SAAS,CAAC;CAC/E,MAAM,MAAM,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,UAAU;CAChE,OAAO;EAAE,WAAW,UAAU,GAAG;EAAG,YAAY,IAAI,KAAK;CAAG;AAC9D;;AAGA,MAAM,cAAc;;;;;;;AAOpB,MAAa,sBAAsB;AAGnC,MAAM,UAAU,IAAI,YAAY;AAChC,MAAM,QAAQ,SAAwB,QAAQ,OAAO,IAAI;AAEzD,SAAgB,cAAc,MAAqB;CACjD,OAAO,IAAI,WAAW,OAAO,KAAK,MAAM,WAAW,CAAC;AACtD;AAEA,MAAM,UAAU,GAAG,UAA+B,IAAI,WAAW,OAAO,OAAO,KAAK,CAAC;;AAGrF,eAAe,KAAK,MAAa,KAAY,MAAa,QA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