easy-ping 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +159 -78
  2. package/dist/adapter-B7R4rXtJ.d.cts +17 -0
  3. package/dist/adapter-B7R4rXtJ.d.ts +17 -0
  4. package/dist/{adapter-BfLe2J0t.d.cts → adapter-D3lTy-4E.d.cts} +6 -32
  5. package/dist/{adapter-BfLe2J0t.d.ts → adapter-D3lTy-4E.d.ts} +6 -32
  6. package/dist/adapters/drizzle.cjs +1 -2
  7. package/dist/adapters/drizzle.cjs.map +1 -1
  8. package/dist/adapters/drizzle.d.cts +1 -1
  9. package/dist/adapters/drizzle.d.ts +1 -1
  10. package/dist/adapters/drizzle.js +3 -4
  11. package/dist/adapters/drizzle.js.map +1 -1
  12. package/dist/adapters/mongodb.cjs +2 -5
  13. package/dist/adapters/mongodb.cjs.map +1 -1
  14. package/dist/adapters/mongodb.d.cts +4 -17
  15. package/dist/adapters/mongodb.d.ts +4 -17
  16. package/dist/adapters/mongodb.js +4 -7
  17. package/dist/adapters/mongodb.js.map +1 -1
  18. package/dist/adapters/mysql.cjs +605 -0
  19. package/dist/adapters/mysql.cjs.map +1 -0
  20. package/dist/adapters/mysql.d.cts +38 -0
  21. package/dist/adapters/mysql.d.ts +38 -0
  22. package/dist/adapters/mysql.js +51 -0
  23. package/dist/adapters/mysql.js.map +1 -0
  24. package/dist/adapters/postgres.cjs +16 -9
  25. package/dist/adapters/postgres.cjs.map +1 -1
  26. package/dist/adapters/postgres.d.cts +9 -54
  27. package/dist/adapters/postgres.d.ts +9 -54
  28. package/dist/adapters/postgres.js +6 -41
  29. package/dist/adapters/postgres.js.map +1 -1
  30. package/dist/adapters/sqlite.cjs +593 -0
  31. package/dist/adapters/sqlite.cjs.map +1 -0
  32. package/dist/adapters/sqlite.d.cts +37 -0
  33. package/dist/adapters/sqlite.d.ts +37 -0
  34. package/dist/adapters/sqlite.js +53 -0
  35. package/dist/adapters/sqlite.js.map +1 -0
  36. package/dist/browser.cjs.map +1 -1
  37. package/dist/browser.d.cts +2 -14
  38. package/dist/browser.d.ts +2 -14
  39. package/dist/browser.js.map +1 -1
  40. package/dist/chunk-2EYKPF5A.js +393 -0
  41. package/dist/chunk-2EYKPF5A.js.map +1 -0
  42. package/dist/{chunk-3Y2MBUAW.js → chunk-3VOQOGDR.js} +4 -3
  43. package/dist/chunk-3VOQOGDR.js.map +1 -0
  44. package/dist/{chunk-PSJHXZPR.js → chunk-AEYYTE5I.js} +2 -2
  45. package/dist/chunk-AEYYTE5I.js.map +1 -0
  46. package/dist/{chunk-DG3ZL5NP.js → chunk-BECMTNK7.js} +2 -2
  47. package/dist/chunk-BECMTNK7.js.map +1 -0
  48. package/dist/chunk-CK5UPVYP.js +48 -0
  49. package/dist/chunk-CK5UPVYP.js.map +1 -0
  50. package/dist/{chunk-W6I3B2CI.js → chunk-E4IZ2CQC.js} +2 -2
  51. package/dist/{chunk-W6I3B2CI.js.map → chunk-E4IZ2CQC.js.map} +1 -1
  52. package/dist/{chunk-CYKAM7LE.js → chunk-GJNLOQJS.js} +2 -2
  53. package/dist/chunk-GJNLOQJS.js.map +1 -0
  54. package/dist/chunk-HY47TQMY.js +52 -0
  55. package/dist/chunk-HY47TQMY.js.map +1 -0
  56. package/dist/chunk-M4R77BJD.js +64 -0
  57. package/dist/chunk-M4R77BJD.js.map +1 -0
  58. package/dist/{chunk-YEMRRMJQ.js → chunk-XIDVLYNQ.js} +14 -4
  59. package/dist/chunk-XIDVLYNQ.js.map +1 -0
  60. package/dist/client.cjs.map +1 -1
  61. package/dist/client.js.map +1 -1
  62. package/dist/index.cjs +2 -2
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +15 -60
  65. package/dist/index.d.ts +15 -60
  66. package/dist/index.js +9 -10
  67. package/dist/index.js.map +1 -1
  68. package/dist/node.cjs.map +1 -1
  69. package/dist/node.js +1 -1
  70. package/dist/node.js.map +1 -1
  71. package/dist/{plugin-C9Hoxus2.d.ts → plugin-CHd2ZiGC.d.cts} +5 -21
  72. package/dist/{plugin-CiMsGlQe.d.cts → plugin-Cg9usuUi.d.ts} +5 -21
  73. package/dist/plugins/digests.cjs +1 -4
  74. package/dist/plugins/digests.cjs.map +1 -1
  75. package/dist/plugins/digests.d.cts +6 -31
  76. package/dist/plugins/digests.d.ts +6 -31
  77. package/dist/plugins/digests.js +1 -4
  78. package/dist/plugins/digests.js.map +1 -1
  79. package/dist/plugins/preferences-client.cjs.map +1 -1
  80. package/dist/plugins/preferences-client.d.cts +2 -2
  81. package/dist/plugins/preferences-client.d.ts +2 -2
  82. package/dist/plugins/preferences-client.js +1 -1
  83. package/dist/plugins/preferences-react.cjs.map +1 -1
  84. package/dist/plugins/preferences-react.js.map +1 -1
  85. package/dist/plugins/preferences.cjs +1 -2
  86. package/dist/plugins/preferences.cjs.map +1 -1
  87. package/dist/plugins/preferences.d.cts +2 -2
  88. package/dist/plugins/preferences.d.ts +2 -2
  89. package/dist/plugins/preferences.js +2 -3
  90. package/dist/plugins/preferences.js.map +1 -1
  91. package/dist/plugins/push.cjs +1 -2
  92. package/dist/plugins/push.cjs.map +1 -1
  93. package/dist/plugins/push.d.cts +6 -26
  94. package/dist/plugins/push.d.ts +6 -26
  95. package/dist/plugins/push.js +3 -4
  96. package/dist/plugins/push.js.map +1 -1
  97. package/dist/providers/web-push.cjs.map +1 -1
  98. package/dist/providers/web-push.d.cts +3 -10
  99. package/dist/providers/web-push.d.ts +3 -10
  100. package/dist/providers/web-push.js.map +1 -1
  101. package/dist/react.cjs.map +1 -1
  102. package/dist/react.d.cts +1 -4
  103. package/dist/react.d.ts +1 -4
  104. package/dist/react.js.map +1 -1
  105. package/dist/schema.cjs +119 -1
  106. package/dist/schema.cjs.map +1 -1
  107. package/dist/schema.d.cts +20 -14
  108. package/dist/schema.d.ts +20 -14
  109. package/dist/schema.js +4 -2
  110. package/dist/testing.cjs +3 -19
  111. package/dist/testing.cjs.map +1 -1
  112. package/dist/testing.d.cts +4 -22
  113. package/dist/testing.d.ts +4 -22
  114. package/dist/testing.js +3 -19
  115. package/dist/testing.js.map +1 -1
  116. package/package.json +12 -1
  117. package/dist/chunk-3Y2MBUAW.js.map +0 -1
  118. package/dist/chunk-CYKAM7LE.js.map +0 -1
  119. package/dist/chunk-DG3ZL5NP.js.map +0 -1
  120. package/dist/chunk-PSJHXZPR.js.map +0 -1
  121. package/dist/chunk-YEMRRMJQ.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/plugin.ts","../../src/plugins/preferences/client.ts"],"names":[],"mappings":";;;AA2MO,SAAS,mBACd,MAAA,EAC6B;AAC7B,EAAA,OAAO,MAAA;AACT;;;AC3LO,IAAM,iBAAA,GAAoB,MAC/B,kBAAA,CAAmB;AAAA,EACjB,EAAA,EAAI,aAAA;AAAA,EACJ,oBAAoB,EAAC;AAAA,EAErB,OAAA,EAAS,CAAC,KAAA,MAAW;AAAA,IACnB,eAAA,EAAiB,YAId,MAAM,KAAA,CAAM,cAAc,CAAA;AAAA,IAK7B,gBAAA,EAAkB,OAAO,KAAA,KACtB,MAAM,MAAM,cAAA,EAAgB;AAAA,MAC3B,MAAA,EAAQ,MAAA;AAAA,MACR,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,KAAK;AAAA,KAC3B;AAAA,GACL;AACF,CAAC","file":"preferences-client.cjs","sourcesContent":["import type { DeliveryOutcome } from \"./adapter\";\nimport type { Logger } from \"./errors\";\nimport type { PluginStore } from \"./store\";\nimport type { SignRequest, TokenClaims } from \"./tokens\";\nimport type { Channel, Recipient } from \"./types\";\n\nexport type Promisable<T> = T | Promise<T>;\n\nexport type PrepareContext = {\n type: string;\n recipients: readonly Recipient[];\n};\n\nexport type BeforeSendContext = {\n type: string;\n recipient: Recipient;\n payload: unknown;\n actorId: string | null;\n dedupeKey: string | null;\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type BeforeSendResult =\n | { action: \"continue\"; payload?: unknown; dedupeKey?: string }\n | { action: \"cancel\"; reason: string };\n\nexport type ChannelDecision = {\n channel: Channel;\n action: \"send\" | \"skip\" | \"defer\";\n /** defer only. Written to notification_delivery.not_before. */\n notBefore?: Date | undefined;\n};\n\nexport type ResolveChannelsContext = {\n type: string;\n recipient: Recipient;\n payload: unknown;\n decisions: readonly ChannelDecision[];\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type DeliverContext = {\n channel: Channel;\n deliveryId: string;\n attempt: number;\n recipient: Recipient;\n notification: { id: string; userId: string; type: string; payload: unknown };\n /** Aborted on the runner's timeout. */\n signal: AbortSignal;\n};\n\nexport type AfterSendContext = {\n type: string;\n payload: unknown;\n /** Committed rows. Ids exist only at this point. */\n notifications: readonly { id: string; userId: string }[];\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type AfterDeliverContext = {\n deliveryId: string;\n notificationId: string;\n userId: string;\n channel: Channel;\n outcome: DeliveryOutcome;\n attempt: number;\n isTerminal: boolean;\n};\n\n/** beforeSend and resolveChannels fail closed; afterDeliver fails open. */\nexport type PluginHooks = {\n /** Once per send, for bulk loading — the per-recipient hooks would be an N+1. */\n prepare?: (ctx: PrepareContext) => Promisable<unknown>;\n beforeSend?: (ctx: BeforeSendContext) => Promisable<BeforeSendResult>;\n resolveChannels?: (ctx: ResolveChannelsContext) => Promisable<readonly ChannelDecision[]>;\n /**\n * Once per send, after the rows are committed. The only hook that sees\n * notification ids, which digests needs to bucket an entry against one.\n * Fails open: the notification is already written.\n */\n afterSend?: (ctx: AfterSendContext) => Promisable<void>;\n /**\n * Delivers one of the plugin's declared `channels`. Core carries inApp and\n * email; everything else arrives here, which is how push, sms and slack are\n * added without core learning about them.\n */\n deliver?: (ctx: DeliverContext) => Promisable<DeliveryOutcome>;\n afterDeliver?: (ctx: AfterDeliverContext) => Promisable<void>;\n};\n\nexport type FieldType = \"string\" | \"number\" | \"boolean\" | \"date\" | \"json\";\n\nexport type FieldDeclaration = {\n type: FieldType;\n required?: boolean;\n default?: string | number | boolean;\n /** date fields only. Renders as defaultNow() / CURRENT_TIMESTAMP. */\n defaultNow?: boolean;\n};\n\nexport type IndexDeclaration = {\n on: readonly string[];\n unique?: boolean;\n name?: string;\n};\n\nexport type TableDeclaration = {\n tableName: string;\n fields: Record<string, FieldDeclaration>;\n primaryKey?: readonly string[];\n indexes?: readonly IndexDeclaration[];\n};\n\nexport type SchemaDeclaration = Record<string, TableDeclaration>;\n\nexport type RouteScope =\n | { type: \"user\" }\n | { type: \"machine\" }\n | { type: \"signed\"; purpose: string }\n | { type: \"custom\"; justification: string };\n\nexport type RouteContext = {\n request: Request;\n /** Resolved for user-scoped routes, so a handler cannot forget to scope. */\n userId: string | null;\n /** Verified before dispatch, so a handler cannot forget to check. */\n claims: TokenClaims | null;\n params: Record<string, string>;\n};\n\nexport type RouteDefinition = {\n path: string;\n method: \"GET\" | \"POST\";\n scope: RouteScope;\n handler: (ctx: RouteContext) => Promise<Response>;\n};\n\n/** Handed to a plugin at startup so it need not be given the database twice. */\nexport type PluginInitContext = {\n /** Scoped to the tables this plugin declares in schema(). */\n store: PluginStore;\n /**\n * Mints tokens for this plugin's own `signed` routes and nothing else. The\n * master secret itself is never handed out: a plugin cannot forge another\n * plugin's links, or anything a future signed flow relies on.\n */\n sign: (request: SignRequest) => Promise<string>;\n logger: Logger;\n /** Configured notification names, so a route can refuse to store rows for types that do not exist. */\n notificationTypes: readonly string[];\n /** The app's resolver, for plugins that need timezones or addresses. */\n getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;\n /**\n * The instance's own send(). A plugin composing a message (a digest, say)\n * routes it back through the pipeline rather than reaching for a provider,\n * so it inherits retry, backoff and idempotency for free.\n */\n send: (\n type: string,\n args: { to: string | readonly string[]; payload: unknown; dedupeKey?: string },\n ) => Promise<unknown>;\n};\n\nexport type EasyPingPlugin<\n TId extends string = string,\n TSchema extends SchemaDeclaration = SchemaDeclaration,\n> = {\n id: TId;\n dependsOn?: readonly string[];\n schema?: TSchema;\n routes?: readonly RouteDefinition[];\n hooks?: PluginHooks;\n /** Channels this plugin delivers. Makes them usable in a notification. */\n channels?: readonly Channel[];\n /** Called once by easyPing() before any hook or route can run. */\n init?: (ctx: PluginInitContext) => void;\n};\n\nexport type AnyPlugin = EasyPingPlugin<string, SchemaDeclaration>;\n\nexport function definePlugin<TId extends string, TSchema extends SchemaDeclaration>(\n plugin: EasyPingPlugin<TId, TSchema>,\n): EasyPingPlugin<TId, TSchema> {\n return plugin;\n}\n\nexport type ClientFetch = (path: string, init?: RequestInit) => Promise<unknown>;\n\nexport type ClientPlugin<\n TId extends string = string,\n TActions extends Record<string, unknown> = Record<string, unknown>,\n> = {\n id: TId;\n /** Phantom. Links client types to the server plugin so a mismatch is a type error. */\n $InferServerPlugin?: AnyPlugin;\n actions: (fetch: ClientFetch) => TActions;\n};\n\nexport type AnyClientPlugin = ClientPlugin<string, Record<string, unknown>>;\n\nexport function defineClientPlugin<TId extends string, TActions extends Record<string, unknown>>(\n plugin: ClientPlugin<TId, TActions>,\n): ClientPlugin<TId, TActions> {\n return plugin;\n}\n\nexport type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (\n k: infer I,\n) => void\n ? I\n : never;\n\n/** Naked type parameter, so the conditional distributes over the union. */\ntype ExtractActions<TPlugin> = TPlugin extends { actions: (fetch: never) => infer TActions }\n ? TActions\n : never;\n\n/** Indexes the tuple rather than recursing: a fold blows the instantiation depth limit. */\nexport type ActionsOf<TPlugins extends readonly AnyClientPlugin[]> = UnionToIntersection<\n ExtractActions<TPlugins[number]>\n>;\n","import { defineClientPlugin } from \"../../core/plugin\";\nimport type { Channel, Frequency } from \"../../core/types\";\nimport type { preferences } from \"./index\";\n\nexport type PreferenceView = {\n userId: string;\n type: string;\n channel: Channel;\n enabled: boolean;\n frequency: Frequency;\n};\n\nexport type UpdatePreferenceInput = {\n type: string;\n channel: Channel;\n enabled?: boolean;\n frequency?: Frequency;\n};\n\n/** Paired by phantom type: importing the server plugin's value would bundle the DB. */\nexport const preferencesClient = () =>\n defineClientPlugin({\n id: \"preferences\",\n $InferServerPlugin: {} as ReturnType<typeof preferences>,\n\n actions: (fetch) => ({\n listPreferences: async (): Promise<{\n preferences: PreferenceView[];\n defaultEnabled: boolean;\n }> =>\n (await fetch(\"/preferences\")) as {\n preferences: PreferenceView[];\n defaultEnabled: boolean;\n },\n\n updatePreference: async (input: UpdatePreferenceInput): Promise<{ ok: boolean }> =>\n (await fetch(\"/preferences\", {\n method: \"POST\",\n body: JSON.stringify(input),\n })) as { ok: boolean },\n }),\n });\n\nexport type PreferencesClient = ReturnType<typeof preferencesClient>;\n"]}
1
+ {"version":3,"sources":["../../src/core/plugin.ts","../../src/plugins/preferences/client.ts"],"names":[],"mappings":";;;AA2LO,SAAS,mBACd,MAAA,EAC6B;AAC7B,EAAA,OAAO,MAAA;AACT;;;AC3KO,IAAM,iBAAA,GAAoB,MAC/B,kBAAA,CAAmB;AAAA,EACjB,EAAA,EAAI,aAAA;AAAA,EACJ,oBAAoB,EAAC;AAAA,EAErB,OAAA,EAAS,CAAC,KAAA,MAAW;AAAA,IACnB,eAAA,EAAiB,YAId,MAAM,KAAA,CAAM,cAAc,CAAA;AAAA,IAK7B,gBAAA,EAAkB,OAAO,KAAA,KACtB,MAAM,MAAM,cAAA,EAAgB;AAAA,MAC3B,MAAA,EAAQ,MAAA;AAAA,MACR,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,KAAK;AAAA,KAC3B;AAAA,GACL;AACF,CAAC","file":"preferences-client.cjs","sourcesContent":["import type { DeliveryOutcome } from \"./adapter\";\nimport type { Logger } from \"./errors\";\nimport type { PluginStore } from \"./store\";\nimport type { SignRequest, TokenClaims } from \"./tokens\";\nimport type { Channel, Recipient } from \"./types\";\n\nexport type Promisable<T> = T | Promise<T>;\n\nexport type PrepareContext = {\n type: string;\n recipients: readonly Recipient[];\n};\n\nexport type BeforeSendContext = {\n type: string;\n recipient: Recipient;\n payload: unknown;\n actorId: string | null;\n dedupeKey: string | null;\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type BeforeSendResult =\n | { action: \"continue\"; payload?: unknown; dedupeKey?: string }\n | { action: \"cancel\"; reason: string };\n\nexport type ChannelDecision = {\n channel: Channel;\n action: \"send\" | \"skip\" | \"defer\";\n /** defer only. Written to notification_delivery.not_before. */\n notBefore?: Date | undefined;\n};\n\nexport type ResolveChannelsContext = {\n type: string;\n recipient: Recipient;\n payload: unknown;\n decisions: readonly ChannelDecision[];\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type DeliverContext = {\n channel: Channel;\n deliveryId: string;\n attempt: number;\n recipient: Recipient;\n notification: { id: string; userId: string; type: string; payload: unknown };\n /** Aborted on the runner's timeout. */\n signal: AbortSignal;\n};\n\nexport type AfterSendContext = {\n type: string;\n payload: unknown;\n /** Committed rows. Ids exist only at this point. */\n notifications: readonly { id: string; userId: string }[];\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type AfterDeliverContext = {\n deliveryId: string;\n notificationId: string;\n userId: string;\n channel: Channel;\n outcome: DeliveryOutcome;\n attempt: number;\n isTerminal: boolean;\n};\n\n/** beforeSend and resolveChannels fail closed; afterDeliver fails open. */\nexport type PluginHooks = {\n /** Once per send, for bulk loading — the per-recipient hooks would be an N+1. */\n prepare?: (ctx: PrepareContext) => Promisable<unknown>;\n beforeSend?: (ctx: BeforeSendContext) => Promisable<BeforeSendResult>;\n resolveChannels?: (ctx: ResolveChannelsContext) => Promisable<readonly ChannelDecision[]>;\n /** Once per send, after commit. The only hook that sees notification ids. Fails open. */\n afterSend?: (ctx: AfterSendContext) => Promisable<void>;\n /** Delivers one of the plugin's declared `channels`. Core carries inApp and email. */\n deliver?: (ctx: DeliverContext) => Promisable<DeliveryOutcome>;\n afterDeliver?: (ctx: AfterDeliverContext) => Promisable<void>;\n};\n\nexport type FieldType = \"string\" | \"number\" | \"boolean\" | \"date\" | \"json\";\n\nexport type FieldDeclaration = {\n type: FieldType;\n required?: boolean;\n default?: string | number | boolean;\n /** date fields only. Renders as defaultNow() / CURRENT_TIMESTAMP. */\n defaultNow?: boolean;\n};\n\nexport type IndexDeclaration = {\n on: readonly string[];\n unique?: boolean;\n name?: string;\n};\n\nexport type TableDeclaration = {\n tableName: string;\n fields: Record<string, FieldDeclaration>;\n primaryKey?: readonly string[];\n indexes?: readonly IndexDeclaration[];\n};\n\nexport type SchemaDeclaration = Record<string, TableDeclaration>;\n\nexport type RouteScope =\n | { type: \"user\" }\n | { type: \"machine\" }\n | { type: \"signed\"; purpose: string }\n | { type: \"custom\"; justification: string };\n\nexport type RouteContext = {\n request: Request;\n /** Resolved for user-scoped routes, so a handler cannot forget to scope. */\n userId: string | null;\n /** Verified before dispatch, so a handler cannot forget to check. */\n claims: TokenClaims | null;\n params: Record<string, string>;\n};\n\nexport type RouteDefinition = {\n path: string;\n method: \"GET\" | \"POST\";\n scope: RouteScope;\n handler: (ctx: RouteContext) => Promise<Response>;\n};\n\n/** Handed to a plugin at startup so it need not be given the database twice. */\nexport type PluginInitContext = {\n /** Scoped to the tables this plugin declares in schema(). */\n store: PluginStore;\n /** Mints tokens for this plugin's own `signed` routes only. The secret itself is never handed out. */\n sign: (request: SignRequest) => Promise<string>;\n logger: Logger;\n /** Configured notification names, so a route can refuse to store rows for types that do not exist. */\n notificationTypes: readonly string[];\n /** The app's resolver, for plugins that need timezones or addresses. */\n getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;\n /** The instance's own send(), so a composed message inherits retry, backoff and idempotency. */\n send: (\n type: string,\n args: { to: string | readonly string[]; payload: unknown; dedupeKey?: string },\n ) => Promise<unknown>;\n};\n\nexport type EasyPingPlugin<\n TId extends string = string,\n TSchema extends SchemaDeclaration = SchemaDeclaration,\n> = {\n id: TId;\n dependsOn?: readonly string[];\n schema?: TSchema;\n routes?: readonly RouteDefinition[];\n hooks?: PluginHooks;\n /** Channels this plugin delivers. Makes them usable in a notification. */\n channels?: readonly Channel[];\n /** Called once by easyPing() before any hook or route can run. */\n init?: (ctx: PluginInitContext) => void;\n};\n\nexport type AnyPlugin = EasyPingPlugin<string, SchemaDeclaration>;\n\nexport function definePlugin<TId extends string, TSchema extends SchemaDeclaration>(\n plugin: EasyPingPlugin<TId, TSchema>,\n): EasyPingPlugin<TId, TSchema> {\n return plugin;\n}\n\nexport type ClientFetch = (path: string, init?: RequestInit) => Promise<unknown>;\n\nexport type ClientPlugin<\n TId extends string = string,\n TActions extends Record<string, unknown> = Record<string, unknown>,\n> = {\n id: TId;\n /** Phantom. Links client types to the server plugin so a mismatch is a type error. */\n $InferServerPlugin?: AnyPlugin;\n actions: (fetch: ClientFetch) => TActions;\n};\n\nexport type AnyClientPlugin = ClientPlugin<string, Record<string, unknown>>;\n\nexport function defineClientPlugin<TId extends string, TActions extends Record<string, unknown>>(\n plugin: ClientPlugin<TId, TActions>,\n): ClientPlugin<TId, TActions> {\n return plugin;\n}\n\nexport type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (\n k: infer I,\n) => void\n ? I\n : never;\n\n/** Naked type parameter, so the conditional distributes over the union. */\ntype ExtractActions<TPlugin> = TPlugin extends { actions: (fetch: never) => infer TActions }\n ? TActions\n : never;\n\n/** Indexes the tuple rather than recursing: a fold blows the instantiation depth limit. */\nexport type ActionsOf<TPlugins extends readonly AnyClientPlugin[]> = UnionToIntersection<\n ExtractActions<TPlugins[number]>\n>;\n","import { defineClientPlugin } from \"../../core/plugin\";\nimport type { Channel, Frequency } from \"../../core/types\";\nimport type { preferences } from \"./index\";\n\nexport type PreferenceView = {\n userId: string;\n type: string;\n channel: Channel;\n enabled: boolean;\n frequency: Frequency;\n};\n\nexport type UpdatePreferenceInput = {\n type: string;\n channel: Channel;\n enabled?: boolean;\n frequency?: Frequency;\n};\n\n/** Paired by phantom type: importing the server plugin's value would bundle the DB. */\nexport const preferencesClient = () =>\n defineClientPlugin({\n id: \"preferences\",\n $InferServerPlugin: {} as ReturnType<typeof preferences>,\n\n actions: (fetch) => ({\n listPreferences: async (): Promise<{\n preferences: PreferenceView[];\n defaultEnabled: boolean;\n }> =>\n (await fetch(\"/preferences\")) as {\n preferences: PreferenceView[];\n defaultEnabled: boolean;\n },\n\n updatePreference: async (input: UpdatePreferenceInput): Promise<{ ok: boolean }> =>\n (await fetch(\"/preferences\", {\n method: \"POST\",\n body: JSON.stringify(input),\n })) as { ok: boolean },\n }),\n });\n\nexport type PreferencesClient = ReturnType<typeof preferencesClient>;\n"]}
@@ -1,5 +1,5 @@
1
- import { f as ClientPlugin } from '../plugin-CiMsGlQe.cjs';
2
- import { C as Channel, F as Frequency } from '../adapter-BfLe2J0t.cjs';
1
+ import { f as ClientPlugin } from '../plugin-CHd2ZiGC.cjs';
2
+ import { C as Channel, F as Frequency } from '../adapter-D3lTy-4E.cjs';
3
3
 
4
4
  type PreferenceView = {
5
5
  userId: string;
@@ -1,5 +1,5 @@
1
- import { f as ClientPlugin } from '../plugin-C9Hoxus2.js';
2
- import { C as Channel, F as Frequency } from '../adapter-BfLe2J0t.js';
1
+ import { f as ClientPlugin } from '../plugin-Cg9usuUi.js';
2
+ import { C as Channel, F as Frequency } from '../adapter-D3lTy-4E.js';
3
3
 
4
4
  type PreferenceView = {
5
5
  userId: string;
@@ -1,4 +1,4 @@
1
- import { defineClientPlugin } from '../chunk-W6I3B2CI.js';
1
+ import { defineClientPlugin } from '../chunk-E4IZ2CQC.js';
2
2
 
3
3
  // src/plugins/preferences/client.ts
4
4
  var preferencesClient = () => defineClientPlugin({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/preferences/react.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { Channel, Frequency } from \"../../core/types\";\nimport type { PreferenceView, UpdatePreferenceInput } from \"./client\";\n\nexport type UsePreferencesOptions = {\n baseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n};\n\nexport type PreferenceKey = { type: string; channel: Channel };\n\nexport type UsePreferencesResult = {\n preferences: readonly PreferenceView[];\n defaultEnabled: boolean;\n isLoading: boolean;\n error: Error | null;\n /** Resolved value for a cell, falling back to the configured default. */\n isEnabled: (key: PreferenceKey) => boolean;\n setEnabled: (key: PreferenceKey, enabled: boolean) => Promise<void>;\n setFrequency: (key: PreferenceKey, frequency: Frequency) => Promise<void>;\n refresh: () => Promise<void>;\n};\n\nconst matches = (row: PreferenceView, key: PreferenceKey) =>\n row.type === key.type && row.channel === key.channel;\n\n/** Headless: state and persistence only, no markup. */\nexport function usePreferences(options: UsePreferencesOptions = {}): UsePreferencesResult {\n const { baseUrl = \"/api/notifications\", fetch: providedFetch } = options;\n\n const doFetch = useMemo(\n () =>\n providedFetch ??\n ((...args: Parameters<typeof globalThis.fetch>) => globalThis.fetch(...args)),\n [providedFetch],\n );\n\n const [preferences, setPreferences] = useState<readonly PreferenceView[]>([]);\n const [defaultEnabled, setDefaultEnabled] = useState(true);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const refresh = useCallback(async () => {\n try {\n const response = await doFetch(`${baseUrl}/preferences`);\n if (!response.ok) throw new Error(`GET /preferences failed: ${response.status}`);\n\n const body = (await response.json()) as {\n preferences: PreferenceView[];\n defaultEnabled: boolean;\n };\n\n setPreferences(body.preferences);\n setDefaultEnabled(body.defaultEnabled);\n setError(null);\n } catch (caught) {\n setError(caught instanceof Error ? caught : new Error(String(caught)));\n } finally {\n setIsLoading(false);\n }\n }, [baseUrl, doFetch]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const persist = useCallback(\n async (input: UpdatePreferenceInput, optimistic: Partial<PreferenceView>) => {\n const previous = preferences;\n\n // A preference toggle that lags behind the network feels broken, so\n // apply immediately and revert if the write fails.\n setPreferences((rows) => {\n const existing = rows.find((row) => matches(row, input));\n if (existing) {\n return rows.map((row) => (matches(row, input) ? { ...row, ...optimistic } : row));\n }\n return [\n ...rows,\n {\n userId: \"\",\n type: input.type,\n channel: input.channel,\n enabled: true,\n frequency: \"instant\" as Frequency,\n ...optimistic,\n },\n ];\n });\n\n try {\n const response = await doFetch(`${baseUrl}/preferences`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n if (!response.ok) throw new Error(`POST /preferences failed: ${response.status}`);\n } catch (caught) {\n setPreferences(previous);\n setError(caught instanceof Error ? caught : new Error(String(caught)));\n throw caught;\n }\n },\n [baseUrl, doFetch, preferences],\n );\n\n return {\n preferences,\n defaultEnabled,\n isLoading,\n error,\n\n isEnabled: useCallback(\n (key: PreferenceKey) => {\n const row = preferences.find((candidate) => matches(candidate, key));\n return row ? row.enabled && row.frequency !== \"off\" : defaultEnabled;\n },\n [preferences, defaultEnabled],\n ),\n\n setEnabled: useCallback(\n (key: PreferenceKey, enabled: boolean) =>\n persist(\n { ...key, enabled, frequency: enabled ? \"instant\" : \"off\" },\n { enabled, frequency: enabled ? \"instant\" : \"off\" },\n ),\n [persist],\n ),\n\n setFrequency: useCallback(\n (key: PreferenceKey, frequency: Frequency) =>\n persist(\n { ...key, enabled: frequency !== \"off\", frequency },\n { enabled: frequency !== \"off\", frequency },\n ),\n [persist],\n ),\n\n refresh,\n };\n}\n\nexport type { PreferenceView, UpdatePreferenceInput } from \"./client\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAA0D;AAuB1D,IAAM,UAAU,CAAC,KAAqB,QACpC,IAAI,SAAS,IAAI,QAAQ,IAAI,YAAY,IAAI;AAGxC,SAAS,eAAe,UAAiC,CAAC,GAAyB;AACxF,QAAM,EAAE,UAAU,sBAAsB,OAAO,cAAc,IAAI;AAEjE,QAAM,cAAU;AAAA,IACd,MACE,kBACC,IAAI,SAA8C,WAAW,MAAM,GAAG,IAAI;AAAA,IAC7E,CAAC,a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port { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { Channel, Frequency } from \"../../core/types\";\nimport type { PreferenceView, UpdatePreferenceInput } from \"./client\";\n\nexport type UsePreferencesOptions = {\n baseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n};\n\nexport type PreferenceKey = { type: string; channel: Channel };\n\nexport type UsePreferencesResult = {\n preferences: readonly PreferenceView[];\n defaultEnabled: boolean;\n isLoading: boolean;\n error: Error | null;\n /** Resolved value for a cell, falling back to the configured default. */\n isEnabled: (key: PreferenceKey) => boolean;\n setEnabled: (key: PreferenceKey, enabled: boolean) => Promise<void>;\n setFrequency: (key: PreferenceKey, frequency: Frequency) => Promise<void>;\n refresh: () => Promise<void>;\n};\n\nconst matches = (row: PreferenceView, key: PreferenceKey) =>\n row.type === key.type && row.channel === key.channel;\n\n/** Headless: state and persistence only, no markup. */\nexport function usePreferences(options: UsePreferencesOptions = {}): UsePreferencesResult {\n const { baseUrl = \"/api/notifications\", fetch: providedFetch } = options;\n\n const doFetch = useMemo(\n () =>\n providedFetch ??\n ((...args: Parameters<typeof globalThis.fetch>) => globalThis.fetch(...args)),\n [providedFetch],\n );\n\n const [preferences, setPreferences] = useState<readonly PreferenceView[]>([]);\n const [defaultEnabled, setDefaultEnabled] = useState(true);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const refresh = useCallback(async () => {\n try {\n const response = await doFetch(`${baseUrl}/preferences`);\n if (!response.ok) throw new Error(`GET /preferences failed: ${response.status}`);\n\n const body = (await response.json()) as {\n preferences: PreferenceView[];\n defaultEnabled: boolean;\n };\n\n setPreferences(body.preferences);\n setDefaultEnabled(body.defaultEnabled);\n setError(null);\n } catch (caught) {\n setError(caught instanceof Error ? caught : new Error(String(caught)));\n } finally {\n setIsLoading(false);\n }\n }, [baseUrl, doFetch]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const persist = useCallback(\n async (input: UpdatePreferenceInput, optimistic: Partial<PreferenceView>) => {\n const previous = preferences;\n\n // Optimistic: apply now, revert on failure.\n setPreferences((rows) => {\n const existing = rows.find((row) => matches(row, input));\n if (existing) {\n return rows.map((row) => (matches(row, input) ? { ...row, ...optimistic } : row));\n }\n return [\n ...rows,\n {\n userId: \"\",\n type: input.type,\n channel: input.channel,\n enabled: true,\n frequency: \"instant\" as Frequency,\n ...optimistic,\n },\n ];\n });\n\n try {\n const response = await doFetch(`${baseUrl}/preferences`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n if (!response.ok) throw new Error(`POST /preferences failed: ${response.status}`);\n } catch (caught) {\n setPreferences(previous);\n setError(caught instanceof Error ? caught : new Error(String(caught)));\n throw caught;\n }\n },\n [baseUrl, doFetch, preferences],\n );\n\n return {\n preferences,\n defaultEnabled,\n isLoading,\n error,\n\n isEnabled: useCallback(\n (key: PreferenceKey) => {\n const row = preferences.find((candidate) => matches(candidate, key));\n return row ? row.enabled && row.frequency !== \"off\" : defaultEnabled;\n },\n [preferences, defaultEnabled],\n ),\n\n setEnabled: useCallback(\n (key: PreferenceKey, enabled: boolean) =>\n persist(\n { ...key, enabled, frequency: enabled ? \"instant\" : \"off\" },\n { enabled, frequency: enabled ? \"instant\" : \"off\" },\n ),\n [persist],\n ),\n\n setFrequency: useCallback(\n (key: PreferenceKey, frequency: Frequency) =>\n persist(\n { ...key, enabled: frequency !== \"off\", frequency },\n { enabled: frequency !== \"off\", frequency },\n ),\n [persist],\n ),\n\n refresh,\n };\n}\n\nexport type { PreferenceView, UpdatePreferenceInput } from \"./client\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAA0D;AAuB1D,IAAM,UAAU,CAAC,KAAqB,QACpC,IAAI,SAAS,IAAI,QAAQ,IAAI,YAAY,IAAI;AAGxC,SAAS,eAAe,UAAiC,CAAC,GAAyB;AACxF,QAAM,EAAE,UAAU,sBAAsB,OAAO,cAAc,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IACV;AAAA,IAEA;AAAA,EACF;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/preferences/react.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { Channel, Frequency } from \"../../core/types\";\nimport type { PreferenceView, UpdatePreferenceInput } from \"./client\";\n\nexport type UsePreferencesOptions = {\n baseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n};\n\nexport type PreferenceKey = { type: string; channel: Channel };\n\nexport type UsePreferencesResult = {\n preferences: readonly PreferenceView[];\n defaultEnabled: boolean;\n isLoading: boolean;\n error: Error | null;\n /** Resolved value for a cell, falling back to the configured default. */\n isEnabled: (key: PreferenceKey) => boolean;\n setEnabled: (key: PreferenceKey, enabled: boolean) => Promise<void>;\n setFrequency: (key: PreferenceKey, frequency: Frequency) => Promise<void>;\n refresh: () => Promise<void>;\n};\n\nconst matches = (row: PreferenceView, key: PreferenceKey) =>\n row.type === key.type && row.channel === key.channel;\n\n/** Headless: state and persistence only, no markup. */\nexport function usePreferences(options: UsePreferencesOptions = {}): UsePreferencesResult {\n const { baseUrl = \"/api/notifications\", fetch: providedFetch } = options;\n\n const doFetch = useMemo(\n () =>\n providedFetch ??\n ((...args: Parameters<typeof globalThis.fetch>) => globalThis.fetch(...args)),\n [providedFetch],\n );\n\n const [preferences, setPreferences] = useState<readonly PreferenceView[]>([]);\n const [defaultEnabled, setDefaultEnabled] = useState(true);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const refresh = useCallback(async () => {\n try {\n const response = await doFetch(`${baseUrl}/preferences`);\n if (!response.ok) throw new Error(`GET /preferences failed: ${response.status}`);\n\n const body = (await response.json()) as {\n preferences: PreferenceView[];\n defaultEnabled: boolean;\n };\n\n setPreferences(body.preferences);\n setDefaultEnabled(body.defaultEnabled);\n setError(null);\n } catch (caught) {\n setError(caught instanceof Error ? caught : new Error(String(caught)));\n } finally {\n setIsLoading(false);\n }\n }, [baseUrl, doFetch]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const persist = useCallback(\n async (input: UpdatePreferenceInput, optimistic: Partial<PreferenceView>) => {\n const previous = preferences;\n\n // A preference toggle that lags behind the network feels broken, so\n // apply immediately and revert if the write fails.\n setPreferences((rows) => {\n const existing = rows.find((row) => matches(row, input));\n if (existing) {\n return rows.map((row) => (matches(row, input) ? { ...row, ...optimistic } : row));\n }\n return [\n ...rows,\n {\n userId: \"\",\n type: input.type,\n channel: input.channel,\n enabled: true,\n frequency: \"instant\" as Frequency,\n ...optimistic,\n },\n ];\n });\n\n try {\n const response = await doFetch(`${baseUrl}/preferences`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n if (!response.ok) throw new Error(`POST /preferences failed: ${response.status}`);\n } catch (caught) {\n setPreferences(previous);\n setError(caught instanceof Error ? caught : new Error(String(caught)));\n throw caught;\n }\n },\n [baseUrl, doFetch, preferences],\n );\n\n return {\n preferences,\n defaultEnabled,\n isLoading,\n error,\n\n isEnabled: useCallback(\n (key: PreferenceKey) => {\n const row = preferences.find((candidate) => matches(candidate, key));\n return row ? row.enabled && row.frequency !== \"off\" : defaultEnabled;\n },\n [preferences, defaultEnabled],\n ),\n\n setEnabled: useCallback(\n (key: PreferenceKey, enabled: boolean) =>\n persist(\n { ...key, enabled, frequency: enabled ? \"instant\" : \"off\" },\n { enabled, frequency: enabled ? \"instant\" : \"off\" },\n ),\n [persist],\n ),\n\n setFrequency: useCallback(\n (key: PreferenceKey, frequency: Frequency) =>\n persist(\n { ...key, enabled: frequency !== \"off\", frequency },\n { enabled: frequency !== \"off\", frequency },\n ),\n [persist],\n ),\n\n refresh,\n };\n}\n\nexport type { PreferenceView, UpdatePreferenceInput } from \"./client\";\n"],"mappings":";;;;AAEA,SAAS,aAAa,WAAW,SAAS,gBAAgB;AAuB1D,IAAM,UAAU,CAAC,KAAqB,QACpC,IAAI,SAAS,I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S,cAAc,OAAO,UAAU;AAAA,QAClD,EAAE,SAAS,cAAc,OAAO,UAAU;AAAA,MAC5C;AAAA,MACF,CAAC,OAAO;AAAA,IACV;AAAA,IAEA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/plugins/preferences/react.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { Channel, Frequency } from \"../../core/types\";\nimport type { PreferenceView, UpdatePreferenceInput } from \"./client\";\n\nexport type UsePreferencesOptions = {\n baseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n};\n\nexport type PreferenceKey = { type: string; channel: Channel };\n\nexport type UsePreferencesResult = {\n preferences: readonly PreferenceView[];\n defaultEnabled: boolean;\n isLoading: boolean;\n error: Error | null;\n /** Resolved value for a cell, falling back to the configured default. */\n isEnabled: (key: PreferenceKey) => boolean;\n setEnabled: (key: PreferenceKey, enabled: boolean) => Promise<void>;\n setFrequency: (key: PreferenceKey, frequency: Frequency) => Promise<void>;\n refresh: () => Promise<void>;\n};\n\nconst matches = (row: PreferenceView, key: PreferenceKey) =>\n row.type === key.type && row.channel === key.channel;\n\n/** Headless: state and persistence only, no markup. */\nexport function usePreferences(options: UsePreferencesOptions = {}): UsePreferencesResult {\n const { baseUrl = \"/api/notifications\", fetch: providedFetch } = options;\n\n const doFetch = useMemo(\n () =>\n providedFetch ??\n ((...args: Parameters<typeof globalThis.fetch>) => globalThis.fetch(...args)),\n [providedFetch],\n );\n\n const [preferences, setPreferences] = useState<readonly PreferenceView[]>([]);\n const [defaultEnabled, setDefaultEnabled] = useState(true);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n const refresh = useCallback(async () => {\n try {\n const response = await doFetch(`${baseUrl}/preferences`);\n if (!response.ok) throw new Error(`GET /preferences failed: ${response.status}`);\n\n const body = (await response.json()) as {\n preferences: PreferenceView[];\n defaultEnabled: boolean;\n };\n\n setPreferences(body.preferences);\n setDefaultEnabled(body.defaultEnabled);\n setError(null);\n } catch (caught) {\n setError(caught instanceof Error ? caught : new Error(String(caught)));\n } finally {\n setIsLoading(false);\n }\n }, [baseUrl, doFetch]);\n\n useEffect(() => {\n void refresh();\n }, [refresh]);\n\n const persist = useCallback(\n async (input: UpdatePreferenceInput, optimistic: Partial<PreferenceView>) => {\n const previous = preferences;\n\n // Optimistic: apply now, revert on failure.\n setPreferences((rows) => {\n const existing = rows.find((row) => matches(row, input));\n if (existing) {\n return rows.map((row) => (matches(row, input) ? { ...row, ...optimistic } : row));\n }\n return [\n ...rows,\n {\n userId: \"\",\n type: input.type,\n channel: input.channel,\n enabled: true,\n frequency: \"instant\" as Frequency,\n ...optimistic,\n },\n ];\n });\n\n try {\n const response = await doFetch(`${baseUrl}/preferences`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(input),\n });\n if (!response.ok) throw new Error(`POST /preferences failed: ${response.status}`);\n } catch (caught) {\n setPreferences(previous);\n setError(caught instanceof Error ? caught : new Error(String(caught)));\n throw caught;\n }\n },\n [baseUrl, doFetch, preferences],\n );\n\n return {\n preferences,\n defaultEnabled,\n isLoading,\n error,\n\n isEnabled: useCallback(\n (key: PreferenceKey) => {\n const row = preferences.find((candidate) => matches(candidate, key));\n return row ? row.enabled && row.frequency !== \"off\" : defaultEnabled;\n },\n [preferences, defaultEnabled],\n ),\n\n setEnabled: useCallback(\n (key: PreferenceKey, enabled: boolean) =>\n persist(\n { ...key, enabled, frequency: enabled ? \"instant\" : \"off\" },\n { enabled, frequency: enabled ? \"instant\" : \"off\" },\n ),\n [persist],\n ),\n\n setFrequency: useCallback(\n (key: PreferenceKey, frequency: Frequency) =>\n persist(\n { ...key, enabled: frequency !== \"off\", frequency },\n { enabled: frequency !== \"off\", frequency },\n ),\n [persist],\n ),\n\n refresh,\n };\n}\n\nexport type { PreferenceView, UpdatePreferenceInput } from \"./client\";\n"],"mappings":";;;;AAEA,SAAS,aAAa,WAAW,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Ac;AAAA,MACZ,CAAC,KAAoB,cACnB;AAAA,QACE,EAAE,GAAG,KAAK,SAAS,cAAc,OAAO,UAAU;AAAA,QAClD,EAAE,SAAS,cAAc,OAAO,UAAU;AAAA,MAC5C;AAAA,MACF,CAAC,OAAO;AAAA,IACV;AAAA,IAEA;AAAA,EACF;AACF;","names":[]}
@@ -189,8 +189,7 @@ function preferences(options = {}) {
189
189
  }
190
190
  },
191
191
  {
192
- // Reached from a mail client with no session, so it is authenticated
193
- // by the signature on the link itself.
192
+ // No session in a mail client; the link carries the proof.
194
193
  path: "/unsubscribe",
195
194
  method: "POST",
196
195
  scope: { type: "signed", purpose: UNSUBSCRIBE_PURPOSE },
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/base64url.ts","../../src/core/tokens.ts","../../src/core/handler.ts","../../src/plugins/preferences/index.ts"],"names":[],"mappings":";;;AAEO,SAAS,gBAAgB,KAAA,EAAoC;AAClE,EAAA,MAAM,KAAA,GAAQ,OAAO,KAAA,KAAU,QAAA,GAAW,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,KAAK,CAAA,GAAI,KAAA;AAC5E,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,EAAO,MAAA,IAAU,MAAA,CAAO,aAAa,IAAI,CAAA;AAC5D,EAAA,OAAO,IAAA,CAAK,MAAM,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/E;;;ACQA,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAGhC,IAAM,QAAA,GAAW,OAAA,CAAQ,MAAA,CAAO,qBAAqB,CAAA;AAOrD,eAAe,OAAA,CAAQ,QAAgB,OAAA,EAAqC;AAC1E,EAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO,MAAA,CAAO,SAAA,CAAU,KAA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AAQ;AAAA,YACpC,EAAE,OAAO,CAAA;AAAE,WACb;AAGA,UAAA,IAAI,WAAW,CAAC,OAAA,CAAQ,OAAA,IAAW,OAAA,CAAQ,cAAc,KAAA,EAAO;AAC9D,YAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,IAAA,EAAM,cAAc,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG,CAAA;AAAA,UACpE;AAIA,UAAA,IACE,OAAA,EAAS,SAAA,IACT,MAAA,CAAO,GAAA,KAAQ,MAAA,IACf,OAAA,CAAQ,SAAA,CAAU,OAAA,EAAQ,GAAA,CAAK,MAAA,CAAO,GAAA,GAAM,CAAA,IAAK,GAAA,EACjD;AACA,YAAA,OAAO,QAAA,CAAS,KAAK,EAAE,KAAA,EAAO,iBAAgB,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,UAClE;AAEA,UAAA,MAAM,IAAA,CAAK;AAAA,YACT,QAAQ,MAAA,CAAO,GAAA;AAAA,YACf,IAAA;AAAA,YACA,OAAA;AAAA,YACA,OAAA,EAAS,KAAA;AAAA,YACT,SAAA,EAAW;AAAA,WACZ,CAAA;AAID,UAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,IAAA,EAAM,cAAc,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG,CAAA;AAAA,QACpE;AAAA;AACF;AACF,GACF;AACF","file":"preferences.cjs","sourcesContent":["// Web APIs, not Buffer: this runs on Workers and Vercel Edge.\n\nexport function encodeBase64Url(input: string | Uint8Array): string {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n// Uint8Array<ArrayBuffer>: bare Uint8Array widens and is not a BufferSource.\nexport function decodeBase64UrlBytes(value: string): Uint8Array<ArrayBuffer> | null {\n try {\n const binary = atob(value.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\nexport function decodeBase64Url(value: string): string | null {\n const bytes = decodeBase64UrlBytes(value);\n return bytes ? new TextDecoder().decode(bytes) : null;\n}\n","import { decodeBase64Url, decodeBase64UrlBytes, encodeBase64Url } from \"./base64url\";\n\nexport type TokenClaims = {\n /** Subject — the user the token acts for. */\n uid: string;\n /** What the token is allowed to do. Verification requires an exact match. */\n purpose: string;\n /** Expiry, epoch seconds. */\n exp: number;\n /** Issued at, epoch seconds. Set by signToken; lets a route refuse a token older than a later change. */\n iat?: number;\n /** Free-form, purpose-specific. */\n data?: Record<string, string>;\n};\n\nconst encoder = new TextEncoder();\n\n// Changing this invalidates every outstanding token. Bump it on purpose only.\nconst KEY_SALT = encoder.encode(\"easy-ping/tokens/v1\");\n\n/**\n * One HMAC key per purpose, derived from the master secret with HKDF. A key\n * that can sign unsubscribe links cannot sign anything else, so a plugin\n * handed the unsubscribe key gets exactly that and no more.\n */\nasync function hmacKey(secret: string, purpose: string): Promise<CryptoKey> {\n const master = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), \"HKDF\", false, [\n \"deriveKey\",\n ]);\n return crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: KEY_SALT, info: encoder.encode(purpose) },\n master,\n { name: \"HMAC\", hash: \"SHA-256\", length: 256 },\n false,\n [\"sign\", \"verify\"],\n );\n}\n\nexport async function signToken(\n secret: string,\n claims: TokenClaims,\n now: Date = new Date(),\n): Promise<string> {\n const stamped: TokenClaims = { ...claims, iat: claims.iat ?? Math.floor(now.getTime() / 1000) };\n const body = encodeBase64Url(JSON.stringify(stamped));\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n await hmacKey(secret, claims.purpose),\n encoder.encode(body),\n );\n return `${body}.${encodeBase64Url(new Uint8Array(signature))}`;\n}\n\n/** null for every failure mode. Distinguishing them tells an attacker which part to fix. */\nexport async function verifyToken(\n secret: string,\n token: string,\n purpose: string,\n now: Date = new Date(),\n): Promise<TokenClaims | null> {\n const separator = token.lastIndexOf(\".\");\n if (separator <= 0) return null;\n\n const body = token.slice(0, separator);\n const signature = decodeBase64UrlBytes(token.slice(separator + 1));\n if (!signature) return null;\n\n // Verified under the key for the purpose this route expects, before the\n // body is even parsed. A token minted for another purpose fails here.\n // crypto.subtle.verify is constant-time.\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n await hmacKey(secret, purpose),\n signature,\n encoder.encode(body),\n );\n if (!valid) return null;\n\n const decoded = decodeBase64Url(body);\n if (!decoded) return null;\n\n let claims: TokenClaims;\n try {\n claims = JSON.parse(decoded) as TokenClaims;\n } catch {\n return null;\n }\n\n if (typeof claims?.uid !== \"string\" || typeof claims.exp !== \"number\") return null;\n if (claims.purpose !== purpose) return null;\n if (claims.exp * 1000 <= now.getTime()) return null;\n if (claims.iat !== undefined && typeof claims.iat !== \"number\") return null;\n\n if (claims.data !== undefined) {\n if (typeof claims.data !== \"object\" || claims.data === null || Array.isArray(claims.data)) {\n return null;\n }\n for (const value of Object.values(claims.data)) {\n if (typeof value !== \"string\") return null;\n }\n }\n\n return claims;\n}\n\nexport const DEFAULT_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;\n/** Ninety days. A link that must outlive this should be re-issued, not made immortal. */\nexport const MAX_TOKEN_TTL_SECONDS = 90 * 24 * 60 * 60;\n\nexport const expiresIn = (seconds: number, now: Date = new Date()): number =>\n Math.floor(now.getTime() / 1000) + Math.min(Math.max(seconds, 0), MAX_TOKEN_TTL_SECONDS);\n\nexport type SignRequest = {\n uid: string;\n purpose: string;\n data?: Record<string, string>;\n /** Defaults to 30 days, capped at 90. */\n ttlSeconds?: number;\n};\n\n/**\n * What a plugin gets instead of the secret: a signer that only mints tokens\n * for the purposes its own `signed` routes declared.\n */\nexport function createScopedSigner(\n secret: string,\n pluginId: string,\n purposes: ReadonlySet<string>,\n onViolation: (message: string) => Error,\n): (request: SignRequest) => Promise<string> {\n return (request) => {\n if (!purposes.has(request.purpose)) {\n throw onViolation(\n `plugin \"${pluginId}\" tried to sign a token for purpose \"${request.purpose}\", ` +\n \"which none of its signed routes declare.\",\n );\n }\n return signToken(secret, {\n uid: request.uid,\n purpose: request.purpose,\n exp: expiresIn(request.ttlSeconds ?? DEFAULT_TOKEN_TTL_SECONDS),\n ...(request.data ? { data: request.data } : {}),\n });\n };\n}\n","import type { DatabaseAdapter } from \"./adapter\";\nimport type { SessionConfig } from \"./config\";\nimport type { Logger } from \"./errors\";\nimport type { Promisable, RouteDefinition } from \"./plugin\";\nimport type { Runner } from \"./runner\";\nimport { verifyToken } from \"./tokens\";\n\nexport type HandlerDeps = {\n adapter: DatabaseAdapter;\n session: SessionConfig;\n runner: Runner;\n logger: Logger;\n basePath: string;\n secret: string;\n cronSecret?: string | undefined;\n /** Guards plugin machine routes. The instance defaults it to cronSecret. */\n machineSecret?: string | undefined;\n cronMaxSweeps?: number | undefined;\n pluginRoutes?: readonly RouteDefinition[] | undefined;\n /** Returns a 429 to send, or null to proceed. Runs after onRequest, before routing. */\n rateLimit?: ((request: Request) => Response | null) | undefined;\n /** Origins other than the request's own host that may POST. `*.example.com` allowed. */\n trustedOrigins?: readonly string[] | undefined;\n /** Runs before routing. Returning a Response short-circuits; use it for rate limiting. */\n // biome-ignore lint/suspicious/noConfusingVoidType: a hook that returns nothing is the common case\n onRequest?: ((request: Request) => Promisable<Response | undefined | void>) | undefined;\n maxBodyBytes?: number | undefined;\n};\n\n/** Every JSON body is capped here. Nothing legitimate the routes accept is bigger. */\nexport const MAX_BODY_BYTES = 64 * 1024;\n\nconst MAX_READ_IDS = 200;\n\n// The inbox is per-user data: never let a shared cache keep it, never let a\n// browser sniff it into something executable.\nconst PRIVATE_HEADERS: Record<string, string> = {\n \"cache-control\": \"private, no-store\",\n \"x-content-type-options\": \"nosniff\",\n};\n\nconst json = (body: unknown, status = 200) =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\", ...PRIVATE_HEADERS },\n });\n\nconst empty = (status: number) => new Response(null, { status, headers: PRIVATE_HEADERS });\n\n/** Plugin responses get the same headers, without touching their body. */\nfunction harden(response: Response): Response {\n const headers = new Headers(response.headers);\n for (const [name, value] of Object.entries(PRIVATE_HEADERS)) {\n if (!headers.has(name)) headers.set(name, value);\n }\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * Constant-time comparison over SHA-256 digests. Node's timingSafeEqual is\n * unavailable on edge runtimes, `===` leaks through timing, and comparing the\n * raw strings would still reveal the secret's length.\n */\nasync function timingSafeEqual(a: string, b: string): Promise<boolean> {\n const [left, right] = await Promise.all(\n [a, b].map(\n async (value) => new Uint8Array(await crypto.subtle.digest(\"SHA-256\", encoder.encode(value))),\n ),\n );\n let diff = 0;\n for (let i = 0; i < 32; i += 1) diff |= (left?.[i] ?? 0) ^ (right?.[i] ?? 0);\n return diff === 0;\n}\n\n/** Anchored at a segment boundary: `/foo/api/notifications/cron` is not a cron request. */\nfunction routePath(url: URL, basePath: string): string {\n const { pathname } = url;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(`${basePath}/`)) return pathname.slice(basePath.length);\n return pathname;\n}\n\nexport type JsonBody = { body: Record<string, unknown> } | { error: Response };\n\n/**\n * Reads a JSON object body with a byte cap enforced while streaming, so an\n * oversized body is refused before it is buffered. Malformed JSON is 400; an\n * empty body is `{}`. Plugin routes should use this rather than\n * `request.json()`, which has no limit.\n */\nexport async function readJsonBody(\n request: Request,\n maxBytes: number = MAX_BODY_BYTES,\n): Promise<JsonBody> {\n const tooLarge = () => ({ error: json({ error: `body exceeds ${maxBytes} bytes` }, 413) });\n\n const declared = Number(request.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > maxBytes) return tooLarge();\n if (!request.body) return { body: {} };\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n return tooLarge();\n }\n chunks.push(value);\n }\n\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n const text = new TextDecoder().decode(bytes);\n if (text.trim() === \"\") return { body: {} };\n\n try {\n const parsed: unknown = JSON.parse(text);\n return {\n body:\n parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {},\n };\n } catch {\n return { error: json({ error: \"body must be a JSON object\" }, 400) };\n }\n}\n\nconst isJsonContentType = (request: Request) =>\n /^application\\/json\\s*(;|$)/i.test((request.headers.get(\"content-type\") ?? \"\").trim());\n\nfunction originAllowed(origin: string, url: URL, request: Request, trusted: readonly string[]) {\n let host: string;\n try {\n host = new URL(origin).host;\n } catch {\n return false;\n }\n\n if (host === url.host) return true;\n // Behind a proxy that rewrites Host, the public host arrives here instead.\n const forwarded = request.headers.get(\"x-forwarded-host\")?.split(\",\")[0]?.trim();\n if (forwarded && host === forwarded) return true;\n\n return trusted.some((entry) =>\n entry.startsWith(\"*.\") ? host.endsWith(entry.slice(1)) : entry === origin,\n );\n}\n\n/**\n * Two cheap CSRF defences for cookie-authenticated POSTs. A cross-site form\n * cannot send `application/json` without a preflight the browser will fail,\n * and it cannot forge `Origin`. Neither depends on the host app's SameSite\n * policy, which the library cannot see.\n */\nfunction csrfCheck(request: Request, url: URL, trusted: readonly string[]): Response | null {\n if (!isJsonContentType(request)) {\n return json({ error: \"content-type must be application/json\" }, 415);\n }\n\n const origin = request.headers.get(\"origin\");\n if (origin === null) return null;\n if (origin === \"null\" || !originAllowed(origin, url, request, trusted)) return empty(403);\n\n return null;\n}\n\nexport function createHandler(deps: HandlerDeps) {\n const trustedOrigins = deps.trustedOrigins ?? [];\n const maxBodyBytes = deps.maxBodyBytes ?? MAX_BODY_BYTES;\n\n async function resolveUserId(request: Request): Promise<string | null | \"error\"> {\n try {\n return await deps.session.getUserId(request);\n } catch (error) {\n // A broken session lookup is a 500, never a 401. Collapsing them makes\n // an outage look like a mass logout. RFC 0002 §1.\n deps.logger.error(\"session.getUserId threw\", { error });\n return \"error\";\n }\n }\n\n async function bearerMatches(request: Request, secret: string | undefined): Promise<boolean> {\n if (!secret) return false;\n const header = request.headers.get(\"authorization\") ?? \"\";\n const presented = header.startsWith(\"Bearer \") ? header.slice(7) : header;\n return timingSafeEqual(presented, secret);\n }\n\n async function handleCron(request: Request): Promise<Response> {\n if (!deps.cronSecret) return empty(404);\n if (!(await bearerMatches(request, deps.cronSecret))) return empty(401);\n\n // Bounded: an overlapping scheduler must not hold a request open for as\n // long as the backlog lasts.\n const result = await deps.runner.drain(\n deps.cronMaxSweeps === undefined ? {} : { maxSweeps: deps.cronMaxSweeps },\n );\n return json(result);\n }\n\n /**\n * Plugin routes are dispatched before core ones and carry their scope with\n * them. Authentication happens here rather than in the plugin handler, so a\n * plugin physically cannot forget to check a signature or scope a query.\n */\n async function handlePluginRoute(\n route: RouteDefinition,\n request: Request,\n url: URL,\n ): Promise<Response> {\n if (route.scope.type === \"user\") {\n if (request.method === \"POST\") {\n const rejected = csrfCheck(request, url, trustedOrigins);\n if (rejected) return rejected;\n }\n\n const userId = await resolveUserId(request);\n if (userId === \"error\") return empty(500);\n if (userId === null) return empty(401);\n return harden(await route.handler({ request, userId, claims: null, params: {} }));\n }\n\n if (route.scope.type === \"machine\") {\n if (!deps.machineSecret) return empty(404);\n if (!(await bearerMatches(request, deps.machineSecret))) return empty(401);\n return harden(await route.handler({ request, userId: null, claims: null, params: {} }));\n }\n\n if (route.scope.type === \"signed\") {\n const token =\n url.searchParams.get(\"token\") ??\n (request.headers.get(\"authorization\") ?? \"\").replace(/^Bearer /, \"\");\n\n const claims = await verifyToken(deps.secret, token, route.scope.purpose);\n // One response for every failure mode. Distinguishing expired from\n // forged tells an attacker which part to fix. RFC 0002 §5.\n if (!claims) return empty(400);\n\n return harden(await route.handler({ request, userId: claims.uid, claims, params: {} }));\n }\n\n return harden(await route.handler({ request, userId: null, claims: null, params: {} }));\n }\n\n async function route(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const path = routePath(url, deps.basePath);\n\n if (deps.onRequest) {\n const early = await deps.onRequest(request);\n if (early instanceof Response) return early;\n }\n\n if (deps.rateLimit) {\n const limited = deps.rateLimit(request);\n if (limited) return limited;\n }\n\n if (path === \"/cron\") {\n if (request.method !== \"POST\") return empty(405);\n return handleCron(request);\n }\n\n const pluginRoute = deps.pluginRoutes?.find(\n (candidate) => candidate.path === path && candidate.method === request.method,\n );\n if (pluginRoute) return handlePluginRoute(pluginRoute, request, url);\n\n if (request.method === \"POST\") {\n const rejected = csrfCheck(request, url, trustedOrigins);\n if (rejected) return rejected;\n }\n\n const userId = await resolveUserId(request);\n if (userId === \"error\") return empty(500);\n if (userId === null) return empty(401);\n\n if (request.method === \"GET\" && path === \"/\") {\n const limitParam = Number(url.searchParams.get(\"limit\") ?? 20);\n const limit = Number.isFinite(limitParam) ? Math.min(Math.max(limitParam, 1), 100) : 20;\n const cursor = url.searchParams.get(\"cursor\");\n\n // The badge count rides along with the first page, so a polling client\n // needs one request per tick instead of two. Paginating past the first\n // page omits it: a cursor request is scrollback, not a poll.\n const [page, unseenCount] = await Promise.all([\n deps.adapter.listNotifications({\n userId,\n limit,\n ...(cursor ? { cursor } : {}),\n ...(url.searchParams.get(\"unreadOnly\") === \"true\" ? { unreadOnly: true } : {}),\n }),\n cursor ? Promise.resolve(null) : deps.adapter.countUnseen(userId),\n ]);\n\n return json(unseenCount === null ? page : { ...page, unseenCount });\n }\n\n if (request.method === \"GET\" && path === \"/count\") {\n return json({ unseen: await deps.adapter.countUnseen(userId) });\n }\n\n if (request.method === \"POST\" && path === \"/seen\") {\n const parsed = await readJsonBody(request, maxBodyBytes);\n if (\"error\" in parsed) return parsed.error;\n const before = typeof parsed.body.before === \"string\" ? new Date(parsed.body.before) : null;\n\n // Defaults to now, but a client should send the timestamp of the newest\n // notification it has actually rendered. Otherwise anything that arrived\n // between the last poll and the click is marked seen without ever having\n // produced a badge — the user silently misses it.\n //\n // +1ms because Postgres keeps microseconds while an ISO string carries\n // only milliseconds. Without it the truncated cutoff falls *before* the\n // very row it was taken from, and markSeen matches nothing at all.\n const cutoff =\n before && !Number.isNaN(before.getTime()) ? new Date(before.getTime() + 1) : new Date();\n\n await deps.adapter.markSeen(userId, cutoff);\n return json({ ok: true });\n }\n\n if (request.method === \"POST\" && path === \"/read\") {\n const parsed = await readJsonBody(request, maxBodyBytes);\n if (\"error\" in parsed) return parsed.error;\n const ids = Array.isArray(parsed.body.ids)\n ? parsed.body.ids.filter((id): id is string => typeof id === \"string\")\n : [];\n if (ids.length === 0) return json({ error: \"ids must be a non-empty string array\" }, 400);\n\n // Unbounded, this builds a query with as many bind parameters as the\n // caller cares to send. Postgres caps at 65535 and degrades long before.\n if (ids.length > MAX_READ_IDS) {\n return json({ error: `at most ${MAX_READ_IDS} ids per request` }, 400);\n }\n\n // Scoped by userId in the adapter. A miss is 404, not 403 — a 403 would\n // confirm the row exists and belongs to someone else. RFC 0002 §2.\n const updated = await deps.adapter.markRead(userId, ids);\n return updated === 0 ? empty(404) : json({ updated });\n }\n\n if (request.method === \"POST\" && path === \"/read-all\") {\n return json({ updated: await deps.adapter.markAllRead(userId) });\n }\n\n return empty(404);\n }\n\n async function handle(request: Request): Promise<Response> {\n try {\n return await route(request);\n } catch (error) {\n // Never let a driver error escape: on Node it becomes an unhandled\n // rejection, on other hosts a stack trace in the response body.\n deps.logger.error(\"request failed\", { url: request.url, error });\n return empty(500);\n }\n }\n\n return {\n handle,\n GET: handle,\n POST: handle,\n };\n}\n","import { readJsonBody } from \"../../core/handler\";\nimport type {\n ChannelDecision,\n EasyPingPlugin,\n PluginInitContext,\n PrepareContext,\n ResolveChannelsContext,\n} from \"../../core/plugin\";\nimport { DEFAULT_TOKEN_TTL_SECONDS, expiresIn, signToken } from \"../../core/tokens\";\nimport type { Channel, Frequency } from \"../../core/types\";\n\nexport const UNSUBSCRIBE_PURPOSE = \"unsubscribe\";\n\nconst TABLE = \"notification_preference\";\n\nconst CHANNELS: readonly Channel[] = [\"inApp\", \"email\", \"push\", \"sms\", \"slack\"];\nconst FREQUENCIES: readonly Frequency[] = [\"instant\", \"daily\", \"weekly\", \"off\"];\n\nconst isChannel = (value: unknown): value is Channel => CHANNELS.includes(value as Channel);\nconst isFrequency = (value: unknown): value is Frequency =>\n FREQUENCIES.includes(value as Frequency);\n\nexport type PreferenceRow = {\n userId: string;\n type: string;\n channel: Channel;\n enabled: boolean;\n frequency: Frequency;\n /** Last explicit change. An unsubscribe token issued before it is refused. */\n updatedAt?: Date;\n};\n\nexport type PreferencesOptions = {\n /** What an absent row means. Flip to false for opt-in-only notifications. */\n defaultEnabled?: boolean;\n /** Types that ignore preferences entirely: receipts, security alerts. */\n alwaysSend?: readonly string[];\n unsubscribeTtlSeconds?: number;\n};\n\nconst key = (userId: string, type: string, channel: string) => `${userId} ${type} ${channel}`;\n\ntype PreparedPreferences = Map<string, PreferenceRow>;\n\nexport function buildUnsubscribeToken(\n secret: string,\n userId: string,\n type: string,\n channel: Channel,\n ttlSeconds = DEFAULT_TOKEN_TTL_SECONDS,\n): Promise<string> {\n return signToken(secret, {\n uid: userId,\n purpose: UNSUBSCRIBE_PURPOSE,\n exp: expiresIn(ttlSeconds),\n data: { type, channel },\n });\n}\n\nexport function preferences(options: PreferencesOptions = {}): EasyPingPlugin<\"preferences\"> {\n const defaultEnabled = options.defaultEnabled ?? true;\n const alwaysSend = new Set(options.alwaysSend ?? []);\n\n // Assigned by init(), which easyPing() runs before any hook or route.\n let ctx: PluginInitContext;\n\n const isAllowed = (userId: string, type: string, channel: Channel, rows: PreparedPreferences) => {\n const row = rows.get(key(userId, type, channel));\n return row ? row.enabled && row.frequency !== \"off\" : defaultEnabled;\n };\n\n const load = (userIds: readonly string[]) =>\n ctx.store.find<PreferenceRow>(TABLE, { userId: { in: [...userIds] } });\n\n const save = (row: PreferenceRow) =>\n ctx.store.upsert(TABLE, [{ ...row, updatedAt: new Date() }], {\n onConflict: [\"userId\", \"type\", \"channel\"],\n });\n\n return {\n id: \"preferences\",\n\n init: (context) => {\n ctx = context;\n },\n\n schema: {\n notificationPreference: {\n tableName: TABLE,\n fields: {\n userId: { type: \"string\", required: true },\n type: { type: \"string\", required: true },\n channel: { type: \"string\", required: true },\n enabled: { type: \"boolean\", required: true, default: true },\n frequency: { type: \"string\", required: true, default: \"instant\" },\n updatedAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"userId\", \"type\", \"channel\"],\n },\n },\n\n hooks: {\n /** One query per send; doing this per recipient would be an N+1. */\n prepare: async (context: PrepareContext): Promise<PreparedPreferences> => {\n if (alwaysSend.has(context.type)) return new Map();\n\n const rows = await load(context.recipients.map((recipient) => recipient.userId));\n return new Map(rows.map((row) => [key(row.userId, row.type, row.channel), row]));\n },\n\n resolveChannels: (context: ResolveChannelsContext) => {\n if (alwaysSend.has(context.type)) return context.decisions;\n\n // prepare() failing leaves this undefined. Fail closed rather than\n // assuming everyone opted in: that is exactly how people who\n // unsubscribed get emailed anyway.\n if (!(context.prepared instanceof Map)) {\n return context.decisions.map((decision) => ({ ...decision, action: \"skip\" as const }));\n }\n\n const rows = context.prepared as PreparedPreferences;\n\n return context.decisions.map<ChannelDecision>((decision) =>\n isAllowed(context.recipient.userId, context.type, decision.channel, rows)\n ? decision\n : { ...decision, action: \"skip\" },\n );\n },\n },\n\n routes: [\n {\n path: \"/preferences\",\n method: \"GET\",\n scope: { type: \"user\" },\n handler: async ({ userId }) => {\n const rows = await load([userId ?? \"\"]);\n return Response.json({ preferences: rows, defaultEnabled });\n },\n },\n\n {\n path: \"/preferences\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const parsed = await readJsonBody(request);\n if (\"error\" in parsed) return parsed.error;\n const body = parsed.body;\n\n const bad = (error: string) => Response.json({ error }, { status: 400 });\n\n // Only types the app defined: otherwise every unknown string the\n // client invents is a row that lives forever.\n if (typeof body.type !== \"string\" || !ctx.notificationTypes.includes(body.type)) {\n return bad(\"type must be a configured notification type\");\n }\n if (!isChannel(body.channel)) return bad(`channel must be one of ${CHANNELS.join(\", \")}`);\n if (body.enabled !== undefined && typeof body.enabled !== \"boolean\") {\n return bad(\"enabled must be a boolean\");\n }\n if (body.frequency !== undefined && !isFrequency(body.frequency)) {\n return bad(`frequency must be one of ${FREQUENCIES.join(\", \")}`);\n }\n\n // userId comes from the resolved session, never from the body.\n await save({\n userId: userId ?? \"\",\n type: body.type,\n channel: body.channel,\n enabled: body.enabled ?? true,\n frequency: body.frequency ?? \"instant\",\n });\n\n return Response.json({ ok: true });\n },\n },\n\n {\n // Reached from a mail client with no session, so it is authenticated\n // by the signature on the link itself.\n path: \"/unsubscribe\",\n method: \"POST\",\n scope: { type: \"signed\", purpose: UNSUBSCRIBE_PURPOSE },\n handler: async ({ claims }) => {\n const type = claims?.data?.type;\n const channel = claims?.data?.channel;\n if (!claims || !type || !isChannel(channel)) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n const [current] = await ctx.store.find<PreferenceRow>(\n TABLE,\n { userId: claims.uid, type, channel },\n { limit: 1 },\n );\n\n // Already off: a second click, or a mail client retrying, is fine.\n if (current && !current.enabled && current.frequency === \"off\") {\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n }\n\n // The user changed this preference after the email went out. An old\n // link must not silently undo a newer decision made while logged in.\n if (\n current?.updatedAt &&\n claims.iat !== undefined &&\n current.updatedAt.getTime() > (claims.iat + 1) * 1000\n ) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n await save({\n userId: claims.uid,\n type,\n channel,\n enabled: false,\n frequency: \"off\",\n });\n\n // Gmail and Yahoo one-click requires the POST itself to unsubscribe,\n // with no confirmation page.\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n },\n },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AAK,GAAA,EACjD;AACA,YAAA,OAAO,QAAA,CAAS,KAAK,EAAE,KAAA,EAAO,iBAAgB,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,UAClE;AAEA,UAAA,MAAM,IAAA,CAAK;AAAA,YACT,QAAQ,MAAA,CAAO,GAAA;AAAA,YACf,IAAA;AAAA,YACA,OAAA;AAAA,YACA,OAAA,EAAS,KAAA;AAAA,YACT,SAAA,EAAW;AAAA,WACZ,CAAA;AAGD,UAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,IAAA,EAAM,cAAc,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG,CAAA;AAAA,QACpE;AAAA;AACF;AACF,GACF;AACF","file":"preferences.cjs","sourcesContent":["// Web APIs, not Buffer: this runs on Workers and Vercel Edge.\n\nexport function encodeBase64Url(input: string | Uint8Array): string {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n// Uint8Array<ArrayBuffer>: bare Uint8Array widens and is not a BufferSource.\nexport function decodeBase64UrlBytes(value: string): Uint8Array<ArrayBuffer> | null {\n try {\n const binary = atob(value.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\nexport function decodeBase64Url(value: string): string | null {\n const bytes = decodeBase64UrlBytes(value);\n return bytes ? new TextDecoder().decode(bytes) : null;\n}\n","import { decodeBase64Url, decodeBase64UrlBytes, encodeBase64Url } from \"./base64url\";\n\nexport type TokenClaims = {\n /** Subject — the user the token acts for. */\n uid: string;\n /** What the token is allowed to do. Verification requires an exact match. */\n purpose: string;\n /** Expiry, epoch seconds. */\n exp: number;\n /** Issued at, epoch seconds. Set by signToken; lets a route refuse a token older than a later change. */\n iat?: number;\n /** Free-form, purpose-specific. */\n data?: Record<string, string>;\n};\n\nconst encoder = new TextEncoder();\n\n// Changing this invalidates every outstanding token. Bump it on purpose only.\nconst KEY_SALT = encoder.encode(\"easy-ping/tokens/v1\");\n\n/** One HMAC key per purpose, derived with HKDF, so an unsubscribe key signs nothing else. */\nasync function hmacKey(secret: string, purpose: string): Promise<CryptoKey> {\n const master = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), \"HKDF\", false, [\n \"deriveKey\",\n ]);\n return crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: KEY_SALT, info: encoder.encode(purpose) },\n master,\n { name: \"HMAC\", hash: \"SHA-256\", length: 256 },\n false,\n [\"sign\", \"verify\"],\n );\n}\n\nexport async function signToken(\n secret: string,\n claims: TokenClaims,\n now: Date = new Date(),\n): Promise<string> {\n const stamped: TokenClaims = { ...claims, iat: claims.iat ?? Math.floor(now.getTime() / 1000) };\n const body = encodeBase64Url(JSON.stringify(stamped));\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n await hmacKey(secret, claims.purpose),\n encoder.encode(body),\n );\n return `${body}.${encodeBase64Url(new Uint8Array(signature))}`;\n}\n\n/** null for every failure mode. Distinguishing them tells an attacker which part to fix. */\nexport async function verifyToken(\n secret: string,\n token: string,\n purpose: string,\n now: Date = new Date(),\n): Promise<TokenClaims | null> {\n const separator = token.lastIndexOf(\".\");\n if (separator <= 0) return null;\n\n const body = token.slice(0, separator);\n const signature = decodeBase64UrlBytes(token.slice(separator + 1));\n if (!signature) return null;\n\n // Verified under the expected purpose's key before the body is parsed. subtle.verify is constant-time.\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n await hmacKey(secret, purpose),\n signature,\n encoder.encode(body),\n );\n if (!valid) return null;\n\n const decoded = decodeBase64Url(body);\n if (!decoded) return null;\n\n let claims: TokenClaims;\n try {\n claims = JSON.parse(decoded) as TokenClaims;\n } catch {\n return null;\n }\n\n if (typeof claims?.uid !== \"string\" || typeof claims.exp !== \"number\") return null;\n if (claims.purpose !== purpose) return null;\n if (claims.exp * 1000 <= now.getTime()) return null;\n if (claims.iat !== undefined && typeof claims.iat !== \"number\") return null;\n\n if (claims.data !== undefined) {\n if (typeof claims.data !== \"object\" || claims.data === null || Array.isArray(claims.data)) {\n return null;\n }\n for (const value of Object.values(claims.data)) {\n if (typeof value !== \"string\") return null;\n }\n }\n\n return claims;\n}\n\nexport const DEFAULT_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;\n/** Ninety days. A link that must outlive this should be re-issued, not made immortal. */\nexport const MAX_TOKEN_TTL_SECONDS = 90 * 24 * 60 * 60;\n\nexport const expiresIn = (seconds: number, now: Date = new Date()): number =>\n Math.floor(now.getTime() / 1000) + Math.min(Math.max(seconds, 0), MAX_TOKEN_TTL_SECONDS);\n\nexport type SignRequest = {\n uid: string;\n purpose: string;\n data?: Record<string, string>;\n /** Defaults to 30 days, capped at 90. */\n ttlSeconds?: number;\n};\n\n/** What a plugin gets instead of the secret: signs only its own declared purposes. */\nexport function createScopedSigner(\n secret: string,\n pluginId: string,\n purposes: ReadonlySet<string>,\n onViolation: (message: string) => Error,\n): (request: SignRequest) => Promise<string> {\n return (request) => {\n if (!purposes.has(request.purpose)) {\n throw onViolation(\n `plugin \"${pluginId}\" tried to sign a token for purpose \"${request.purpose}\", ` +\n \"which none of its signed routes declare.\",\n );\n }\n return signToken(secret, {\n uid: request.uid,\n purpose: request.purpose,\n exp: expiresIn(request.ttlSeconds ?? DEFAULT_TOKEN_TTL_SECONDS),\n ...(request.data ? { data: request.data } : {}),\n });\n };\n}\n","import type { DatabaseAdapter } from \"./adapter\";\nimport type { SessionConfig } from \"./config\";\nimport type { Logger } from \"./errors\";\nimport type { Promisable, RouteDefinition } from \"./plugin\";\nimport type { Runner } from \"./runner\";\nimport { verifyToken } from \"./tokens\";\n\nexport type HandlerDeps = {\n adapter: DatabaseAdapter;\n session: SessionConfig;\n runner: Runner;\n logger: Logger;\n basePath: string;\n secret: string;\n cronSecret?: string | undefined;\n /** Guards plugin machine routes. The instance defaults it to cronSecret. */\n machineSecret?: string | undefined;\n cronMaxSweeps?: number | undefined;\n pluginRoutes?: readonly RouteDefinition[] | undefined;\n /** Returns a 429 to send, or null to proceed. Runs after onRequest, before routing. */\n rateLimit?: ((request: Request) => Response | null) | undefined;\n /** Origins other than the request's own host that may POST. `*.example.com` allowed. */\n trustedOrigins?: readonly string[] | undefined;\n /** Runs before routing. Returning a Response short-circuits; use it for rate limiting. */\n // biome-ignore lint/suspicious/noConfusingVoidType: a hook that returns nothing is the common case\n onRequest?: ((request: Request) => Promisable<Response | undefined | void>) | undefined;\n maxBodyBytes?: number | undefined;\n};\n\n/** Every JSON body is capped here. Nothing legitimate the routes accept is bigger. */\nexport const MAX_BODY_BYTES = 64 * 1024;\n\nconst MAX_READ_IDS = 200;\n\n// Per-user data: no shared caching, no sniffing.\nconst PRIVATE_HEADERS: Record<string, string> = {\n \"cache-control\": \"private, no-store\",\n \"x-content-type-options\": \"nosniff\",\n};\n\nconst json = (body: unknown, status = 200) =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\", ...PRIVATE_HEADERS },\n });\n\nconst empty = (status: number) => new Response(null, { status, headers: PRIVATE_HEADERS });\n\n/** Plugin responses get the same headers, without touching their body. */\nfunction harden(response: Response): Response {\n const headers = new Headers(response.headers);\n for (const [name, value] of Object.entries(PRIVATE_HEADERS)) {\n if (!headers.has(name)) headers.set(name, value);\n }\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nconst encoder = new TextEncoder();\n\n/** Constant time over SHA-256 digests, so neither content nor length leaks. Works on edge runtimes. */\nasync function timingSafeEqual(a: string, b: string): Promise<boolean> {\n const [left, right] = await Promise.all(\n [a, b].map(\n async (value) => new Uint8Array(await crypto.subtle.digest(\"SHA-256\", encoder.encode(value))),\n ),\n );\n let diff = 0;\n for (let i = 0; i < 32; i += 1) diff |= (left?.[i] ?? 0) ^ (right?.[i] ?? 0);\n return diff === 0;\n}\n\n/** Anchored at a segment boundary: `/foo/api/notifications/cron` is not a cron request. */\nfunction routePath(url: URL, basePath: string): string {\n const { pathname } = url;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(`${basePath}/`)) return pathname.slice(basePath.length);\n return pathname;\n}\n\nexport type JsonBody = { body: Record<string, unknown> } | { error: Response };\n\n/** Reads a JSON object body with a streaming byte cap. Malformed JSON is 400; an empty body is `{}`. */\nexport async function readJsonBody(\n request: Request,\n maxBytes: number = MAX_BODY_BYTES,\n): Promise<JsonBody> {\n const tooLarge = () => ({ error: json({ error: `body exceeds ${maxBytes} bytes` }, 413) });\n\n const declared = Number(request.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > maxBytes) return tooLarge();\n if (!request.body) return { body: {} };\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n return tooLarge();\n }\n chunks.push(value);\n }\n\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n const text = new TextDecoder().decode(bytes);\n if (text.trim() === \"\") return { body: {} };\n\n try {\n const parsed: unknown = JSON.parse(text);\n return {\n body:\n parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {},\n };\n } catch {\n return { error: json({ error: \"body must be a JSON object\" }, 400) };\n }\n}\n\nconst isJsonContentType = (request: Request) =>\n /^application\\/json\\s*(;|$)/i.test((request.headers.get(\"content-type\") ?? \"\").trim());\n\nfunction originAllowed(origin: string, url: URL, request: Request, trusted: readonly string[]) {\n let host: string;\n try {\n host = new URL(origin).host;\n } catch {\n return false;\n }\n\n if (host === url.host) return true;\n // Behind a proxy that rewrites Host, the public host arrives here instead.\n const forwarded = request.headers.get(\"x-forwarded-host\")?.split(\",\")[0]?.trim();\n if (forwarded && host === forwarded) return true;\n\n return trusted.some((entry) =>\n entry.startsWith(\"*.\") ? host.endsWith(entry.slice(1)) : entry === origin,\n );\n}\n\n/** CSRF: a cross-site form can neither send `application/json` without a preflight nor forge `Origin`. */\nfunction csrfCheck(request: Request, url: URL, trusted: readonly string[]): Response | null {\n if (!isJsonContentType(request)) {\n return json({ error: \"content-type must be application/json\" }, 415);\n }\n\n const origin = request.headers.get(\"origin\");\n if (origin === null) return null;\n if (origin === \"null\" || !originAllowed(origin, url, request, trusted)) return empty(403);\n\n return null;\n}\n\nexport function createHandler(deps: HandlerDeps) {\n const trustedOrigins = deps.trustedOrigins ?? [];\n const maxBodyBytes = deps.maxBodyBytes ?? MAX_BODY_BYTES;\n\n async function resolveUserId(request: Request): Promise<string | null | \"error\"> {\n try {\n return await deps.session.getUserId(request);\n } catch (error) {\n // A broken session lookup is a 500, never a 401. RFC 0002 §1.\n deps.logger.error(\"session.getUserId threw\", { error });\n return \"error\";\n }\n }\n\n async function bearerMatches(request: Request, secret: string | undefined): Promise<boolean> {\n if (!secret) return false;\n const header = request.headers.get(\"authorization\") ?? \"\";\n const presented = header.startsWith(\"Bearer \") ? header.slice(7) : header;\n return timingSafeEqual(presented, secret);\n }\n\n async function handleCron(request: Request): Promise<Response> {\n if (!deps.cronSecret) return empty(404);\n if (!(await bearerMatches(request, deps.cronSecret))) return empty(401);\n\n // Bounded so an overlapping scheduler does not hold a request open for the whole backlog.\n const result = await deps.runner.drain(\n deps.cronMaxSweeps === undefined ? {} : { maxSweeps: deps.cronMaxSweeps },\n );\n return json(result);\n }\n\n /** Plugin routes first; auth is enforced here so a plugin cannot forget it. */\n async function handlePluginRoute(\n route: RouteDefinition,\n request: Request,\n url: URL,\n ): Promise<Response> {\n if (route.scope.type === \"user\") {\n if (request.method === \"POST\") {\n const rejected = csrfCheck(request, url, trustedOrigins);\n if (rejected) return rejected;\n }\n\n const userId = await resolveUserId(request);\n if (userId === \"error\") return empty(500);\n if (userId === null) return empty(401);\n return harden(await route.handler({ request, userId, claims: null, params: {} }));\n }\n\n if (route.scope.type === \"machine\") {\n if (!deps.machineSecret) return empty(404);\n if (!(await bearerMatches(request, deps.machineSecret))) return empty(401);\n return harden(await route.handler({ request, userId: null, claims: null, params: {} }));\n }\n\n if (route.scope.type === \"signed\") {\n const token =\n url.searchParams.get(\"token\") ??\n (request.headers.get(\"authorization\") ?? \"\").replace(/^Bearer /, \"\");\n\n const claims = await verifyToken(deps.secret, token, route.scope.purpose);\n // One response for every failure mode. RFC 0002 §5.\n if (!claims) return empty(400);\n\n return harden(await route.handler({ request, userId: claims.uid, claims, params: {} }));\n }\n\n return harden(await route.handler({ request, userId: null, claims: null, params: {} }));\n }\n\n async function route(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const path = routePath(url, deps.basePath);\n\n if (deps.onRequest) {\n const early = await deps.onRequest(request);\n if (early instanceof Response) return early;\n }\n\n if (deps.rateLimit) {\n const limited = deps.rateLimit(request);\n if (limited) return limited;\n }\n\n if (path === \"/cron\") {\n if (request.method !== \"POST\") return empty(405);\n return handleCron(request);\n }\n\n const pluginRoute = deps.pluginRoutes?.find(\n (candidate) => candidate.path === path && candidate.method === request.method,\n );\n if (pluginRoute) return handlePluginRoute(pluginRoute, request, url);\n\n if (request.method === \"POST\") {\n const rejected = csrfCheck(request, url, trustedOrigins);\n if (rejected) return rejected;\n }\n\n const userId = await resolveUserId(request);\n if (userId === \"error\") return empty(500);\n if (userId === null) return empty(401);\n\n if (request.method === \"GET\" && path === \"/\") {\n const limitParam = Number(url.searchParams.get(\"limit\") ?? 20);\n const limit = Number.isFinite(limitParam) ? Math.min(Math.max(limitParam, 1), 100) : 20;\n const cursor = url.searchParams.get(\"cursor\");\n\n // unseenCount rides on the first page only: a cursor request is scrollback, not a poll.\n const [page, unseenCount] = await Promise.all([\n deps.adapter.listNotifications({\n userId,\n limit,\n ...(cursor ? { cursor } : {}),\n ...(url.searchParams.get(\"unreadOnly\") === \"true\" ? { unreadOnly: true } : {}),\n }),\n cursor ? Promise.resolve(null) : deps.adapter.countUnseen(userId),\n ]);\n\n return json(unseenCount === null ? page : { ...page, unseenCount });\n }\n\n if (request.method === \"GET\" && path === \"/count\") {\n return json({ unseen: await deps.adapter.countUnseen(userId) });\n }\n\n if (request.method === \"POST\" && path === \"/seen\") {\n const parsed = await readJsonBody(request, maxBodyBytes);\n if (\"error\" in parsed) return parsed.error;\n const before = typeof parsed.body.before === \"string\" ? new Date(parsed.body.before) : null;\n\n // +1ms: Postgres keeps microseconds, an ISO string milliseconds; without it markSeen misses the newest row.\n const cutoff =\n before && !Number.isNaN(before.getTime()) ? new Date(before.getTime() + 1) : new Date();\n\n await deps.adapter.markSeen(userId, cutoff);\n return json({ ok: true });\n }\n\n if (request.method === \"POST\" && path === \"/read\") {\n const parsed = await readJsonBody(request, maxBodyBytes);\n if (\"error\" in parsed) return parsed.error;\n const ids = Array.isArray(parsed.body.ids)\n ? parsed.body.ids.filter((id): id is string => typeof id === \"string\")\n : [];\n if (ids.length === 0) return json({ error: \"ids must be a non-empty string array\" }, 400);\n\n if (ids.length > MAX_READ_IDS) {\n return json({ error: `at most ${MAX_READ_IDS} ids per request` }, 400);\n }\n\n // 404, not 403: a 403 confirms the row exists. RFC 0002 §2.\n const updated = await deps.adapter.markRead(userId, ids);\n return updated === 0 ? empty(404) : json({ updated });\n }\n\n if (request.method === \"POST\" && path === \"/read-all\") {\n return json({ updated: await deps.adapter.markAllRead(userId) });\n }\n\n return empty(404);\n }\n\n async function handle(request: Request): Promise<Response> {\n try {\n return await route(request);\n } catch (error) {\n // A thrown driver error must not escape: unhandled rejection on Node, stack trace elsewhere.\n deps.logger.error(\"request failed\", { url: request.url, error });\n return empty(500);\n }\n }\n\n return {\n handle,\n GET: handle,\n POST: handle,\n };\n}\n","import { readJsonBody } from \"../../core/handler\";\nimport type {\n ChannelDecision,\n EasyPingPlugin,\n PluginInitContext,\n PrepareContext,\n ResolveChannelsContext,\n} from \"../../core/plugin\";\nimport { DEFAULT_TOKEN_TTL_SECONDS, expiresIn, signToken } from \"../../core/tokens\";\nimport type { Channel, Frequency } from \"../../core/types\";\n\nexport const UNSUBSCRIBE_PURPOSE = \"unsubscribe\";\n\nconst TABLE = \"notification_preference\";\n\nconst CHANNELS: readonly Channel[] = [\"inApp\", \"email\", \"push\", \"sms\", \"slack\"];\nconst FREQUENCIES: readonly Frequency[] = [\"instant\", \"daily\", \"weekly\", \"off\"];\n\nconst isChannel = (value: unknown): value is Channel => CHANNELS.includes(value as Channel);\nconst isFrequency = (value: unknown): value is Frequency =>\n FREQUENCIES.includes(value as Frequency);\n\nexport type PreferenceRow = {\n userId: string;\n type: string;\n channel: Channel;\n enabled: boolean;\n frequency: Frequency;\n /** Last explicit change. An unsubscribe token issued before it is refused. */\n updatedAt?: Date;\n};\n\nexport type PreferencesOptions = {\n /** What an absent row means. Flip to false for opt-in-only notifications. */\n defaultEnabled?: boolean;\n /** Types that ignore preferences entirely: receipts, security alerts. */\n alwaysSend?: readonly string[];\n unsubscribeTtlSeconds?: number;\n};\n\nconst key = (userId: string, type: string, channel: string) => `${userId} ${type} ${channel}`;\n\ntype PreparedPreferences = Map<string, PreferenceRow>;\n\nexport function buildUnsubscribeToken(\n secret: string,\n userId: string,\n type: string,\n channel: Channel,\n ttlSeconds = DEFAULT_TOKEN_TTL_SECONDS,\n): Promise<string> {\n return signToken(secret, {\n uid: userId,\n purpose: UNSUBSCRIBE_PURPOSE,\n exp: expiresIn(ttlSeconds),\n data: { type, channel },\n });\n}\n\nexport function preferences(options: PreferencesOptions = {}): EasyPingPlugin<\"preferences\"> {\n const defaultEnabled = options.defaultEnabled ?? true;\n const alwaysSend = new Set(options.alwaysSend ?? []);\n\n // Assigned by init(), which easyPing() runs before any hook or route.\n let ctx: PluginInitContext;\n\n const isAllowed = (userId: string, type: string, channel: Channel, rows: PreparedPreferences) => {\n const row = rows.get(key(userId, type, channel));\n return row ? row.enabled && row.frequency !== \"off\" : defaultEnabled;\n };\n\n const load = (userIds: readonly string[]) =>\n ctx.store.find<PreferenceRow>(TABLE, { userId: { in: [...userIds] } });\n\n const save = (row: PreferenceRow) =>\n ctx.store.upsert(TABLE, [{ ...row, updatedAt: new Date() }], {\n onConflict: [\"userId\", \"type\", \"channel\"],\n });\n\n return {\n id: \"preferences\",\n\n init: (context) => {\n ctx = context;\n },\n\n schema: {\n notificationPreference: {\n tableName: TABLE,\n fields: {\n userId: { type: \"string\", required: true },\n type: { type: \"string\", required: true },\n channel: { type: \"string\", required: true },\n enabled: { type: \"boolean\", required: true, default: true },\n frequency: { type: \"string\", required: true, default: \"instant\" },\n updatedAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"userId\", \"type\", \"channel\"],\n },\n },\n\n hooks: {\n /** One query per send; doing this per recipient would be an N+1. */\n prepare: async (context: PrepareContext): Promise<PreparedPreferences> => {\n if (alwaysSend.has(context.type)) return new Map();\n\n const rows = await load(context.recipients.map((recipient) => recipient.userId));\n return new Map(rows.map((row) => [key(row.userId, row.type, row.channel), row]));\n },\n\n resolveChannels: (context: ResolveChannelsContext) => {\n if (alwaysSend.has(context.type)) return context.decisions;\n\n // prepare() failed: fail closed rather than assume everyone opted in.\n if (!(context.prepared instanceof Map)) {\n return context.decisions.map((decision) => ({ ...decision, action: \"skip\" as const }));\n }\n\n const rows = context.prepared as PreparedPreferences;\n\n return context.decisions.map<ChannelDecision>((decision) =>\n isAllowed(context.recipient.userId, context.type, decision.channel, rows)\n ? decision\n : { ...decision, action: \"skip\" },\n );\n },\n },\n\n routes: [\n {\n path: \"/preferences\",\n method: \"GET\",\n scope: { type: \"user\" },\n handler: async ({ userId }) => {\n const rows = await load([userId ?? \"\"]);\n return Response.json({ preferences: rows, defaultEnabled });\n },\n },\n\n {\n path: \"/preferences\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const parsed = await readJsonBody(request);\n if (\"error\" in parsed) return parsed.error;\n const body = parsed.body;\n\n const bad = (error: string) => Response.json({ error }, { status: 400 });\n\n // Only configured types, or every invented string becomes a row.\n if (typeof body.type !== \"string\" || !ctx.notificationTypes.includes(body.type)) {\n return bad(\"type must be a configured notification type\");\n }\n if (!isChannel(body.channel)) return bad(`channel must be one of ${CHANNELS.join(\", \")}`);\n if (body.enabled !== undefined && typeof body.enabled !== \"boolean\") {\n return bad(\"enabled must be a boolean\");\n }\n if (body.frequency !== undefined && !isFrequency(body.frequency)) {\n return bad(`frequency must be one of ${FREQUENCIES.join(\", \")}`);\n }\n\n // userId comes from the resolved session, never from the body.\n await save({\n userId: userId ?? \"\",\n type: body.type,\n channel: body.channel,\n enabled: body.enabled ?? true,\n frequency: body.frequency ?? \"instant\",\n });\n\n return Response.json({ ok: true });\n },\n },\n\n {\n // No session in a mail client; the link carries the proof.\n path: \"/unsubscribe\",\n method: \"POST\",\n scope: { type: \"signed\", purpose: UNSUBSCRIBE_PURPOSE },\n handler: async ({ claims }) => {\n const type = claims?.data?.type;\n const channel = claims?.data?.channel;\n if (!claims || !type || !isChannel(channel)) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n const [current] = await ctx.store.find<PreferenceRow>(\n TABLE,\n { userId: claims.uid, type, channel },\n { limit: 1 },\n );\n\n // Already off: a second click, or a mail client retrying, is fine.\n if (current && !current.enabled && current.frequency === \"off\") {\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n }\n\n // Changed after the email went out: an old link must not undo a newer decision.\n if (\n current?.updatedAt &&\n claims.iat !== undefined &&\n current.updatedAt.getTime() > (claims.iat + 1) * 1000\n ) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n await save({\n userId: claims.uid,\n type,\n channel,\n enabled: false,\n frequency: \"off\",\n });\n\n // One-click (Gmail, Yahoo) requires the POST itself to unsubscribe.\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n },\n },\n ],\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { h as EasyPingPlugin } from '../plugin-CiMsGlQe.cjs';
2
- import { C as Channel, F as Frequency } from '../adapter-BfLe2J0t.cjs';
1
+ import { h as EasyPingPlugin } from '../plugin-CHd2ZiGC.cjs';
2
+ import { C as Channel, F as Frequency } from '../adapter-D3lTy-4E.cjs';
3
3
 
4
4
  declare const UNSUBSCRIBE_PURPOSE = "unsubscribe";
5
5
  type PreferenceRow = {
@@ -1,5 +1,5 @@
1
- import { h as EasyPingPlugin } from '../plugin-C9Hoxus2.js';
2
- import { C as Channel, F as Frequency } from '../adapter-BfLe2J0t.js';
1
+ import { h as EasyPingPlugin } from '../plugin-Cg9usuUi.js';
2
+ import { C as Channel, F as Frequency } from '../adapter-D3lTy-4E.js';
3
3
 
4
4
  declare const UNSUBSCRIBE_PURPOSE = "unsubscribe";
5
5
  type PreferenceRow = {
@@ -1,4 +1,4 @@
1
- import { DEFAULT_TOKEN_TTL_SECONDS, signToken, expiresIn, readJsonBody } from '../chunk-DG3ZL5NP.js';
1
+ import { DEFAULT_TOKEN_TTL_SECONDS, signToken, expiresIn, readJsonBody } from '../chunk-BECMTNK7.js';
2
2
  import '../chunk-PTGHMCCG.js';
3
3
 
4
4
  // src/plugins/preferences/index.ts
@@ -106,8 +106,7 @@ function preferences(options = {}) {
106
106
  }
107
107
  },
108
108
  {
109
- // Reached from a mail client with no session, so it is authenticated
110
- // by the signature on the link itself.
109
+ // No session in a mail client; the link carries the proof.
111
110
  path: "/unsubscribe",
112
111
  method: "POST",
113
112
  scope: { type: "signed", purpose: UNSUBSCRIBE_PURPOSE },
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/plugins/preferences/index.ts"],"names":[],"mappings":";;;;AAWO,IAAM,mBAAA,GAAsB;AAEnC,IAAM,KAAA,GAAQ,yBAAA;AAEd,IAAM,WAA+B,CAAC,OAAA,EAAS,OAAA,EAAS,MAAA,EAAQ,OAAO,OAAO,CAAA;AAC9E,IAAM,WAAA,GAAoC,CAAC,SAAA,EAAW,OAAA,EAAS,UAAU,KAAK,CAAA;AAE9E,IAAM,S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AAO,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,IAAA,EAAM,cAAc,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG,CAAA;AAAA,UACpE;AAIA,UAAA,IACE,OAAA,EAAS,SAAA,IACT,MAAA,CAAO,GAAA,KAAQ,MAAA,IACf,OAAA,CAAQ,SAAA,CAAU,OAAA,EAAQ,GAAA,CAAK,MAAA,CAAO,GAAA,GAAM,CAAA,IAAK,GAAA,EACjD;AACA,YAAA,OAAO,QAAA,CAAS,KAAK,EAAE,KAAA,EAAO,iBAAgB,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,UAClE;AAEA,UAAA,MAAM,IAAA,CAAK;AAAA,YACT,QAAQ,MAAA,CAAO,GAAA;AAAA,YACf,IAAA;AAAA,YACA,OAAA;AAAA,YACA,OAAA,EAAS,KAAA;AAAA,YACT,SAAA,EAAW;AAAA,WACZ,CAAA;AAID,UAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,IAAA,EAAM,cAAc,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG,CAAA;AAAA,QACpE;AAAA;AACF;AACF,GACF;AACF","file":"preferences.js","sourcesContent":["import { readJsonBody } from \"../../core/handler\";\nimport type {\n ChannelDecision,\n EasyPingPlugin,\n PluginInitContext,\n PrepareContext,\n ResolveChannelsContext,\n} from \"../../core/plugin\";\nimport { DEFAULT_TOKEN_TTL_SECONDS, expiresIn, signToken } from \"../../core/tokens\";\nimport type { Channel, Frequency } from \"../../core/types\";\n\nexport const UNSUBSCRIBE_PURPOSE = \"unsubscribe\";\n\nconst TABLE = \"notification_preference\";\n\nconst CHANNELS: readonly Channel[] = [\"inApp\", \"email\", \"push\", \"sms\", \"slack\"];\nconst FREQUENCIES: readonly Frequency[] = [\"instant\", \"daily\", \"weekly\", \"off\"];\n\nconst isChannel = (value: unknown): value is Channel => CHANNELS.includes(value as Channel);\nconst isFrequency = (value: unknown): value is Frequency =>\n FREQUENCIES.includes(value as Frequency);\n\nexport type PreferenceRow = {\n userId: string;\n type: string;\n channel: Channel;\n enabled: boolean;\n frequency: Frequency;\n /** Last explicit change. An unsubscribe token issued before it is refused. */\n updatedAt?: Date;\n};\n\nexport type PreferencesOptions = {\n /** What an absent row means. Flip to false for opt-in-only notifications. */\n defaultEnabled?: boolean;\n /** Types that ignore preferences entirely: receipts, security alerts. */\n alwaysSend?: readonly string[];\n unsubscribeTtlSeconds?: number;\n};\n\nconst key = (userId: string, type: string, channel: string) => `${userId} ${type} ${channel}`;\n\ntype PreparedPreferences = Map<string, PreferenceRow>;\n\nexport function buildUnsubscribeToken(\n secret: string,\n userId: string,\n type: string,\n channel: Channel,\n ttlSeconds = DEFAULT_TOKEN_TTL_SECONDS,\n): Promise<string> {\n return signToken(secret, {\n uid: userId,\n purpose: UNSUBSCRIBE_PURPOSE,\n exp: expiresIn(ttlSeconds),\n data: { type, channel },\n });\n}\n\nexport function preferences(options: PreferencesOptions = {}): EasyPingPlugin<\"preferences\"> {\n const defaultEnabled = options.defaultEnabled ?? true;\n const alwaysSend = new Set(options.alwaysSend ?? []);\n\n // Assigned by init(), which easyPing() runs before any hook or route.\n let ctx: PluginInitContext;\n\n const isAllowed = (userId: string, type: string, channel: Channel, rows: PreparedPreferences) => {\n const row = rows.get(key(userId, type, channel));\n return row ? row.enabled && row.frequency !== \"off\" : defaultEnabled;\n };\n\n const load = (userIds: readonly string[]) =>\n ctx.store.find<PreferenceRow>(TABLE, { userId: { in: [...userIds] } });\n\n const save = (row: PreferenceRow) =>\n ctx.store.upsert(TABLE, [{ ...row, updatedAt: new Date() }], {\n onConflict: [\"userId\", \"type\", \"channel\"],\n });\n\n return {\n id: \"preferences\",\n\n init: (context) => {\n ctx = context;\n },\n\n schema: {\n notificationPreference: {\n tableName: TABLE,\n fields: {\n userId: { type: \"string\", required: true },\n type: { type: \"string\", required: true },\n channel: { type: \"string\", required: true },\n enabled: { type: \"boolean\", required: true, default: true },\n frequency: { type: \"string\", required: true, default: \"instant\" },\n updatedAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"userId\", \"type\", \"channel\"],\n },\n },\n\n hooks: {\n /** One query per send; doing this per recipient would be an N+1. */\n prepare: async (context: PrepareContext): Promise<PreparedPreferences> => {\n if (alwaysSend.has(context.type)) return new Map();\n\n const rows = await load(context.recipients.map((recipient) => recipient.userId));\n return new Map(rows.map((row) => [key(row.userId, row.type, row.channel), row]));\n },\n\n resolveChannels: (context: ResolveChannelsContext) => {\n if (alwaysSend.has(context.type)) return context.decisions;\n\n // prepare() failing leaves this undefined. Fail closed rather than\n // assuming everyone opted in: that is exactly how people who\n // unsubscribed get emailed anyway.\n if (!(context.prepared instanceof Map)) {\n return context.decisions.map((decision) => ({ ...decision, action: \"skip\" as const }));\n }\n\n const rows = context.prepared as PreparedPreferences;\n\n return context.decisions.map<ChannelDecision>((decision) =>\n isAllowed(context.recipient.userId, context.type, decision.channel, rows)\n ? decision\n : { ...decision, action: \"skip\" },\n );\n },\n },\n\n routes: [\n {\n path: \"/preferences\",\n method: \"GET\",\n scope: { type: \"user\" },\n handler: async ({ userId }) => {\n const rows = await load([userId ?? \"\"]);\n return Response.json({ preferences: rows, defaultEnabled });\n },\n },\n\n {\n path: \"/preferences\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const parsed = await readJsonBody(request);\n if (\"error\" in parsed) return parsed.error;\n const body = parsed.body;\n\n const bad = (error: string) => Response.json({ error }, { status: 400 });\n\n // Only types the app defined: otherwise every unknown string the\n // client invents is a row that lives forever.\n if (typeof body.type !== \"string\" || !ctx.notificationTypes.includes(body.type)) {\n return bad(\"type must be a configured notification type\");\n }\n if (!isChannel(body.channel)) return bad(`channel must be one of ${CHANNELS.join(\", \")}`);\n if (body.enabled !== undefined && typeof body.enabled !== \"boolean\") {\n return bad(\"enabled must be a boolean\");\n }\n if (body.frequency !== undefined && !isFrequency(body.frequency)) {\n return bad(`frequency must be one of ${FREQUENCIES.join(\", \")}`);\n }\n\n // userId comes from the resolved session, never from the body.\n await save({\n userId: userId ?? \"\",\n type: body.type,\n channel: body.channel,\n enabled: body.enabled ?? true,\n frequency: body.frequency ?? \"instant\",\n });\n\n return Response.json({ ok: true });\n },\n },\n\n {\n // Reached from a mail client with no session, so it is authenticated\n // by the signature on the link itself.\n path: \"/unsubscribe\",\n method: \"POST\",\n scope: { type: \"signed\", purpose: UNSUBSCRIBE_PURPOSE },\n handler: async ({ claims }) => {\n const type = claims?.data?.type;\n const channel = claims?.data?.channel;\n if (!claims || !type || !isChannel(channel)) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n const [current] = await ctx.store.find<PreferenceRow>(\n TABLE,\n { userId: claims.uid, type, channel },\n { limit: 1 },\n );\n\n // Already off: a second click, or a mail client retrying, is fine.\n if (current && !current.enabled && current.frequency === \"off\") {\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n }\n\n // The user changed this preference after the email went out. An old\n // link must not silently undo a newer decision made while logged in.\n if (\n current?.updatedAt &&\n claims.iat !== undefined &&\n current.updatedAt.getTime() > (claims.iat + 1) * 1000\n ) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n await save({\n userId: claims.uid,\n type,\n channel,\n enabled: false,\n frequency: \"off\",\n });\n\n // Gmail and Yahoo one-click requires the POST itself to unsubscribe,\n // with no confirmation page.\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n },\n },\n ],\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/plugins/preferences/index.ts"],"names":[],"mappings":";;;;AAWO,IAAM,mBAAA,GAAsB;AAEnC,IAAM,KAAA,GAAQ,yBAAA;AAEd,IAAM,WAA+B,CAAC,OAAA,EAAS,OAAA,EAAS,MAAA,EAAQ,OAAO,OAAO,CAAA;AAC9E,IAAM,WAAA,GAAoC,CAAC,SAAA,EAAW,OAAA,EAAS,UAAU,KAAK,CAAA;AAE9E,IAAM,SAAA,GAAY,CAAC,KAAA,KA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AE,EAAA,EAAI,IAAA,EAAM,cAAc,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG,CAAA;AAAA,UACpE;AAGA,UAAA,IACE,OAAA,EAAS,SAAA,IACT,MAAA,CAAO,GAAA,KAAQ,MAAA,IACf,OAAA,CAAQ,SAAA,CAAU,OAAA,EAAQ,GAAA,CAAK,MAAA,CAAO,GAAA,GAAM,CAAA,IAAK,GAAA,EACjD;AACA,YAAA,OAAO,QAAA,CAAS,KAAK,EAAE,KAAA,EAAO,iBAAgB,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,UAClE;AAEA,UAAA,MAAM,IAAA,CAAK;AAAA,YACT,QAAQ,MAAA,CAAO,GAAA;AAAA,YACf,IAAA;AAAA,YACA,OAAA;AAAA,YACA,OAAA,EAAS,KAAA;AAAA,YACT,SAAA,EAAW;AAAA,WACZ,CAAA;AAGD,UAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,IAAA,EAAM,cAAc,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG,CAAA;AAAA,QACpE;AAAA;AACF;AACF,GACF;AACF","file":"preferences.js","sourcesContent":["import { readJsonBody } from \"../../core/handler\";\nimport type {\n ChannelDecision,\n EasyPingPlugin,\n PluginInitContext,\n PrepareContext,\n ResolveChannelsContext,\n} from \"../../core/plugin\";\nimport { DEFAULT_TOKEN_TTL_SECONDS, expiresIn, signToken } from \"../../core/tokens\";\nimport type { Channel, Frequency } from \"../../core/types\";\n\nexport const UNSUBSCRIBE_PURPOSE = \"unsubscribe\";\n\nconst TABLE = \"notification_preference\";\n\nconst CHANNELS: readonly Channel[] = [\"inApp\", \"email\", \"push\", \"sms\", \"slack\"];\nconst FREQUENCIES: readonly Frequency[] = [\"instant\", \"daily\", \"weekly\", \"off\"];\n\nconst isChannel = (value: unknown): value is Channel => CHANNELS.includes(value as Channel);\nconst isFrequency = (value: unknown): value is Frequency =>\n FREQUENCIES.includes(value as Frequency);\n\nexport type PreferenceRow = {\n userId: string;\n type: string;\n channel: Channel;\n enabled: boolean;\n frequency: Frequency;\n /** Last explicit change. An unsubscribe token issued before it is refused. */\n updatedAt?: Date;\n};\n\nexport type PreferencesOptions = {\n /** What an absent row means. Flip to false for opt-in-only notifications. */\n defaultEnabled?: boolean;\n /** Types that ignore preferences entirely: receipts, security alerts. */\n alwaysSend?: readonly string[];\n unsubscribeTtlSeconds?: number;\n};\n\nconst key = (userId: string, type: string, channel: string) => `${userId} ${type} ${channel}`;\n\ntype PreparedPreferences = Map<string, PreferenceRow>;\n\nexport function buildUnsubscribeToken(\n secret: string,\n userId: string,\n type: string,\n channel: Channel,\n ttlSeconds = DEFAULT_TOKEN_TTL_SECONDS,\n): Promise<string> {\n return signToken(secret, {\n uid: userId,\n purpose: UNSUBSCRIBE_PURPOSE,\n exp: expiresIn(ttlSeconds),\n data: { type, channel },\n });\n}\n\nexport function preferences(options: PreferencesOptions = {}): EasyPingPlugin<\"preferences\"> {\n const defaultEnabled = options.defaultEnabled ?? true;\n const alwaysSend = new Set(options.alwaysSend ?? []);\n\n // Assigned by init(), which easyPing() runs before any hook or route.\n let ctx: PluginInitContext;\n\n const isAllowed = (userId: string, type: string, channel: Channel, rows: PreparedPreferences) => {\n const row = rows.get(key(userId, type, channel));\n return row ? row.enabled && row.frequency !== \"off\" : defaultEnabled;\n };\n\n const load = (userIds: readonly string[]) =>\n ctx.store.find<PreferenceRow>(TABLE, { userId: { in: [...userIds] } });\n\n const save = (row: PreferenceRow) =>\n ctx.store.upsert(TABLE, [{ ...row, updatedAt: new Date() }], {\n onConflict: [\"userId\", \"type\", \"channel\"],\n });\n\n return {\n id: \"preferences\",\n\n init: (context) => {\n ctx = context;\n },\n\n schema: {\n notificationPreference: {\n tableName: TABLE,\n fields: {\n userId: { type: \"string\", required: true },\n type: { type: \"string\", required: true },\n channel: { type: \"string\", required: true },\n enabled: { type: \"boolean\", required: true, default: true },\n frequency: { type: \"string\", required: true, default: \"instant\" },\n updatedAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"userId\", \"type\", \"channel\"],\n },\n },\n\n hooks: {\n /** One query per send; doing this per recipient would be an N+1. */\n prepare: async (context: PrepareContext): Promise<PreparedPreferences> => {\n if (alwaysSend.has(context.type)) return new Map();\n\n const rows = await load(context.recipients.map((recipient) => recipient.userId));\n return new Map(rows.map((row) => [key(row.userId, row.type, row.channel), row]));\n },\n\n resolveChannels: (context: ResolveChannelsContext) => {\n if (alwaysSend.has(context.type)) return context.decisions;\n\n // prepare() failed: fail closed rather than assume everyone opted in.\n if (!(context.prepared instanceof Map)) {\n return context.decisions.map((decision) => ({ ...decision, action: \"skip\" as const }));\n }\n\n const rows = context.prepared as PreparedPreferences;\n\n return context.decisions.map<ChannelDecision>((decision) =>\n isAllowed(context.recipient.userId, context.type, decision.channel, rows)\n ? decision\n : { ...decision, action: \"skip\" },\n );\n },\n },\n\n routes: [\n {\n path: \"/preferences\",\n method: \"GET\",\n scope: { type: \"user\" },\n handler: async ({ userId }) => {\n const rows = await load([userId ?? \"\"]);\n return Response.json({ preferences: rows, defaultEnabled });\n },\n },\n\n {\n path: \"/preferences\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const parsed = await readJsonBody(request);\n if (\"error\" in parsed) return parsed.error;\n const body = parsed.body;\n\n const bad = (error: string) => Response.json({ error }, { status: 400 });\n\n // Only configured types, or every invented string becomes a row.\n if (typeof body.type !== \"string\" || !ctx.notificationTypes.includes(body.type)) {\n return bad(\"type must be a configured notification type\");\n }\n if (!isChannel(body.channel)) return bad(`channel must be one of ${CHANNELS.join(\", \")}`);\n if (body.enabled !== undefined && typeof body.enabled !== \"boolean\") {\n return bad(\"enabled must be a boolean\");\n }\n if (body.frequency !== undefined && !isFrequency(body.frequency)) {\n return bad(`frequency must be one of ${FREQUENCIES.join(\", \")}`);\n }\n\n // userId comes from the resolved session, never from the body.\n await save({\n userId: userId ?? \"\",\n type: body.type,\n channel: body.channel,\n enabled: body.enabled ?? true,\n frequency: body.frequency ?? \"instant\",\n });\n\n return Response.json({ ok: true });\n },\n },\n\n {\n // No session in a mail client; the link carries the proof.\n path: \"/unsubscribe\",\n method: \"POST\",\n scope: { type: \"signed\", purpose: UNSUBSCRIBE_PURPOSE },\n handler: async ({ claims }) => {\n const type = claims?.data?.type;\n const channel = claims?.data?.channel;\n if (!claims || !type || !isChannel(channel)) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n const [current] = await ctx.store.find<PreferenceRow>(\n TABLE,\n { userId: claims.uid, type, channel },\n { limit: 1 },\n );\n\n // Already off: a second click, or a mail client retrying, is fine.\n if (current && !current.enabled && current.frequency === \"off\") {\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n }\n\n // Changed after the email went out: an old link must not undo a newer decision.\n if (\n current?.updatedAt &&\n claims.iat !== undefined &&\n current.updatedAt.getTime() > (claims.iat + 1) * 1000\n ) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n await save({\n userId: claims.uid,\n type,\n channel,\n enabled: false,\n frequency: \"off\",\n });\n\n // One-click (Gmail, Yahoo) requires the POST itself to unsubscribe.\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n },\n },\n ],\n };\n}\n"]}
@@ -78,8 +78,7 @@ var pushSchema = {
78
78
  primaryKey: ["id"],
79
79
  indexes: [
80
80
  { on: ["userId"], name: "push_device_user_idx" },
81
- // One row per endpoint: re-registering the same browser must update,
82
- // not duplicate, or every send goes out N times to one device.
81
+ // One row per endpoint: re-registering updates instead of duplicating.
83
82
  { on: ["endpoint"], unique: true, name: "push_device_endpoint_idx" }
84
83
  ]
85
84
  }