pinia-plugin-subscription 1.0.0-beta.17 → 1.0.0-beta.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
24
24
  - Added unit tests covering the tracing system and the leak detection logic
25
25
 
26
26
  ### Changed
27
+ - `PluginSubscriberWithoutInstance` now captures the shared store-events handler and provides helpers to register `StoreEventsSubscriber` instances or event callback maps; the state-snapshots subscriber uses this shared registration path.
27
28
  - Subscribers now execute in ascending `execution.order` order (default `9`), preserving declaration order for equal priorities; `PluginSubscriber.tracer` exposes the tracer created for that subscriber and passes the same instance to its `Store` factory.
28
29
  - Trace groups follow the lifecycles of a store: `groupId` is now a `/` separated path (`<storeId>/plugin`, `<storeId>/onAction:<name>#<n>`, with `/after` and `/onError` sub-groups, `<storeId>/onMutation#<n>`, `<storeId>/reset#<n>`, `<storeId>/plugin/deferred:<subscriber>#<n>`). Every trace emitted for a store while a group is open, including those of subscribers and `Store` subclasses, joins the innermost one. `traceGroups` builders take the call counter; `TraceGroupId` is removed, and `groupId` is lifted from the payload to the event like `actionId`
29
30
  - `storeMutationSubscription` now supports several subscribers per store, like `storeOnActionSubscription`: a single `$subscribe` is registered per store and dispatches to every callback. A failing callback is reported through `traceError` without blocking the others, subscriber names are tracked, and the hook is unsubscribed when the store is disposed
package/README.md CHANGED
@@ -6,8 +6,7 @@ This project provides:
6
6
  - a lightweight mechanism to declare "subscribers" that are invoked when stores are registered or updated by Pinia;
7
7
  - a `Store` base class (helper wrapper) to ease interacting with Pinia stores from subscribers or other plugin code;
8
8
  - an API to create a Pinia plugin from a list of subscribers;
9
- - the `$reset` method on all stores modified by the plugin;
10
- - optional state rollback through the separate [`pinia-plugin-state-snapshots`](packages/state-snapshots/) package.
9
+ - optional `$reset` support and state rollback through the separate [`pinia-plugin-state-snapshots`](packages/state-snapshots/) package.
11
10
 
12
11
  Deferred subscribers attach their action and reset callbacks to their own store after hydration; disposing a store removes its callbacks.
13
12
  If a snapshot cannot be created, the state-snapshots subscriber logs the error
@@ -65,10 +64,22 @@ app.use(pinia)
65
64
  app.mount('#app')
66
65
  ```
67
66
 
67
+ ## Compatible Plugins
68
+
69
+ These plugins build on `pinia-plugin-subscription`; register their subscribers
70
+ with `createPlugin()` to use their features:
71
+
72
+ - **[pinia-plugin-subscription-devtools](packages/devtools/README.md):** structured tracing with filtered listeners, a per-store journal, payload redaction and an in-page panel.
73
+ - **[pinia-plugin-state-snapshots](packages/state-snapshots/README.md):** opt-in `$reset` wrapping and reset callbacks, plus state rollback when configured actions fail.
74
+ - **[pinia-plugin-extending-store](https://github.com/AlxBDo/extending-pinia-store):** compose state, getters and actions from parent stores into a child store.
75
+ - **[pinia-plugin-persist-state](https://github.com/AlxBDo/pinia-plugin-persist-state):** persist store state to browser storage or IndexedDB, with optional encryption.
76
+ - **[pinia-plugin-action-flow](https://github.com/AlxBDo/pinia-plugin-action-flow):** define before/after flows around store actions, including validation and side effects.
77
+
78
+ Discover more compatible plugins on the [`pinia-plugin-subscription` GitHub topic](https://github.com/topics/pinia-plugin-subscription).
79
+
68
80
  ## Advanced Features
69
81
 
70
- - **Structured tracing:** the plugin and `Store` emit typed trace events through an optional `tracerHandler`. Tracing itself (listeners, journal, redaction, in-page panel) lives in the separate [`pinia-plugin-subscription-devtools`](packages/devtools/) package, so apps that do not debug stay lean — see [Tracing](#tracing).
71
- - **Reset callbacks:** The separate [`pinia-plugin-state-snapshots`](packages/state-snapshots/README.md) package owns reset behavior. Register callbacks with the store's `$onResetStore()` method; `PluginSubscription` itself does not replace or reset `$reset`.
82
+ - **Structured tracing:** the plugin and `Store` emit typed trace events through an optional `tracerHandler`; without one, no trace events are emitted. See [Tracing](#tracing).
72
83
  - **SSR and hydration control:** Configure whether each subscribed plugin runs on the server, the client, or only after client hydration.
73
84
  - **Lifecycle safety:** Internal hydration ordering is now guarded so `hydrate()` completes before `afterHydration()` and disposed stores do not retain stale subscriber metadata.
74
85
 
@@ -1,3 +1,5 @@
1
+ import StoreEventsSubscriber from "../events/store-events-subscriber";
2
+ import StoreEventSubscriberHandler from "../events/store-events-subscriber-handler";
1
3
  import TraceEmitterBase from "../system/TraceEmitterBase";
2
4
  import type { PiniaPluginContext, Store as PiniaStore } from "pinia";
3
5
  import type { PluginExecutionOptions, PluginHydrationScheduler, PluginOptions, PluginSubscriber as PluginSubscriberInterface, PluginSubscriptions, StoreClassConstructorParams, StoreMutationSubscription, StoreOnActionSubscription } from "../types/plugin";
@@ -7,20 +9,34 @@ import type { PluginExecutionOptions, PluginHydrationScheduler, PluginOptions, P
7
9
  * @returns The created store instance or undefined if creation fails.
8
10
  */
9
11
  export default abstract class PluginSubscriberWithoutInstance extends TraceEmitterBase implements PluginSubscriberInterface {
12
+ private _eventsStoreSubscribers;
13
+ /** Options for the plugin subscriber's execution. */
14
+ execution?: PluginExecutionOptions;
15
+ /** Scheduler for handling the hydration process of the plugin subscriber. */
16
+ hydrationScheduler?: PluginHydrationScheduler;
10
17
  private _name;
11
- private _pluginOptions?;
12
- protected _storeOnActionSubscription?: StoreOnActionSubscription;
13
- protected _storeMutationSubscription?: StoreMutationSubscription;
14
- protected _subscriptions?: PluginSubscriptions;
15
18
  /**
16
19
  * Called when the plugin subscriber has been created for a specific store.
17
20
  * This callback can be used to perform any initialization or setup required for the plugin subscriber.
18
21
  */
19
22
  protected pluginCreated?: (store: PiniaStore) => void;
20
- /** Options for the plugin subscriber's execution. */
21
- execution?: PluginExecutionOptions;
22
- /** Scheduler for handling the hydration process of the plugin subscriber. */
23
- hydrationScheduler?: PluginHydrationScheduler;
23
+ private _pluginOptions?;
24
+ protected _storeEventSubscriberHandler?: StoreEventSubscriberHandler;
25
+ /**
26
+ * Subscription for store actions.
27
+ * This subscription is used to listen for actions dispatched in the store.
28
+ */
29
+ protected _storeOnActionSubscription?: StoreOnActionSubscription;
30
+ /**
31
+ * Subscription for store mutations.
32
+ * This subscription is used to listen for mutations occurring in the store.
33
+ */
34
+ protected _storeMutationSubscription?: StoreMutationSubscription;
35
+ /**
36
+ * Subscriptions for the plugin subscriber.
37
+ * This is used to manage and track all active subscriptions related to the plugin subscriber.
38
+ */
39
+ protected _subscriptions?: PluginSubscriptions;
24
40
  get name(): string;
25
41
  get pluginOptions(): StoreClassConstructorParams | undefined;
26
42
  set pluginOptions(options: StoreClassConstructorParams | undefined);
@@ -29,12 +45,15 @@ export default abstract class PluginSubscriberWithoutInstance extends TraceEmitt
29
45
  get subscriptions(): PluginSubscriptions | undefined;
30
46
  set subscriptions(subscriptions: PluginSubscriptions);
31
47
  constructor(pluginName: string);
48
+ protected addEventStoreSubscriber(subscriber: StoreEventsSubscriber): void;
49
+ protected addEventStoreSubscription(id: string, store: PiniaPluginContext['store'], subscriptions: Record<string, (...args: any[]) => void>): void;
32
50
  /**
33
51
  * Called after the store has been hydrated.
34
52
  * @param context The Pinia plugin context containing the store and options.
35
53
  * @returns A promise that resolves when the post-hydration process is complete, or void if synchronous.
36
54
  */
37
55
  afterHydration(_context: PiniaPluginContext): void | Promise<void>;
56
+ clearStoreEventsSubscriptions(storeId: string): void;
38
57
  /**
39
58
  * Called when the plugin subscriber needs to hydrate its state.
40
59
  * @param context The Pinia plugin context containing the store and options.
@@ -4,6 +4,7 @@ export default class StoreEventsSubscriber {
4
4
  private _storeId?;
5
5
  private _subscriptions;
6
6
  get id(): string | undefined;
7
+ get storeId(): string | undefined;
7
8
  get subscriptions(): Record<string, (...args: any[]) => void>;
8
9
  constructor(id: string, store: Store, subscriptions?: Record<string, (...args: any[]) => void>);
9
10
  clear(): void;
package/dist/helpers.js CHANGED
@@ -1,20 +1,60 @@
1
1
  var o = Object.defineProperty;
2
2
  var c = (i, s, t) => s in i ? o(i, s, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[s] = t;
3
3
  var r = (i, s, t) => c(i, typeof s != "symbol" ? s + "" : s, t);
4
- import { T as a, a as u, g as h, s as _, i as p, h as b } from "./chunks/PluginSubscription-BwmFDjfB.js";
5
- import { P as x, b as $, S as v, c as C, d as R, e as K, t as k } from "./chunks/PluginSubscription-BwmFDjfB.js";
6
- import { isRef as d, ref as S, toRef as g } from "vue";
7
- class l extends a {
4
+ import { T as a, a as u, g as h, s as _, i as b, h as p } from "./chunks/PluginSubscription-BwmFDjfB.js";
5
+ import { P, b as $, S as x, c as H, d as C, e as R, t as K } from "./chunks/PluginSubscription-BwmFDjfB.js";
6
+ import { isRef as d, ref as S, toRef as l } from "vue";
7
+ class g {
8
+ constructor(s, t, e) {
9
+ r(this, "_id");
10
+ r(this, "_storeId");
11
+ r(this, "_subscriptions");
12
+ this._id = s, this._storeId = t.$id, this._subscriptions = e ?? {};
13
+ }
14
+ get id() {
15
+ return this._id;
16
+ }
17
+ get storeId() {
18
+ return this._storeId;
19
+ }
20
+ get subscriptions() {
21
+ return this._subscriptions;
22
+ }
23
+ clear() {
24
+ this._subscriptions = {}, this._storeId = void 0, this._id = void 0;
25
+ }
26
+ getSubscription(s, t) {
27
+ return this._storeId === t.$id ? this._subscriptions?.[s] : void 0;
28
+ }
29
+ hasSubscription(s, t) {
30
+ return this._storeId === t.$id && !!this._subscriptions?.[s];
31
+ }
32
+ hasSubscriptions(s) {
33
+ return this._storeId === s.$id && Object.keys(this._subscriptions ?? {}).length > 0;
34
+ }
35
+ shouldPropagateError(s) {
36
+ return !1;
37
+ }
38
+ subscribe(s, t) {
39
+ this._subscriptions[s] = t;
40
+ }
41
+ unsubscribe(s) {
42
+ delete this._subscriptions?.[s];
43
+ }
44
+ }
45
+ class f extends a {
8
46
  constructor(t) {
9
47
  super();
48
+ r(this, "_eventsStoreSubscribers", /* @__PURE__ */ new Map());
49
+ r(this, "execution");
50
+ r(this, "hydrationScheduler");
10
51
  r(this, "_name");
52
+ r(this, "pluginCreated");
11
53
  r(this, "_pluginOptions");
54
+ r(this, "_storeEventSubscriberHandler");
12
55
  r(this, "_storeOnActionSubscription");
13
56
  r(this, "_storeMutationSubscription");
14
57
  r(this, "_subscriptions");
15
- r(this, "pluginCreated");
16
- r(this, "execution");
17
- r(this, "hydrationScheduler");
18
58
  this._name = t;
19
59
  }
20
60
  get name() {
@@ -38,18 +78,31 @@ class l extends a {
38
78
  set subscriptions(t) {
39
79
  this._subscriptions = t;
40
80
  }
81
+ addEventStoreSubscriber(t) {
82
+ this._storeEventSubscriberHandler && (this._eventsStoreSubscribers.set(t.id, t), this._storeEventSubscriberHandler.subscribe(t.storeId, t), this.trace(
83
+ `eventsStoreSubscriber:${t.id}:subscribed`,
84
+ t.storeId,
85
+ () => ({ eventsStoreSubscriber: t })
86
+ ));
87
+ }
88
+ addEventStoreSubscription(t, e, n) {
89
+ this.addEventStoreSubscriber(new g(t, e, n));
90
+ }
41
91
  afterHydration(t) {
42
92
  }
93
+ clearStoreEventsSubscriptions(t) {
94
+ this._eventsStoreSubscribers.delete(t), this._storeEventSubscriberHandler?.clearSubscribers(t);
95
+ }
43
96
  hydrate(t) {
44
97
  }
45
98
  invoke({ store: t }, e) {
46
- return this._tracer = e?.createTracer ? e.createTracer(this.name) : void 0, this.pluginCreated && this.pluginCreated(t), !0;
99
+ return this._tracer = e?.createTracer ? e.createTracer(this.name) : void 0, this._storeEventSubscriberHandler = e?.eventsHandler, this.pluginCreated && this.pluginCreated(t), !0;
47
100
  }
48
101
  traceLabelFormatter(t) {
49
102
  return `${this.name}:${t}`;
50
103
  }
51
104
  }
52
- class T extends l {
105
+ class y extends f {
53
106
  constructor(t, e) {
54
107
  super(t);
55
108
  r(this, "_createInstance");
@@ -67,7 +120,7 @@ class T extends l {
67
120
  }), this._storeInstance ? (this._subscriptions = this._storeInstance.getSubscriptions(), this._storeMutationSubscription = this._storeInstance.storeSubscribe, this._storeOnActionSubscription = this._storeInstance.onAction, this.pluginCreated && this.pluginCreated(t), !0) : !1;
68
121
  }
69
122
  }
70
- class f extends u {
123
+ class v extends u {
71
124
  constructor(t, e) {
72
125
  super();
73
126
  r(this, "_className", "Store");
@@ -118,7 +171,7 @@ class f extends u {
118
171
  return !this._tracer && this._createTracer && (this._tracer = this._createTracer(), this._tracer.scope = this.store.$id), this._tracer;
119
172
  }
120
173
  addToState(t, e) {
121
- this.isOptionApi() || d(e) || (e = S(e)), this.state[t] = e, this.store[t] = g(this.state, t);
174
+ this.isOptionApi() || d(e) || (e = S(e)), this.state[t] = e, this.store[t] = l(this.state, t);
122
175
  }
123
176
  addSubscription(t, e, n) {
124
177
  this._subscriptions[t] = { subscription: e, ...n ?? {} };
@@ -136,14 +189,14 @@ class f extends u {
136
189
  return this.getValue(this.state[t]);
137
190
  }
138
191
  getSubscriptions() {
139
- if (!p(this._subscriptions))
192
+ if (!b(this._subscriptions))
140
193
  return this._subscriptions;
141
194
  }
142
195
  getValue(t) {
143
196
  return t?.__v_isRef ? t.value : t;
144
197
  }
145
198
  hasDeniedFirstChar(t) {
146
- return b(t);
199
+ return p(t);
147
200
  }
148
201
  static hasRequiredKeys(t) {
149
202
  return this._requiredKeys !== void 0 && this._requiredKeys?.every((e) => !!t[e]);
@@ -163,64 +216,29 @@ class f extends u {
163
216
  return Object.prototype.hasOwnProperty.call(this.store, t);
164
217
  }
165
218
  }
166
- r(f, "_requiredKeys");
167
- function A(i, s, t) {
219
+ r(v, "_requiredKeys");
220
+ function T(i, s, t) {
168
221
  return {
169
222
  name: i,
170
223
  invoke: s,
171
224
  ...t
172
225
  };
173
226
  }
174
- class m {
175
- constructor(s, t, e) {
176
- r(this, "_id");
177
- r(this, "_storeId");
178
- r(this, "_subscriptions");
179
- this._id = s, this._storeId = t.$id, this._subscriptions = e ?? {};
180
- }
181
- get id() {
182
- return this._id;
183
- }
184
- get subscriptions() {
185
- return this._subscriptions;
186
- }
187
- clear() {
188
- this._subscriptions = {}, this._storeId = void 0, this._id = void 0;
189
- }
190
- getSubscription(s, t) {
191
- return this._storeId === t.$id ? this._subscriptions?.[s] : void 0;
192
- }
193
- hasSubscription(s, t) {
194
- return this._storeId === t.$id && !!this._subscriptions?.[s];
195
- }
196
- hasSubscriptions(s) {
197
- return this._storeId === s.$id && Object.keys(this._subscriptions ?? {}).length > 0;
198
- }
199
- shouldPropagateError(s) {
200
- return !1;
201
- }
202
- subscribe(s, t) {
203
- this._subscriptions[s] = t;
204
- }
205
- unsubscribe(s) {
206
- delete this._subscriptions?.[s];
207
- }
208
- }
209
227
  export {
210
- x as PLUGIN_EVENTS,
211
- T as PluginSubscriber,
212
- l as PluginSubscriberWithoutInstance,
228
+ P as PLUGIN_EVENTS,
229
+ y as PluginSubscriber,
230
+ f as PluginSubscriberWithoutInstance,
213
231
  $ as PluginSubscription,
214
- v as STORE_EVENTS,
215
- C as SUBSCRIBER_EVENTS,
216
- f as Store,
217
- m as StoreEventsSubscriber,
218
- A as createPluginSubscriber,
219
- R as getActionStoreKey,
232
+ x as STORE_EVENTS,
233
+ H as SUBSCRIBER_EVENTS,
234
+ v as Store,
235
+ g as StoreEventsSubscriber,
236
+ T as createPluginSubscriber,
237
+ C as getActionStoreKey,
220
238
  h as getDefineAStoreSetupContext,
221
- K as getStoreKeyPrefix,
222
- b as hasDeniedFirstChar,
223
- p as isEmpty,
239
+ R as getStoreKeyPrefix,
240
+ p as hasDeniedFirstChar,
241
+ b as isEmpty,
224
242
  _ as setEnhancedStore,
225
- k as traceGroups
243
+ K as traceGroups
226
244
  };
@@ -478,6 +478,19 @@ runtime environment, store behavior and tracing.
478
478
 
479
479
  Factory returning a plain-object subscriber `{ name, invoke, ...optionalProps }`. Exported from `pinia-plugin-subscription/helpers`.
480
480
 
481
+ ### `PluginSubscriberWithoutInstance`
482
+
483
+ Extend `PluginSubscriberWithoutInstance` when a class-based subscriber needs
484
+ to work with the Pinia store directly rather than creating a `Store` wrapper.
485
+ `createPlugin()` passes the shared store-events handler to `invoke()`. After
486
+ calling `super.invoke(context, pluginOptions)`, subclasses can register
487
+ per-store event callbacks with the protected
488
+ `addEventStoreSubscription(id, store, subscriptions)` helper, or register an
489
+ existing `StoreEventsSubscriber` with `addEventStoreSubscriber(subscriber)`.
490
+ The subscription map keys are store event names and values are callbacks.
491
+ `clearStoreEventsSubscriptions(storeId)` clears event subscribers for that
492
+ store from the shared handler.
493
+
481
494
  `createPlugin()` accepts hydration options directly. Set shared execution and
482
495
  scheduling defaults for its subscribers, or use `subscriberExecution` to
483
496
  configure execution by subscriber name:
@@ -13,22 +13,22 @@ the [plugin authoring guide](authoring-plugins.md) instead.
13
13
  > annotations and generics. Types are always optional at runtime — they only
14
14
  > add autocompletion and compile-time checks.
15
15
 
16
- ## What every compatible plugin guarantees
16
+ ## What compatible plugins can use
17
17
 
18
- Plugins built on `pinia-plugin-subscription` share a common contract:
18
+ Plugins built on `pinia-plugin-subscription` use the shared subscriber
19
+ registration and execution infrastructure:
19
20
 
20
21
  - **Single registration point** — all subscribers are registered through one
21
22
  `createPlugin()` call.
22
- - **`$reset` on registered stores** — every store registered by the plugin
23
- gains a `$reset()` method that restores its initial state, including
24
- setup-style stores where pinia does not provide one natively.
25
- - **Runtime-filtered tracing** — with `pinia-plugin-subscription-devtools`,
26
- register trace listeners and filter events by source, namespace, scope, or
27
- level.
28
- - **SSR-safe execution** — each plugin declares where (`client`, `server`
29
- or `both`) and when (`immediate` or deferred after hydration) it runs.
30
- - **Optional state rollback** — install and register `pinia-plugin-state-snapshots`
31
- to restore configured state when an action fails.
23
+ - **Configurable execution** — subscribers can declare their runtime
24
+ environment (`client`, `server` or `both`) and whether they run immediately
25
+ or after client hydration.
26
+ - **Optional tracing** — the core emits structured events when a
27
+ `tracerHandler` is configured; a compatible tracing plugin can consume them.
28
+ - **Optional reset and rollback** — `pinia-plugin-state-snapshots` can add
29
+ `$reset` to setup-style stores and restore configured state when an action
30
+ fails. Reset wrapping is opt-in; it is not provided automatically to every
31
+ store or by every compatible plugin.
32
32
 
33
33
  ## Installation
34
34
 
@@ -246,8 +246,11 @@ associated (and on store dispose), which limits map growth over time.
246
246
 
247
247
  ## `$reset` on registered stores
248
248
 
249
- Every store registered by the plugin exposes `$reset()`, which restores the
250
- initial state captured at registration — including for setup-style stores:
249
+ Register `StateSnapshotsSubscriber` and enable its `overrideReset` option to
250
+ add `$reset()` to a store. The wrapper restores a fresh copy of the initial
251
+ state captured at registration, including for setup-style stores. Enable it
252
+ globally on the subscriber or per store (see the
253
+ [state-snapshots documentation](../packages/state-snapshots/README.md)):
251
254
 
252
255
  ```js
253
256
  const store = useCounterStore()
@@ -255,8 +258,8 @@ store.increment()
255
258
  store.$reset() // state is back to its initial value
256
259
  ```
257
260
 
258
- Each compatible plugin may also run custom logic on reset — see the plugin's
259
- own documentation.
261
+ When the wrapper is installed, callbacks registered with `$onResetStore()`
262
+ run after the state is restored.
260
263
 
261
264
  ## State rollback on action failure
262
265
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinia-plugin-subscription",
3
- "version": "1.0.0-beta.17",
3
+ "version": "1.0.0-beta.18",
4
4
  "description": "Pinia plugin for Vue.js that helps building Pinia plugins by centralizing subscriber registration and providing a Store base class for store helpers.",
5
5
  "type": "module",
6
6
  "sideEffects": false,