@playstack/notifications
Typed user-directed notifications across queued mail, push delivery, and a persisted in-app inbox.
Reference: @playstack/notifications@0.1.0-beta.5 · TypeScript · MIT licence
Free. MIT licensed. Check preview availability before installing. See package access.
@playstack/notifications defines what a user-directed notification means, validates its input, applies channel preferences, and routes work to queued mail, push delivery, or a persisted in-app inbox. It does not own broadcasts, audiences, templates, provider clients, application routes, or SMS.
Install
npm install @playstack/notifications @playstack/delivery @playstack/eventsDefine and compose notifications
import { createNotifications, defineNotifications } from '@playstack/notifications'
const registry = defineNotifications({
'account.invitation.accepted': {
input: invitationAcceptedSchema,
category: 'transactional',
channels: ['mail', 'push', 'inApp'],
digestible: false,
render: {
mail: ({ input, locale }) => ({
payload: { template: 'invite', input, locale },
}),
push: ({ input }) => ({
payload: { title: 'Invitation accepted', body: input.summary },
}),
inApp: ({ input }) => ({
title: 'Invitation accepted',
body: input.summary,
href: '/members',
}),
},
},
})
const notifications = createNotifications({
registry,
preferences,
locales,
recipients,
queue,
delivery,
inbox,
events,
clock,
ids,
})enqueue() validates input and creates endpoint-free, per-channel jobs. process() revalidates the job, preference, locale, and current recipient endpoint before rendering or dispatching it. Push recipients resolve to opaque device-token IDs and fan out through @playstack/delivery/push; provider credentials are loaded only by the delivery worker.
Personal and account-scoped inboxes
Use an explicit recipient plus optional account for inbox operations. Omitted
accountId selects personal notifications only; it never means all accounts.
Your server must authorize the current recipient and account before calling these
methods. Account IDs in a request or job are not authorization evidence.
const scope = {
recipient: { type: 'user', id: currentUserId },
accountId: authorizedAccountId,
}
await notifications.listInbox({ ...scope, limit: 50 })
await notifications.countUnread(scope)
await notifications.markReadAndArchive(inboxId, scope)
const changed = await notifications.markReadBatch({ ...scope, limit: 100 })Pass producer-owned accountId in enqueue options, alongside an optional stable
idempotencyKey. Attribution survives queueing and transactional preparation;
preference policies receive it, and renderers cannot replace it. Reusing a
notification/recipient identity under a different account rejects. Personal rows
remain separate from every account inbox, including cursor anchors and retention.
markReadAndArchive preserves independent first-read/archive timestamps in one
transaction. markReadBatch changes at most 1–1000 currently unread, unarchived
rows and commits their read events atomically; a zero count can mean eligible rows
are locked. It does not install a background drain or authorize bulk access.
The native inbox adapter requires the nullable accountId column and updated
recipient/account/order index before deployment. Existing unscoped rows remain
personal; do not infer account ownership from old content or links. Schema changes,
custom-adapter updates and application qualification remain explicit owner work.
Unified reads across authorized accounts
listInbox and countUnread also accept an explicit
selection: { accountIds, includePersonal } instead of accountId. The host
must derive and reauthorize that account set for the authenticated recipient on
every request. Browser input and cursors do not establish account authority.
At most 1,000 supplied account IDs are accepted and normalized into one sorted
set. Empty IDs with includePersonal: false select nothing, never all accounts.
Listing uses one global time/ID order. Its opaque cursor binds the recipient,
canonical account set, personal inclusion and archive filter; changing that view
requires fresh pagination. Page size may change. Existing personal-only and
exact-account queries retain their current behavior. The adapter's
supportsAccountSelection: true capability is required for unified reads;
exact-only custom adapters fail closed instead of silently selecting personal
rows. Update custom adapters and qualify their selection/cursor predicates before
advertising this capability.
Individual mutations, bulk-read batches and retention still require one exact
account or personal scope and reject selection. Cross-account bulk mutation
needs a separate authority and per-row evidence design. React hosts should
replace the client/cache identity when their authorized selection changes.
This read profile adds no column or migration and makes no physical scan-cost
or snapshot-consistency guarantee.
Configuration reference
Prepare on the caller's transaction
For preparation only, use the public createNotificationPreparer({ registry, transactionKind, preferences, locales, recipients, clock, ids, safeOrigins? }).
The resolvers are transaction-aware; no ordinary root, queue, delivery, inbox or
event ports are required. Its prepareInTransaction method shares all the
full-service validation, snapshot and closure safeguards below.
Configure optional preparation: { transactionKind, preferences, locales, recipients } with transaction-aware resolvers. Each takes its ordinary input and
the original transaction context as a second argument; ordinary root resolvers
are never a fallback. prepareInTransaction(job, transaction) validates input,
rechecks native preference/category policy, resolves current locale/recipient and
renders. It returns deeply frozen suppressed or prepared delivery requests/
inbox data, without opening transactions, enqueueing, sending or emitting events.
Use it inside PrismaNotificationQueue.consumeNext to join Delivery intent,
encrypted protected content and required outbox writes—or inbox and its required
event—on the supplied handle. The packaged README has the maintained sequence.
Recipient outputs and results must be bounded portable JSON; jobs are snapshotted
before awaits, with up to 100 unique push targets. Policy/render/data failures
return fixed preparation_failed; missing capability or kind mismatch refuses.
Prepared values may contain addresses/proofs/rendered secrets: keep them private
and transient or encrypted, never ordinary jobs/logs/browser data. They are not
authorization receipts or send grants. Host consent/account/lifecycle and final
suppression checks, compatible locks, immutable hashes and later committed-begin
Delivery dispatch remain required. No new schema is needed. Ordinary process
remains non-caller-transaction and must not run inside the queue callback.
NotificationsOptions property | Required | Purpose |
|---|---|---|
registry | Yes | Typed definitions, Standard Schema input validators, channels, categories, and renderers. |
preferences | Yes | Resolves policy, quiet-hours, and marketing preferences per channel. |
locales | Yes | Resolves the recipient locale at enqueue and execution time. |
recipients | Yes | Resolves the current delivery subject and mail endpoint. |
queue | Yes | Enqueues endpoint-free notification jobs. |
delivery | Yes | Hands rendered mail payloads to @playstack/delivery. |
inbox | For in-app channels | Transactional inbox persistence; omit for mail/push-only registries. |
admissions | For keyed enqueue | Durable admission and queue-handoff replay persistence. |
preparation | For caller-transaction preparation | Explicit same-handle preference, locale and recipient resolvers. |
events | Yes | Emits queued, delivered, failed, read, and archived lifecycle events. |
clock, ids | Yes | Application-owned time and identifiers. |
readRetentionMs | No | Read-row retention; defaults to 90 days. |
safeOrigins | No | Explicit HTTPS origins allowed in in-app notification links. |
Transactional notifications bypass only marketing-preference decisions. They still honor policy and quiet-hours decisions and always pass through delivery suppression.
Persistence and testing
Outbound-only composition
Mail/push-only registries can omit inbox. An in-app definition without an inbox
fails configuration, and inbox read/mutation/retention methods reject without an
adapter. Do not supply a dummy store to compose mail-only notifications.
All three native database artifacts are independently optional:
| Artifact ID | Needed for |
|---|---|
notifications.prisma | Native persisted in-app inbox. |
notifications.queue.prisma | Native queued jobs and independent consumption replay receipts. |
notifications.admissions.prisma | Caller-keyed logical notification admission. |
The updated CLI omits these schemas unless selected in artifacts or
existingArtifacts. Queue-only adoption does not propose unused inbox tables.
Use the queue-only configuration
to validate existing native queue storage with artifacts: [], or explicitly
select notifications.queue.prisma for managed output. existingArtifacts
validation remains mandatory. An inApp definition still needs an inbox; keyed
enqueue still needs admissions, independently of queue replay receipts.
No selection applies migrations, deletes old files/tables or proves live readiness.
Caller-keyed durable enqueue
import { PrismaNotificationAdmissionPersistence } from '@playstack/notifications/prisma'
const admissions = new PrismaNotificationAdmissionPersistence(prisma, {
namespace: 'product:production',
})
const notifications = createNotifications({ ...options, admissions })
await notifications.enqueue(name, input, recipient, context, {
idempotencyKey: 'invitation:opaque-id:accepted',
})This composition fragment requires the optional notifications.admissions.prisma
artifact and a root Prisma client. Persist the logical key with the producer's
domain event and reuse it on every retry. Unkeyed calls remain new notifications;
a key without admission persistence rejects before queue I/O. Conflicting input
or recipient under the same key rejects instead of changing the existing intent.
Admissions retain the original notification ID, validated portable JSON input, recipient, context and initial channel plan. Keep secrets, rendered content and raw addresses out of jobs/admissions; storage is not encrypted. Worker-time recipient and preference authority is rechecked.
A lost queue acknowledgment can repeat the same channel key. The queue/outbox must retain that key or a tombstone for the full replay lifetime, including after consumption; a short deduplication TTL or remove-on-complete is insufficient. Confirmed handoffs are recorded before queued-event emission, so that event can be retried without enqueueing again. Observational events remain at-least-once.
Terminal admission-payload redaction
Native PrismaNotificationAdmissionPersistence.redactTerminal({ key, redactedAt }, transaction) joins a trusted cleanup worker's Read Committed caller
transaction. It is an optional privileged persistence port; authorize the exact
namespace/key, retire/drain the source, await required Audit and repeat final
authority checks on the same transaction. The adapter supplies no product
permission and does not commit by itself. A failed caller operation must roll
redaction and evidence back together.
Only valid plans whose allowed channels are both handed off and observed qualify,
including all-suppressed plans. Missing keys stay absent; incomplete or malformed
state refuses. The row retains its permanent namespace/key and first redaction
time, replacing the original request, recipient/account/notification identity,
input and context with a minimal marker. Identical or changed input then fails
with admission_redacted; late receipt updates cannot restore the payload.
Repeated cleanup preserves the first time. No TTL, key reuse, row deletion,
schema migration or artifact-hash change is introduced.
Native enqueue admission now also requires Read Committed, preventing a waiting transaction from returning a snapshot older than the redaction. Treat results as provisional until caller commit is acknowledged. Cleanup storage diagnostics are redacted; lost commit acknowledgment never grants replay permission.
An older producer can still hold a copied plan and resume a queue/event call. Retire/fence producers and drain whole operations before claiming completion; permanent queue receipts and event deduplication remain necessary. Pending jobs, inboxes, outboxes, protected content, delivery journals, database history and backups need independent retention. Namespace/key identifiers remain data and should be opaque or keyed. This API redacts logical admission payloads, not a whole subject or remote provider history.
Native queue and retained replay receipts
PrismaNotificationQueue from @playstack/notifications/prisma supplies that
queue contract without an application-written broker adapter. Explicitly select
and migrate notifications.queue.prisma, then configure a root Prisma client,
clock and immutable application/environment namespace. Construction starts no
worker; scheduling, bounded ticks and shutdown remain host-owned.
consumeNext(callback) locks one available job and supplies its physical
transaction to the callback. Join native Delivery intent registration, protected
content storage and a worker outbox on that handle, or join inbox insertion and
its required event. The callback must not call notifications.process() (which
has no caller-transaction contract), open another root transaction or perform
provider/network I/O. Recheck definition, preference, actor and recipient
authority during this admission. A later committed-begin Delivery worker owns
external effects.
Successful consumption inserts an independent NotificationQueueReceipt and
deletes the job atomically. Replaying the same key after job deletion cannot
recreate work; changed immutable input conflicts. Rollback leaves the job and
no committed downstream handoff. A tick returning false means no currently
claimable row, not proof that all workers have drained.
Receipts retain namespace, logical key, request hash and completion time, not the consumed job payload. Those identifiers are still retained data. There is no automatic TTL or safe replay-key reuse: deleting receipts while replay remains possible reopens delivery. Review pending payloads, admission records, protected content, downstream queues, provider records and backups together before claiming complete erasure. See the Audiences consent-mail recipe.
The host owns durable producer replay, downstream deduplication, retention and erasure. Admissions have no automatic expiry/deletion policy and do not join an arbitrary domain transaction. Queue acceptance is not provider delivery; pair with the durable delivery worker for provider attempts. Neither layer promises exactly-once delivery.
@playstack/notifications/prisma exports PrismaNotificationInboxPersistence;
explicitly selecting the optional notifications.prisma artifact synchronizes
its inbox schema fragment. Applications own migration execution.
@playstack/notifications/testing provides deterministic in-memory queue and
inbox implementations.
In-app persistence and its delivered event share one transaction. Queue and observational event failures cannot make another notification channel fail.
Cross-store erasure qualification
Local inbox/preparation cleanup is not proof that provider payloads, queue work, exports, backups or other stores have been erased. Join required cleanup intents and Audit to native lifecycle changes; resume external cleanup durably using the original identity and acknowledged receipts. Do not delete replay barriers to make an operation look complete.
Before claiming complete erasure, qualify rollback on hook/evidence failure, producer replay and restart, delayed previously unseen events, active sender races, partial provider outages and restore from a pre-erasure backup. Isolate a restored store until current lifecycle decisions have been reconciled. A sender already admitted to provider I/O cannot be recalled by deleting a local row. New consent needs a new identity and must still consult retained complaint, bounce and stop-all policy. These gates remain application-owned; keep unqualified erasure actions disabled.
API entry points and requirements
Reference snapshot: @playstack/notifications@0.1.0-beta.5. Import only the entry point your runtime needs. Paths below are relative to the installed package; use Go to Definition in your editor to inspect exact parameters, return types and overloads. Do not import the declaration-file paths directly.
| Public entry point | Declaration file |
|---|---|
@playstack/notifications | ./dist/index.d.ts |
@playstack/notifications/errors | ./dist/errors.d.ts |
@playstack/notifications/prisma | ./dist/prisma.d.ts |
@playstack/notifications/testing | ./dist/testing.d.ts |
@playstack/notifications/package.json | No TypeScript declaration (asset or metadata export). |
Node.js engine requirement: >=20. This is not a claim that every entry point works in browsers or Workers.
Peer dependencies
This package declares no peer dependencies. Its ordinary dependencies are resolved by the package manager.
For a complete first program, start with Getting started. For API lookup and partial-example conventions, see Reading the reference. Provider failures, lifecycle requirements and application responsibilities remain described in the guide above; types alone do not establish production safety.