pinia.d.ts 36 KB

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