pinia.d.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. import { App } from 'vue-demi';
  2. import { ComputedRef } from 'vue-demi';
  3. import type { DebuggerEvent } from 'vue-demi';
  4. import { EffectScope } from 'vue-demi';
  5. import type { Plugin as Plugin_2 } from 'vue-demi';
  6. import { Ref } from 'vue-demi';
  7. import { ToRef } from 'vue-demi';
  8. import { ToRefs } from 'vue-demi';
  9. import { UnwrapRef } from 'vue-demi';
  10. import type { WatchOptions } from 'vue-demi';
  11. import { WritableComputedRef } from 'vue-demi';
  12. /**
  13. * Creates an _accept_ function to pass to `import.meta.hot` in Vite applications.
  14. *
  15. * @example
  16. * ```js
  17. * const useUser = defineStore(...)
  18. * if (import.meta.hot) {
  19. * import.meta.hot.accept(acceptHMRUpdate(useUser, import.meta.hot))
  20. * }
  21. * ```
  22. *
  23. * @param initialUseStore - return of the defineStore to hot update
  24. * @param hot - `import.meta.hot`
  25. */
  26. export declare function acceptHMRUpdate<Id extends string = string, S extends StateTree = StateTree, G extends _GettersTree<S> = _GettersTree<S>, A = _ActionsTree>(initialUseStore: StoreDefinition<Id, S, G, A>, hot: any): (newModule: any) => any;
  27. /**
  28. * Type of an object of Actions. For internal usage only.
  29. * For internal use **only**
  30. */
  31. export declare type _ActionsTree = Record<string, _Method>;
  32. export declare type _Awaited<T> = T extends null | undefined ? T : T extends object & {
  33. then(onfulfilled: infer F): any;
  34. } ? F extends (value: infer V, ...args: any) => any ? _Awaited<V> : never : T;
  35. /**
  36. * Creates a Pinia instance to be used by the application
  37. */
  38. export declare function createPinia(): Pinia;
  39. /**
  40. * Recursive `Partial<T>`. Used by {@link Store['$patch']}.
  41. *
  42. * For internal use **only**
  43. */
  44. export declare type _DeepPartial<T> = {
  45. [K in keyof T]?: _DeepPartial<T[K]>;
  46. };
  47. /**
  48. * Options parameter of `defineStore()` for setup stores. Can be extended to
  49. * augment stores with the plugin API. @see {@link DefineStoreOptionsBase}.
  50. */
  51. export declare interface DefineSetupStoreOptions<Id extends string, S extends StateTree, G, A> extends DefineStoreOptionsBase<S, Store<Id, S, G, A>> {
  52. /**
  53. * Extracted actions. Added by useStore(). SHOULD NOT be added by the user when
  54. * creating the store. Can be used in plugins to get the list of actions in a
  55. * store defined with a setup function. Note this is always defined
  56. */
  57. actions?: A;
  58. }
  59. /**
  60. * Creates a `useStore` function that retrieves the store instance
  61. *
  62. * @param id - id of the store (must be unique)
  63. * @param options - options to define the store
  64. */
  65. export declare function defineStore<Id extends string, S extends StateTree = {}, G extends _GettersTree<S> = {}, A = {}>(id: Id, options: Omit<DefineStoreOptions<Id, S, G, A>, 'id'>): StoreDefinition<Id, S, G, A>;
  66. /**
  67. * Creates a `useStore` function that retrieves the store instance
  68. *
  69. * @param options - options to define the store
  70. *
  71. * @deprecated use `defineStore(id, options)` instead
  72. */
  73. export declare function defineStore<Id extends string, S extends StateTree = {}, G extends _GettersTree<S> = {}, A = {}>(options: DefineStoreOptions<Id, S, G, A>): StoreDefinition<Id, S, G, A>;
  74. /**
  75. * Creates a `useStore` function that retrieves the store instance
  76. *
  77. * @param id - id of the store (must be unique)
  78. * @param storeSetup - function that defines the store
  79. * @param options - extra options
  80. */
  81. export declare function defineStore<Id extends string, SS>(id: Id, storeSetup: (helpers: SetupStoreHelpers) => SS, options?: DefineSetupStoreOptions<Id, _ExtractStateFromSetupStore<SS>, _ExtractGettersFromSetupStore<SS>, _ExtractActionsFromSetupStore<SS>>): StoreDefinition<Id, _ExtractStateFromSetupStore<SS>, _ExtractGettersFromSetupStore<SS>, _ExtractActionsFromSetupStore<SS>>;
  82. /**
  83. * Options parameter of `defineStore()` for option stores. Can be extended to
  84. * augment stores with the plugin API. @see {@link DefineStoreOptionsBase}.
  85. */
  86. export declare interface DefineStoreOptions<Id extends string, S extends StateTree, G, A> extends DefineStoreOptionsBase<S, Store<Id, S, G, A>> {
  87. /**
  88. * Unique string key to identify the store across the application.
  89. */
  90. id: Id;
  91. /**
  92. * Function to create a fresh state. **Must be an arrow function** to ensure
  93. * correct typings!
  94. */
  95. state?: () => S;
  96. /**
  97. * Optional object of getters.
  98. */
  99. getters?: G & ThisType<UnwrapRef<S> & _StoreWithGetters<G> & PiniaCustomProperties> & _GettersTree<S>;
  100. /**
  101. * Optional object of actions.
  102. */
  103. actions?: A & ThisType<A & UnwrapRef<S> & _StoreWithState<Id, S, G, A> & _StoreWithGetters<G> & PiniaCustomProperties>;
  104. /**
  105. * Allows hydrating the store during SSR when complex state (like client side only refs) are used in the store
  106. * definition and copying the value from `pinia.state` isn't enough.
  107. *
  108. * @example
  109. * If in your `state`, you use any `customRef`s, any `computed`s, or any `ref`s that have a different value on
  110. * Server and Client, you need to manually hydrate them. e.g., a custom ref that is stored in the local
  111. * storage:
  112. *
  113. * ```ts
  114. * const useStore = defineStore('main', {
  115. * state: () => ({
  116. * n: useLocalStorage('key', 0)
  117. * }),
  118. * hydrate(storeState, initialState) {
  119. * // @ts-expect-error: https://github.com/microsoft/TypeScript/issues/43826
  120. * storeState.n = useLocalStorage('key', 0)
  121. * }
  122. * })
  123. * ```
  124. *
  125. * @param storeState - the current state in the store
  126. * @param initialState - initialState
  127. */
  128. hydrate?(storeState: UnwrapRef<S>, initialState: UnwrapRef<S>): void;
  129. }
  130. /**
  131. * Options passed to `defineStore()` that are common between option and setup
  132. * stores. Extend this interface if you want to add custom options to both kinds
  133. * of stores.
  134. */
  135. export declare interface DefineStoreOptionsBase<S extends StateTree, Store> {
  136. }
  137. /**
  138. * Available `options` when creating a pinia plugin.
  139. */
  140. export declare interface DefineStoreOptionsInPlugin<Id extends string, S extends StateTree, G, A> extends Omit<DefineStoreOptions<Id, S, G, A>, 'id' | 'actions'> {
  141. /**
  142. * Extracted object of actions. Added by useStore() when the store is built
  143. * using the setup API, otherwise uses the one passed to `defineStore()`.
  144. * Defaults to an empty object if no actions are defined.
  145. */
  146. actions: A;
  147. }
  148. /**
  149. * Dispose a Pinia instance by stopping its effectScope and removing the state, plugins and stores. This is mostly
  150. * useful in tests, with both a testing pinia or a regular pinia and in applications that use multiple pinia instances.
  151. * Once disposed, the pinia instance cannot be used anymore.
  152. *
  153. * @param pinia - pinia instance
  154. */
  155. export declare function disposePinia(pinia: Pinia): void;
  156. /**
  157. * For internal use **only**
  158. */
  159. export declare type _ExtractActionsFromSetupStore<SS> = SS extends undefined | void ? {} : Pick<SS, _ExtractActionsFromSetupStore_Keys<SS>>;
  160. /**
  161. * Type that enables refactoring through IDE.
  162. * For internal use **only**
  163. */
  164. export declare type _ExtractActionsFromSetupStore_Keys<SS> = keyof {
  165. [K in keyof SS as SS[K] extends _Method ? K : never]: any;
  166. };
  167. /**
  168. * For internal use **only**
  169. */
  170. export declare type _ExtractGettersFromSetupStore<SS> = SS extends undefined | void ? {} : Pick<SS, _ExtractGettersFromSetupStore_Keys<SS>>;
  171. /**
  172. * Type that enables refactoring through IDE.
  173. * For internal use **only**
  174. */
  175. export declare type _ExtractGettersFromSetupStore_Keys<SS> = keyof {
  176. [K in keyof SS as SS[K] extends ComputedRef ? K : never]: any;
  177. };
  178. /**
  179. * For internal use **only**
  180. */
  181. export declare type _ExtractStateFromSetupStore<SS> = SS extends undefined | void ? {} : Pick<SS, _ExtractStateFromSetupStore_Keys<SS>>;
  182. /**
  183. * Type that enables refactoring through IDE.
  184. * For internal use **only**
  185. */
  186. export declare type _ExtractStateFromSetupStore_Keys<SS> = keyof {
  187. [K in keyof SS as SS[K] extends _Method | ComputedRef ? never : K]: any;
  188. };
  189. /**
  190. * Get the currently active pinia if there is any.
  191. */
  192. export declare const getActivePinia: () => Pinia | undefined;
  193. /**
  194. * Type of an object of Getters that infers the argument. For internal usage only.
  195. * For internal use **only**
  196. */
  197. export declare type _GettersTree<S extends StateTree> = Record<string, ((state: UnwrapRef<S> & UnwrapRef<PiniaCustomStateProperties<S>>) => any) | (() => any)>;
  198. /**
  199. * Internal utility type
  200. */
  201. declare type _IfEquals<X, Y, A = true, B = false> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B;
  202. /**
  203. * Internal utility type
  204. */
  205. declare type _IsReadonly<T, K extends keyof T> = _IfEquals<{
  206. [P in K]: T[P];
  207. }, {
  208. -readonly [P in K]: T[P];
  209. }, false, // Property is not readonly if they are the same
  210. true>;
  211. /**
  212. * Allows directly using actions from your store without using the composition
  213. * API (`setup()`) by generating an object to be spread in the `methods` field
  214. * of a component. The values of the object are the actions while the keys are
  215. * the names of the resulting methods.
  216. *
  217. * @example
  218. * ```js
  219. * export default {
  220. * methods: {
  221. * // other methods properties
  222. * // useCounterStore has two actions named `increment` and `setCount`
  223. * ...mapActions(useCounterStore, { more: 'increment', setIt: 'setCount' })
  224. * },
  225. *
  226. * created() {
  227. * this.more()
  228. * this.setIt(2)
  229. * }
  230. * }
  231. * ```
  232. *
  233. * @param useStore - store to map from
  234. * @param keyMapper - object to define new names for the actions
  235. */
  236. export declare function mapActions<Id extends string, S extends StateTree, G extends _GettersTree<S>, A, KeyMapper extends Record<string, keyof A>>(useStore: StoreDefinition<Id, S, G, A>, keyMapper: KeyMapper): _MapActionsObjectReturn<A, KeyMapper>;
  237. /**
  238. * Allows directly using actions from your store without using the composition
  239. * API (`setup()`) by generating an object to be spread in the `methods` field
  240. * of a component.
  241. *
  242. * @example
  243. * ```js
  244. * export default {
  245. * methods: {
  246. * // other methods properties
  247. * ...mapActions(useCounterStore, ['increment', 'setCount'])
  248. * },
  249. *
  250. * created() {
  251. * this.increment()
  252. * this.setCount(2) // pass arguments as usual
  253. * }
  254. * }
  255. * ```
  256. *
  257. * @param useStore - store to map from
  258. * @param keys - array of action names to map
  259. */
  260. export declare function mapActions<Id extends string, S extends StateTree, G extends _GettersTree<S>, A>(useStore: StoreDefinition<Id, S, G, A>, keys: Array<keyof A>): _MapActionsReturn<A>;
  261. /**
  262. * For internal use **only**
  263. */
  264. export declare type _MapActionsObjectReturn<A, T extends Record<string, keyof A>> = {
  265. [key in keyof T]: A[T[key]];
  266. };
  267. /**
  268. * For internal use **only**
  269. */
  270. export declare type _MapActionsReturn<A> = {
  271. [key in keyof A]: A[key];
  272. };
  273. /**
  274. * Alias for `mapState()`. You should use `mapState()` instead.
  275. * @deprecated use `mapState()` instead.
  276. */
  277. export declare const mapGetters: typeof mapState;
  278. /**
  279. * Allows using state and getters from one store without using the composition
  280. * API (`setup()`) by generating an object to be spread in the `computed` field
  281. * of a component. The values of the object are the state properties/getters
  282. * while the keys are the names of the resulting computed properties.
  283. * Optionally, you can also pass a custom function that will receive the store
  284. * as its first argument. Note that while it has access to the component
  285. * instance via `this`, it won't be typed.
  286. *
  287. * @example
  288. * ```js
  289. * export default {
  290. * computed: {
  291. * // other computed properties
  292. * // useCounterStore has a state property named `count` and a getter `double`
  293. * ...mapState(useCounterStore, {
  294. * n: 'count',
  295. * triple: store => store.n * 3,
  296. * // note we can't use an arrow function if we want to use `this`
  297. * custom(store) {
  298. * return this.someComponentValue + store.n
  299. * },
  300. * doubleN: 'double'
  301. * })
  302. * },
  303. *
  304. * created() {
  305. * this.n // 2
  306. * this.doubleN // 4
  307. * }
  308. * }
  309. * ```
  310. *
  311. * @param useStore - store to map from
  312. * @param keyMapper - object of state properties or getters
  313. */
  314. export declare function mapState<Id extends string, S extends StateTree, G extends _GettersTree<S> | {
  315. [key: string]: ComputedRef;
  316. }, A, KeyMapper extends Record<string, keyof S | keyof G | ((store: Store<Id, S, G, A>) => any)>>(useStore: StoreDefinition<Id, S, G, A>, keyMapper: KeyMapper): _MapStateObjectReturn<Id, S, G, A, KeyMapper>;
  317. /**
  318. * Allows using state and getters from one store without using the composition
  319. * API (`setup()`) by generating an object to be spread in the `computed` field
  320. * of a component.
  321. *
  322. * @example
  323. * ```js
  324. * export default {
  325. * computed: {
  326. * // other computed properties
  327. * ...mapState(useCounterStore, ['count', 'double'])
  328. * },
  329. *
  330. * created() {
  331. * this.count // 2
  332. * this.double // 4
  333. * }
  334. * }
  335. * ```
  336. *
  337. * @param useStore - store to map from
  338. * @param keys - array of state properties or getters
  339. */
  340. export declare function mapState<Id extends string, S extends StateTree, G extends _GettersTree<S> | {
  341. [key: string]: ComputedRef;
  342. }, A, Keys extends keyof S | keyof G>(useStore: StoreDefinition<Id, S, G, A>, keys: readonly Keys[]): _MapStateReturn<S, G, Keys>;
  343. /**
  344. * For internal use **only**
  345. */
  346. export declare type _MapStateObjectReturn<Id extends string, S extends StateTree, G extends _GettersTree<S> | {
  347. [key: string]: ComputedRef;
  348. }, A, T extends Record<string, keyof S | keyof G | ((store: Store<Id, S, G, A>) => any)> = {}> = {
  349. [key in keyof T]: () => T[key] extends (store: any) => infer R ? R : T[key] extends keyof Store<Id, S, G, A> ? Store<Id, S, G, A>[T[key]] : never;
  350. };
  351. /**
  352. * For internal use **only**
  353. */
  354. export declare type _MapStateReturn<S extends StateTree, G extends _GettersTree<S> | {
  355. [key: string]: ComputedRef;
  356. }, Keys extends keyof S | keyof G = keyof S | keyof G> = {
  357. [key in Keys]: key extends keyof Store<string, S, G, {}> ? () => Store<string, S, G, {}>[key] : never;
  358. };
  359. /**
  360. * Allows using stores without the composition API (`setup()`) by generating an
  361. * object to be spread in the `computed` field of a component. It accepts a list
  362. * of store definitions.
  363. *
  364. * @example
  365. * ```js
  366. * export default {
  367. * computed: {
  368. * // other computed properties
  369. * ...mapStores(useUserStore, useCartStore)
  370. * },
  371. *
  372. * created() {
  373. * this.userStore // store with id "user"
  374. * this.cartStore // store with id "cart"
  375. * }
  376. * }
  377. * ```
  378. *
  379. * @param stores - list of stores to map to an object
  380. */
  381. export declare function mapStores<Stores extends any[]>(...stores: [...Stores]): _Spread<Stores>;
  382. /**
  383. * Interface to allow customizing map helpers. Extend this interface with the
  384. * following properties:
  385. *
  386. * - `suffix`: string. Affects the suffix of `mapStores()`, defaults to `Store`.
  387. */
  388. export declare interface MapStoresCustomization {
  389. }
  390. /**
  391. * Same as `mapState()` but creates computed setters as well so the state can be
  392. * modified. Differently from `mapState()`, only `state` properties can be
  393. * added.
  394. *
  395. * @param useStore - store to map from
  396. * @param keyMapper - object of state properties
  397. */
  398. export declare function mapWritableState<Id extends string, S extends StateTree, G, A, KeyMapper extends Record<string, _MapWritableStateKeys<S, G>>>(useStore: StoreDefinition<Id, S, G, A>, keyMapper: KeyMapper): _MapWritableStateObjectReturn<S, G, KeyMapper>;
  399. /**
  400. * Allows using state and getters from one store without using the composition
  401. * API (`setup()`) by generating an object to be spread in the `computed` field
  402. * of a component.
  403. *
  404. * @param useStore - store to map from
  405. * @param keys - array of state properties
  406. */
  407. export declare function mapWritableState<Id extends string, S extends StateTree, G, A, Keys extends _MapWritableStateKeys<S, G>>(useStore: StoreDefinition<Id, S, G, A>, keys: readonly Keys[]): Pick<_MapWritableStateReturn<S, G, Keys>, Keys>;
  408. /**
  409. * For internal use **only**
  410. */
  411. declare type _MapWritableStateKeys<S extends StateTree, G> = keyof UnwrapRef<S> | keyof _StoreWithGetters_Writable<G>;
  412. /**
  413. * For internal use **only**
  414. */
  415. export declare type _MapWritableStateObjectReturn<S extends StateTree, G, KeyMapper extends Record<string, _MapWritableStateKeys<S, G>>> = {
  416. [key in keyof KeyMapper]: {
  417. get: () => UnwrapRef<(S & G)[KeyMapper[key]]>;
  418. set: (value: UnwrapRef<(S & G)[KeyMapper[key]]>) => any;
  419. };
  420. };
  421. /**
  422. * For internal use **only**
  423. */
  424. export declare type _MapWritableStateReturn<S extends StateTree, G, Keys extends _MapWritableStateKeys<S, G>> = {
  425. [key in Keys]: {
  426. get: () => UnwrapRef<(S & G)[key]>;
  427. set: (value: UnwrapRef<(S & G)[key]>) => any;
  428. };
  429. };
  430. /**
  431. * Generic type for a function that can infer arguments and return type
  432. *
  433. * For internal use **only**
  434. */
  435. export declare type _Method = (...args: any[]) => any;
  436. /**
  437. * Possible types for SubscriptionCallback
  438. */
  439. export declare enum MutationType {
  440. /**
  441. * Direct mutation of the state:
  442. *
  443. * - `store.name = 'new name'`
  444. * - `store.$state.name = 'new name'`
  445. * - `store.list.push('new item')`
  446. */
  447. direct = "direct",
  448. /**
  449. * Mutated the state with `$patch` and an object
  450. *
  451. * - `store.$patch({ name: 'newName' })`
  452. */
  453. patchObject = "patch object",
  454. /**
  455. * Mutated the state with `$patch` and a function
  456. *
  457. * - `store.$patch(state => state.name = 'newName')`
  458. */
  459. patchFunction = "patch function"
  460. }
  461. /**
  462. * Every application must own its own pinia to be able to create stores
  463. */
  464. export declare interface Pinia {
  465. install: (app: App) => void;
  466. /**
  467. * root state
  468. */
  469. state: Ref<Record<string, StateTree>>;
  470. /**
  471. * Adds a store plugin to extend every store
  472. *
  473. * @param plugin - store plugin to add
  474. */
  475. use(plugin: PiniaPlugin): Pinia;
  476. /* Excluded from this release type: _p */
  477. /* Excluded from this release type: _a */
  478. /* Excluded from this release type: _e */
  479. /* Excluded from this release type: _s */
  480. /* Excluded from this release type: _testing */
  481. }
  482. /**
  483. * Interface to be extended by the user when they add properties through plugins.
  484. */
  485. export declare interface PiniaCustomProperties<Id extends string = string, S extends StateTree = StateTree, G = _GettersTree<S>, A = _ActionsTree> {
  486. }
  487. /**
  488. * Properties that are added to every `store.$state` by `pinia.use()`.
  489. */
  490. export declare interface PiniaCustomStateProperties<S extends StateTree = StateTree> {
  491. }
  492. /**
  493. * Plugin to extend every store.
  494. */
  495. export declare interface PiniaPlugin {
  496. /**
  497. * Plugin to extend every store. Returns an object to extend the store or
  498. * nothing.
  499. *
  500. * @param context - Context
  501. */
  502. (context: PiniaPluginContext): Partial<PiniaCustomProperties & PiniaCustomStateProperties> | void;
  503. }
  504. /**
  505. * Context argument passed to Pinia plugins.
  506. */
  507. export declare interface PiniaPluginContext<Id extends string = string, S extends StateTree = StateTree, G = _GettersTree<S>, A = _ActionsTree> {
  508. /**
  509. * pinia instance.
  510. */
  511. pinia: Pinia;
  512. /**
  513. * Current app created with `Vue.createApp()`.
  514. */
  515. app: App;
  516. /**
  517. * Current store being extended.
  518. */
  519. store: Store<Id, S, G, A>;
  520. /**
  521. * Initial options defining the store when calling `defineStore()`.
  522. */
  523. options: DefineStoreOptionsInPlugin<Id, S, G, A>;
  524. }
  525. /**
  526. * Plugin to extend every store.
  527. * @deprecated use PiniaPlugin instead
  528. */
  529. export declare type PiniaStorePlugin = PiniaPlugin;
  530. /**
  531. * Vue 2 Plugin that must be installed for pinia to work. Note **you don't need
  532. * this plugin if you are using Nuxt.js**. Use the `buildModule` instead:
  533. * https://pinia.vuejs.org/ssr/nuxt.html.
  534. *
  535. * @example
  536. * ```js
  537. * import Vue from 'vue'
  538. * import { PiniaVuePlugin, createPinia } from 'pinia'
  539. *
  540. * Vue.use(PiniaVuePlugin)
  541. * const pinia = createPinia()
  542. *
  543. * new Vue({
  544. * el: '#app',
  545. * // ...
  546. * pinia,
  547. * })
  548. * ```
  549. *
  550. * @param _Vue - `Vue` imported from 'vue'.
  551. */
  552. export declare const PiniaVuePlugin: Plugin_2;
  553. declare interface _SetActivePinia {
  554. (pinia: Pinia): Pinia;
  555. (pinia: undefined): undefined;
  556. (pinia: Pinia | undefined): Pinia | undefined;
  557. }
  558. /**
  559. * Sets or unsets the active pinia. Used in SSR and internally when calling
  560. * actions and getters
  561. *
  562. * @param pinia - Pinia instance
  563. */
  564. export declare const setActivePinia: _SetActivePinia;
  565. /**
  566. * Changes the suffix added by `mapStores()`. Can be set to an empty string.
  567. * Defaults to `"Store"`. Make sure to extend the MapStoresCustomization
  568. * interface if you are using TypeScript.
  569. *
  570. * @param suffix - new suffix
  571. */
  572. export declare function setMapStoreSuffix(suffix: MapStoresCustomization extends Record<'suffix', infer Suffix> ? Suffix : string): void;
  573. /**
  574. * Return type of `defineStore()` with a setup function.
  575. * - `Id` is a string literal of the store's name
  576. * - `SS` is the return type of the setup function
  577. * @see {@link StoreDefinition}
  578. */
  579. export declare interface SetupStoreDefinition<Id extends string, SS> extends StoreDefinition<Id, _ExtractStateFromSetupStore<SS>, _ExtractGettersFromSetupStore<SS>, _ExtractActionsFromSetupStore<SS>> {
  580. }
  581. declare interface SetupStoreHelpers {
  582. action: <Fn extends _Method>(fn: Fn) => Fn;
  583. }
  584. /**
  585. * Returns whether a value should be hydrated
  586. *
  587. * @param obj - target variable
  588. * @returns true if `obj` should be hydrated
  589. */
  590. export declare function shouldHydrate(obj: any): boolean;
  591. /**
  592. * Tells Pinia to skip the hydration process of a given object. This is useful in setup stores (only) when you return a
  593. * stateful object in the store but it isn't really state. e.g. returning a router instance in a setup store.
  594. *
  595. * @param obj - target object
  596. * @returns obj
  597. */
  598. export declare function skipHydrate<T = any>(obj: T): T;
  599. /**
  600. * For internal use **only**.
  601. */
  602. export declare type _Spread<A extends readonly any[]> = A extends [infer L, ...infer R] ? _StoreObject<L> & _Spread<R> : unknown;
  603. /**
  604. * Generic state of a Store
  605. */
  606. export declare type StateTree = Record<PropertyKey, any>;
  607. /**
  608. * Store type to build a store.
  609. */
  610. export declare type Store<Id extends string = string, S extends StateTree = {}, G = {}, A = {}> = _StoreWithState<Id, S, G, A> & UnwrapRef<S> & _StoreWithGetters<G> & (_ActionsTree extends A ? {} : A) & PiniaCustomProperties<Id, S, G, A> & PiniaCustomStateProperties<S>;
  611. /**
  612. * Extract the actions of a store type. Works with both a Setup Store or an
  613. * Options Store.
  614. */
  615. export declare type StoreActions<SS> = SS extends Store<string, StateTree, _GettersTree<StateTree>, infer A> ? A : _ExtractActionsFromSetupStore<SS>;
  616. /**
  617. * Return type of `defineStore()`. Function that allows instantiating a store.
  618. */
  619. export declare interface StoreDefinition<Id extends string = string, S extends StateTree = StateTree, G = _GettersTree<S>, A = _ActionsTree> {
  620. /**
  621. * Returns a store, creates it if necessary.
  622. *
  623. * @param pinia - Pinia instance to retrieve the store
  624. * @param hot - dev only hot module replacement
  625. */
  626. (pinia?: Pinia | null | undefined, hot?: StoreGeneric): Store<Id, S, G, A>;
  627. /**
  628. * Id of the store. Used by map helpers.
  629. */
  630. $id: Id;
  631. /* Excluded from this release type: _pinia */
  632. }
  633. /**
  634. * Generic and type-unsafe version of Store. Doesn't fail on access with
  635. * strings, making it much easier to write generic functions that do not care
  636. * about the kind of store that is passed.
  637. */
  638. export declare type StoreGeneric = Store<string, StateTree, _GettersTree<StateTree>, _ActionsTree>;
  639. /**
  640. * Extract the getters of a store type. Works with both a Setup Store or an
  641. * Options Store.
  642. */
  643. export declare type StoreGetters<SS> = SS extends Store<string, StateTree, infer G, _ActionsTree> ? _StoreWithGetters<G> : _ExtractGettersFromSetupStore<SS>;
  644. /**
  645. * For internal use **only**.
  646. */
  647. export declare type _StoreObject<S> = S extends StoreDefinition<infer Ids, infer State, infer Getters, infer Actions> ? {
  648. [Id in `${Ids}${MapStoresCustomization extends Record<'suffix', infer Suffix> ? Suffix : 'Store'}`]: () => Store<Id extends `${infer RealId}${MapStoresCustomization extends Record<'suffix', infer Suffix> ? Suffix : 'Store'}` ? RealId : string, State, Getters, Actions>;
  649. } : {};
  650. /**
  651. * Argument of `store.$onAction()`
  652. */
  653. export declare type StoreOnActionListener<Id extends string, S extends StateTree, G, A> = (context: StoreOnActionListenerContext<Id, S, G, {} extends A ? _ActionsTree : A>) => void;
  654. /**
  655. * Context object passed to callbacks of `store.$onAction(context => {})`
  656. * TODO: should have only the Id, the Store and Actions to generate the proper object
  657. */
  658. export declare type StoreOnActionListenerContext<Id extends string, S extends StateTree, G, A> = _ActionsTree extends A ? _StoreOnActionListenerContext<StoreGeneric, string, _ActionsTree> : {
  659. [Name in keyof A]: Name extends string ? _StoreOnActionListenerContext<Store<Id, S, G, A>, Name, A> : never;
  660. }[keyof A];
  661. /**
  662. * Actual type for {@link StoreOnActionListenerContext}. Exists for refactoring
  663. * purposes. For internal use only.
  664. * For internal use **only**
  665. */
  666. export declare interface _StoreOnActionListenerContext<Store, ActionName extends string, A> {
  667. /**
  668. * Name of the action
  669. */
  670. name: ActionName;
  671. /**
  672. * Store that is invoking the action
  673. */
  674. store: Store;
  675. /**
  676. * Parameters passed to the action
  677. */
  678. args: A extends Record<ActionName, _Method> ? Parameters<A[ActionName]> : unknown[];
  679. /**
  680. * Sets up a hook once the action is finished. It receives the return value
  681. * of the action, if it's a Promise, it will be unwrapped.
  682. */
  683. after: (callback: A extends Record<ActionName, _Method> ? (resolvedReturn: _Awaited<ReturnType<A[ActionName]>>) => void : () => void) => void;
  684. /**
  685. * Sets up a hook if the action fails. Return `false` to catch the error and
  686. * stop it from propagating.
  687. */
  688. onError: (callback: (error: unknown) => void) => void;
  689. }
  690. /**
  691. * Properties of a store.
  692. */
  693. export declare interface StoreProperties<Id extends string> {
  694. /**
  695. * Unique identifier of the store
  696. */
  697. $id: Id;
  698. /* Excluded from this release type: _p */
  699. /* Excluded from this release type: _getters */
  700. /* Excluded from this release type: _isOptionsAPI */
  701. /**
  702. * Used by devtools plugin to retrieve properties added with plugins. Removed
  703. * in production. Can be used by the user to add property keys of the store
  704. * that should be displayed in devtools.
  705. */
  706. _customProperties: Set<string>;
  707. /* Excluded from this release type: _hotUpdate */
  708. /* Excluded from this release type: _hotUpdating */
  709. /* Excluded from this release type: _hmrPayload */
  710. }
  711. /**
  712. * Extract the state of a store type. Works with both a Setup Store or an
  713. * Options Store. Note this unwraps refs.
  714. */
  715. export declare type StoreState<SS> = SS extends Store<string, infer S, _GettersTree<StateTree>, _ActionsTree> ? UnwrapRef<S> : _ExtractStateFromSetupStore<SS>;
  716. /**
  717. * Extracts the return type for `storeToRefs`.
  718. * Will convert any `getters` into `ComputedRef`.
  719. */
  720. declare type StoreToRefs<SS extends StoreGeneric> = SS extends unknown ? _ToStateRefs<SS> & ToRefs<PiniaCustomStateProperties<StoreState<SS>>> & _ToComputedRefs<StoreGetters<SS>> : never;
  721. /**
  722. * Creates an object of references with all the state, getters, and plugin-added
  723. * state properties of the store. Similar to `toRefs()` but specifically
  724. * designed for Pinia stores so methods and non reactive properties are
  725. * completely ignored.
  726. *
  727. * @param store - store to extract the refs from
  728. */
  729. export declare function storeToRefs<SS extends StoreGeneric>(store: SS): StoreToRefs<SS>;
  730. /**
  731. * Store augmented for actions. For internal usage only.
  732. * For internal use **only**
  733. */
  734. export declare type _StoreWithActions<A> = {
  735. [k in keyof A]: A[k] extends (...args: infer P) => infer R ? (...args: P) => R : never;
  736. };
  737. /**
  738. * Store augmented with getters. For internal usage only.
  739. * For internal use **only**
  740. */
  741. export declare type _StoreWithGetters<G> = _StoreWithGetters_Readonly<G> & _StoreWithGetters_Writable<G>;
  742. /**
  743. * Store augmented with readonly getters. For internal usage **only**.
  744. */
  745. declare type _StoreWithGetters_Readonly<G> = {
  746. readonly [K in keyof G as G[K] extends (...args: any[]) => any ? K : ComputedRef extends G[K] ? K : never]: G[K] extends (...args: any[]) => infer R ? R : UnwrapRef<G[K]>;
  747. };
  748. /**
  749. * Store augmented with writable getters. For internal usage **only**.
  750. */
  751. declare type _StoreWithGetters_Writable<G> = {
  752. [K in keyof G as G[K] extends WritableComputedRef<any> ? K : never]: G[K] extends WritableComputedRef<infer R, infer _S> ? R : never;
  753. };
  754. /**
  755. * Base store with state and functions. Should not be used directly.
  756. */
  757. export declare interface _StoreWithState<Id extends string, S extends StateTree, G, A> extends StoreProperties<Id> {
  758. /**
  759. * State of the Store. Setting it will internally call `$patch()` to update the state.
  760. */
  761. $state: UnwrapRef<S> & PiniaCustomStateProperties<S>;
  762. /**
  763. * Applies a state patch to current state. Allows passing nested values
  764. *
  765. * @param partialState - patch to apply to the state
  766. */
  767. $patch(partialState: _DeepPartial<UnwrapRef<S>>): void;
  768. /**
  769. * Group multiple changes into one function. Useful when mutating objects like
  770. * Sets or arrays and applying an object patch isn't practical, e.g. appending
  771. * to an array. The function passed to `$patch()` **must be synchronous**.
  772. *
  773. * @param stateMutator - function that mutates `state`, cannot be asynchronous
  774. */
  775. $patch<F extends (state: UnwrapRef<S>) => any>(stateMutator: ReturnType<F> extends Promise<any> ? never : F): void;
  776. /**
  777. * Resets the store to its initial state by building a new state object.
  778. */
  779. $reset(): void;
  780. /**
  781. * Setups a callback to be called whenever the state changes. It also returns a function to remove the callback. Note
  782. * that when calling `store.$subscribe()` inside of a component, it will be automatically cleaned up when the
  783. * component gets unmounted unless `detached` is set to true.
  784. *
  785. * @param callback - callback passed to the watcher
  786. * @param options - `watch` options + `detached` to detach the subscription from the context (usually a component)
  787. * this is called from. Note that the `flush` option does not affect calls to `store.$patch()`.
  788. * @returns function that removes the watcher
  789. */
  790. $subscribe(callback: SubscriptionCallback<S>, options?: {
  791. detached?: boolean;
  792. } & WatchOptions): () => void;
  793. /**
  794. * Setups a callback to be called every time an action is about to get
  795. * invoked. The callback receives an object with all the relevant information
  796. * of the invoked action:
  797. * - `store`: the store it is invoked on
  798. * - `name`: The name of the action
  799. * - `args`: The parameters passed to the action
  800. *
  801. * On top of these, it receives two functions that allow setting up a callback
  802. * once the action finishes or when it fails.
  803. *
  804. * It also returns a function to remove the callback. Note than when calling
  805. * `store.$onAction()` inside of a component, it will be automatically cleaned
  806. * up when the component gets unmounted unless `detached` is set to true.
  807. *
  808. * @example
  809. *
  810. *```js
  811. *store.$onAction(({ after, onError }) => {
  812. * // Here you could share variables between all of the hooks as well as
  813. * // setting up watchers and clean them up
  814. * after((resolvedValue) => {
  815. * // can be used to cleanup side effects
  816. * . // `resolvedValue` is the value returned by the action, if it's a
  817. * . // Promise, it will be the resolved value instead of the Promise
  818. * })
  819. * onError((error) => {
  820. * // can be used to pass up errors
  821. * })
  822. *})
  823. *```
  824. *
  825. * @param callback - callback called before every action
  826. * @param detached - detach the subscription from the context this is called from
  827. * @returns function that removes the watcher
  828. */
  829. $onAction(callback: StoreOnActionListener<Id, S, G, A>, detached?: boolean): () => void;
  830. /**
  831. * Stops the associated effect scope of the store and remove it from the store
  832. * registry. Plugins can override this method to cleanup any added effects.
  833. * e.g. devtools plugin stops displaying disposed stores from devtools.
  834. * Note this doesn't delete the state of the store, you have to do it manually with
  835. * `delete pinia.state.value[store.$id]` if you want to. If you don't and the
  836. * store is used again, it will reuse the previous state.
  837. */
  838. $dispose(): void;
  839. /* Excluded from this release type: _r */
  840. }
  841. /**
  842. * Callback of a subscription
  843. */
  844. export declare type SubscriptionCallback<S> = (
  845. /**
  846. * Object with information relative to the store mutation that triggered the
  847. * subscription.
  848. */
  849. mutation: SubscriptionCallbackMutation<S>,
  850. /**
  851. * State of the store when the subscription is triggered. Same as
  852. * `store.$state`.
  853. */
  854. state: UnwrapRef<S>) => void;
  855. /**
  856. * Context object passed to a subscription callback.
  857. */
  858. export declare type SubscriptionCallbackMutation<S> = SubscriptionCallbackMutationDirect | SubscriptionCallbackMutationPatchObject<S> | SubscriptionCallbackMutationPatchFunction;
  859. /**
  860. * Base type for the context passed to a subscription callback. Internal type.
  861. */
  862. export declare interface _SubscriptionCallbackMutationBase {
  863. /**
  864. * Type of the mutation.
  865. */
  866. type: MutationType;
  867. /**
  868. * `id` of the store doing the mutation.
  869. */
  870. storeId: string;
  871. /**
  872. * 🔴 DEV ONLY, DO NOT use for production code. Different mutation calls. Comes from
  873. * https://vuejs.org/guide/extras/reactivity-in-depth.html#reactivity-debugging and allows to track mutations in
  874. * devtools and plugins **during development only**.
  875. */
  876. events?: DebuggerEvent[] | DebuggerEvent;
  877. }
  878. /**
  879. * Context passed to a subscription callback when directly mutating the state of
  880. * a store with `store.someState = newValue` or `store.$state.someState =
  881. * newValue`.
  882. */
  883. export declare interface SubscriptionCallbackMutationDirect extends _SubscriptionCallbackMutationBase {
  884. type: MutationType.direct;
  885. events: DebuggerEvent;
  886. }
  887. /**
  888. * Context passed to a subscription callback when `store.$patch()` is called
  889. * with a function.
  890. */
  891. export declare interface SubscriptionCallbackMutationPatchFunction extends _SubscriptionCallbackMutationBase {
  892. type: MutationType.patchFunction;
  893. events: DebuggerEvent[];
  894. }
  895. /**
  896. * Context passed to a subscription callback when `store.$patch()` is called
  897. * with an object.
  898. */
  899. export declare interface SubscriptionCallbackMutationPatchObject<S> extends _SubscriptionCallbackMutationBase {
  900. type: MutationType.patchObject;
  901. events: DebuggerEvent[];
  902. /**
  903. * Object passed to `store.$patch()`.
  904. */
  905. payload: _DeepPartial<UnwrapRef<S>>;
  906. }
  907. /**
  908. * Extracts the getters of a store while keeping writable and readonly properties. **Internal type DO NOT USE**.
  909. */
  910. declare type _ToComputedRefs<SS> = {
  911. [K in keyof SS]: true extends _IsReadonly<SS, K> ? ComputedRef<SS[K]> : WritableComputedRef<SS[K]>;
  912. };
  913. /**
  914. * Extracts the refs of a state object from a store. If the state value is a Ref or type that extends ref, it will be kept as is.
  915. * Otherwise, it will be converted into a Ref. **Internal type DO NOT USE**.
  916. */
  917. declare type _ToStateRefs<SS> = SS extends Store<string, infer UnwrappedState, _GettersTree<StateTree>, _ActionsTree> ? UnwrappedState extends _UnwrapAll<Pick<infer State, infer Key>> ? {
  918. [K in Key]: ToRef<State[K]>;
  919. } : ToRefs<UnwrappedState> : ToRefs<StoreState<SS>>;
  920. /**
  921. * Type that enables refactoring through IDE.
  922. * For internal use **only**
  923. */
  924. export declare type _UnwrapAll<SS> = {
  925. [K in keyof SS]: UnwrapRef<SS[K]>;
  926. };
  927. export { }
  928. // Extensions of Vue types to be appended manually
  929. // https://github.com/microsoft/rushstack/issues/2090
  930. // https://github.com/microsoft/rushstack/issues/1709
  931. // @ts-ignore: works on Vue 2, fails in Vue 3
  932. declare module 'vue/types/vue' {
  933. interface Vue {
  934. /**
  935. * Currently installed pinia instance.
  936. */
  937. $pinia: Pinia
  938. /**
  939. * Cache of stores instantiated by the current instance. Used by map
  940. * helpers. Used internally by Pinia.
  941. *
  942. * @internal
  943. */
  944. _pStores?: Record<string, Store>
  945. }
  946. }
  947. // @ts-ignore: works on Vue 2, fails in Vue 3
  948. declare module 'vue/types/options' {
  949. interface ComponentOptions<V> {
  950. /**
  951. * Pinia instance to install in your application. Should be passed to the
  952. * root Vue.
  953. */
  954. pinia?: Pinia
  955. }
  956. }
  957. /**
  958. * NOTE: Used to be `@vue/runtime-core` but it break types from time to time. Then, in Vue docs, we started recommending
  959. * to use `vue` instead of `@vue/runtime-core` but that broke others' types so we reverted it. Now, local types do not
  960. * work if we use `@vue/runtime-core` so we are using `vue` again.
  961. */
  962. // @ts-ignore: works on Vue 3, fails in Vue 2
  963. declare module 'vue' {
  964. // This seems to be needed to not break auto import types based on the order
  965. // https://github.com/vuejs/pinia/pull/2730
  966. interface GlobalComponents {}
  967. interface ComponentCustomProperties {
  968. /**
  969. * Access to the application's Pinia
  970. */
  971. $pinia: Pinia
  972. /**
  973. * Cache of stores instantiated by the current instance. Used by devtools to
  974. * list currently used stores. Used internally by Pinia.
  975. *
  976. * @internal
  977. */
  978. _pStores?: Record<string, StoreGeneric>
  979. }
  980. }
  981. // normally this is only needed in .d.ts files
  982. export {}