pinia.mjs 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941
  1. /*!
  2. * pinia v3.0.4
  3. * (c) 2025 Eduardo San Martin Morote
  4. * @license MIT
  5. */
  6. import { hasInjectionContext, inject, toRaw, watch, unref, markRaw, effectScope, ref, isRef, isReactive, getCurrentScope, onScopeDispose, getCurrentInstance, reactive, toRef, nextTick, computed, toRefs } from 'vue';
  7. import { setupDevtoolsPlugin } from '@vue/devtools-api';
  8. const IS_CLIENT = typeof window !== 'undefined';
  9. /**
  10. * setActivePinia must be called to handle SSR at the top of functions like
  11. * `fetch`, `setup`, `serverPrefetch` and others
  12. */
  13. let activePinia;
  14. /**
  15. * Sets or unsets the active pinia. Used in SSR and internally when calling
  16. * actions and getters
  17. *
  18. * @param pinia - Pinia instance
  19. */
  20. // @ts-expect-error: cannot constrain the type of the return
  21. const setActivePinia = (pinia) => (activePinia = pinia);
  22. /**
  23. * Get the currently active pinia if there is any.
  24. */
  25. const getActivePinia = (process.env.NODE_ENV !== 'production')
  26. ? () => {
  27. const pinia = hasInjectionContext() && inject(piniaSymbol);
  28. if (!pinia && !IS_CLIENT) {
  29. console.error(`[🍍]: Pinia instance not found in context. This falls back to the global activePinia which exposes you to cross-request pollution on the server. Most of the time, it means you are calling "useStore()" in the wrong place.\n` +
  30. `Read https://vuejs.org/guide/reusability/composables.html to learn more`);
  31. }
  32. return pinia || activePinia;
  33. }
  34. : () => (hasInjectionContext() && inject(piniaSymbol)) || activePinia;
  35. const piniaSymbol = ((process.env.NODE_ENV !== 'production') ? Symbol('pinia') : /* istanbul ignore next */ Symbol());
  36. function isPlainObject(
  37. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  38. o) {
  39. return (o &&
  40. typeof o === 'object' &&
  41. Object.prototype.toString.call(o) === '[object Object]' &&
  42. typeof o.toJSON !== 'function');
  43. }
  44. // type DeepReadonly<T> = { readonly [P in keyof T]: DeepReadonly<T[P]> }
  45. // TODO: can we change these to numbers?
  46. /**
  47. * Possible types for SubscriptionCallback
  48. */
  49. var MutationType;
  50. (function (MutationType) {
  51. /**
  52. * Direct mutation of the state:
  53. *
  54. * - `store.name = 'new name'`
  55. * - `store.$state.name = 'new name'`
  56. * - `store.list.push('new item')`
  57. */
  58. MutationType["direct"] = "direct";
  59. /**
  60. * Mutated the state with `$patch` and an object
  61. *
  62. * - `store.$patch({ name: 'newName' })`
  63. */
  64. MutationType["patchObject"] = "patch object";
  65. /**
  66. * Mutated the state with `$patch` and a function
  67. *
  68. * - `store.$patch(state => state.name = 'newName')`
  69. */
  70. MutationType["patchFunction"] = "patch function";
  71. // maybe reset? for $state = {} and $reset
  72. })(MutationType || (MutationType = {}));
  73. /*
  74. * FileSaver.js A saveAs() FileSaver implementation.
  75. *
  76. * Originally by Eli Grey, adapted as an ESM module by Eduardo San Martin
  77. * Morote.
  78. *
  79. * License : MIT
  80. */
  81. // The one and only way of getting global scope in all environments
  82. // https://stackoverflow.com/q/3277182/1008999
  83. const _global = /*#__PURE__*/ (() => typeof window === 'object' && window.window === window
  84. ? window
  85. : typeof self === 'object' && self.self === self
  86. ? self
  87. : typeof global === 'object' && global.global === global
  88. ? global
  89. : typeof globalThis === 'object'
  90. ? globalThis
  91. : { HTMLElement: null })();
  92. function bom(blob, { autoBom = false } = {}) {
  93. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  94. // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
  95. if (autoBom &&
  96. /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  97. return new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
  98. }
  99. return blob;
  100. }
  101. function download(url, name, opts) {
  102. const xhr = new XMLHttpRequest();
  103. xhr.open('GET', url);
  104. xhr.responseType = 'blob';
  105. xhr.onload = function () {
  106. saveAs(xhr.response, name, opts);
  107. };
  108. xhr.onerror = function () {
  109. console.error('could not download file');
  110. };
  111. xhr.send();
  112. }
  113. function corsEnabled(url) {
  114. const xhr = new XMLHttpRequest();
  115. // use sync to avoid popup blocker
  116. xhr.open('HEAD', url, false);
  117. try {
  118. xhr.send();
  119. }
  120. catch (e) { }
  121. return xhr.status >= 200 && xhr.status <= 299;
  122. }
  123. // `a.click()` doesn't work for all browsers (#465)
  124. function click(node) {
  125. try {
  126. node.dispatchEvent(new MouseEvent('click'));
  127. }
  128. catch (e) {
  129. const evt = new MouseEvent('click', {
  130. bubbles: true,
  131. cancelable: true,
  132. view: window,
  133. detail: 0,
  134. screenX: 80,
  135. screenY: 20,
  136. clientX: 80,
  137. clientY: 20,
  138. ctrlKey: false,
  139. altKey: false,
  140. shiftKey: false,
  141. metaKey: false,
  142. button: 0,
  143. relatedTarget: null,
  144. });
  145. node.dispatchEvent(evt);
  146. }
  147. }
  148. const _navigator = typeof navigator === 'object' ? navigator : { userAgent: '' };
  149. // Detect WebView inside a native macOS app by ruling out all browsers
  150. // We just need to check for 'Safari' because all other browsers (besides Firefox) include that too
  151. // https://www.whatismybrowser.com/guides/the-latest-user-agent/macos
  152. const isMacOSWebView = /*#__PURE__*/ (() => /Macintosh/.test(_navigator.userAgent) &&
  153. /AppleWebKit/.test(_navigator.userAgent) &&
  154. !/Safari/.test(_navigator.userAgent))();
  155. const saveAs = !IS_CLIENT
  156. ? () => { } // noop
  157. : // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program
  158. typeof HTMLAnchorElement !== 'undefined' &&
  159. 'download' in HTMLAnchorElement.prototype &&
  160. !isMacOSWebView
  161. ? downloadSaveAs
  162. : // Use msSaveOrOpenBlob as a second approach
  163. 'msSaveOrOpenBlob' in _navigator
  164. ? msSaveAs
  165. : // Fallback to using FileReader and a popup
  166. fileSaverSaveAs;
  167. function downloadSaveAs(blob, name = 'download', opts) {
  168. const a = document.createElement('a');
  169. a.download = name;
  170. a.rel = 'noopener'; // tabnabbing
  171. // TODO: detect chrome extensions & packaged apps
  172. // a.target = '_blank'
  173. if (typeof blob === 'string') {
  174. // Support regular links
  175. a.href = blob;
  176. if (a.origin !== location.origin) {
  177. if (corsEnabled(a.href)) {
  178. download(blob, name, opts);
  179. }
  180. else {
  181. a.target = '_blank';
  182. click(a);
  183. }
  184. }
  185. else {
  186. click(a);
  187. }
  188. }
  189. else {
  190. // Support blobs
  191. a.href = URL.createObjectURL(blob);
  192. setTimeout(function () {
  193. URL.revokeObjectURL(a.href);
  194. }, 4e4); // 40s
  195. setTimeout(function () {
  196. click(a);
  197. }, 0);
  198. }
  199. }
  200. function msSaveAs(blob, name = 'download', opts) {
  201. if (typeof blob === 'string') {
  202. if (corsEnabled(blob)) {
  203. download(blob, name, opts);
  204. }
  205. else {
  206. const a = document.createElement('a');
  207. a.href = blob;
  208. a.target = '_blank';
  209. setTimeout(function () {
  210. click(a);
  211. });
  212. }
  213. }
  214. else {
  215. // @ts-ignore: works on windows
  216. navigator.msSaveOrOpenBlob(bom(blob, opts), name);
  217. }
  218. }
  219. function fileSaverSaveAs(blob, name, opts, popup) {
  220. // Open a popup immediately do go around popup blocker
  221. // Mostly only available on user interaction and the fileReader is async so...
  222. popup = popup || open('', '_blank');
  223. if (popup) {
  224. popup.document.title = popup.document.body.innerText = 'downloading...';
  225. }
  226. if (typeof blob === 'string')
  227. return download(blob, name, opts);
  228. const force = blob.type === 'application/octet-stream';
  229. const isSafari = /constructor/i.test(String(_global.HTMLElement)) || 'safari' in _global;
  230. const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
  231. if ((isChromeIOS || (force && isSafari) || isMacOSWebView) &&
  232. typeof FileReader !== 'undefined') {
  233. // Safari doesn't allow downloading of blob URLs
  234. const reader = new FileReader();
  235. reader.onloadend = function () {
  236. let url = reader.result;
  237. if (typeof url !== 'string') {
  238. popup = null;
  239. throw new Error('Wrong reader.result type');
  240. }
  241. url = isChromeIOS
  242. ? url
  243. : url.replace(/^data:[^;]*;/, 'data:attachment/file;');
  244. if (popup) {
  245. popup.location.href = url;
  246. }
  247. else {
  248. location.assign(url);
  249. }
  250. popup = null; // reverse-tabnabbing #460
  251. };
  252. reader.readAsDataURL(blob);
  253. }
  254. else {
  255. const url = URL.createObjectURL(blob);
  256. if (popup)
  257. popup.location.assign(url);
  258. else
  259. location.href = url;
  260. popup = null; // reverse-tabnabbing #460
  261. setTimeout(function () {
  262. URL.revokeObjectURL(url);
  263. }, 4e4); // 40s
  264. }
  265. }
  266. /**
  267. * Shows a toast or console.log
  268. *
  269. * @param message - message to log
  270. * @param type - different color of the tooltip
  271. */
  272. function toastMessage(message, type) {
  273. const piniaMessage = '🍍 ' + message;
  274. if (typeof __VUE_DEVTOOLS_TOAST__ === 'function') {
  275. // No longer available :(
  276. __VUE_DEVTOOLS_TOAST__(piniaMessage, type);
  277. }
  278. else if (type === 'error') {
  279. console.error(piniaMessage);
  280. }
  281. else if (type === 'warn') {
  282. console.warn(piniaMessage);
  283. }
  284. else {
  285. console.log(piniaMessage);
  286. }
  287. }
  288. function isPinia(o) {
  289. return '_a' in o && 'install' in o;
  290. }
  291. /**
  292. * This file contain devtools actions, they are not Pinia actions.
  293. */
  294. // ---
  295. function checkClipboardAccess() {
  296. if (!('clipboard' in navigator)) {
  297. toastMessage(`Your browser doesn't support the Clipboard API`, 'error');
  298. return true;
  299. }
  300. }
  301. function checkNotFocusedError(error) {
  302. if (error instanceof Error &&
  303. error.message.toLowerCase().includes('document is not focused')) {
  304. toastMessage('You need to activate the "Emulate a focused page" setting in the "Rendering" panel of devtools.', 'warn');
  305. return true;
  306. }
  307. return false;
  308. }
  309. async function actionGlobalCopyState(pinia) {
  310. if (checkClipboardAccess())
  311. return;
  312. try {
  313. await navigator.clipboard.writeText(JSON.stringify(pinia.state.value));
  314. toastMessage('Global state copied to clipboard.');
  315. }
  316. catch (error) {
  317. if (checkNotFocusedError(error))
  318. return;
  319. toastMessage(`Failed to serialize the state. Check the console for more details.`, 'error');
  320. console.error(error);
  321. }
  322. }
  323. async function actionGlobalPasteState(pinia) {
  324. if (checkClipboardAccess())
  325. return;
  326. try {
  327. loadStoresState(pinia, JSON.parse(await navigator.clipboard.readText()));
  328. toastMessage('Global state pasted from clipboard.');
  329. }
  330. catch (error) {
  331. if (checkNotFocusedError(error))
  332. return;
  333. toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, 'error');
  334. console.error(error);
  335. }
  336. }
  337. async function actionGlobalSaveState(pinia) {
  338. try {
  339. saveAs(new Blob([JSON.stringify(pinia.state.value)], {
  340. type: 'text/plain;charset=utf-8',
  341. }), 'pinia-state.json');
  342. }
  343. catch (error) {
  344. toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error');
  345. console.error(error);
  346. }
  347. }
  348. let fileInput;
  349. function getFileOpener() {
  350. if (!fileInput) {
  351. fileInput = document.createElement('input');
  352. fileInput.type = 'file';
  353. fileInput.accept = '.json';
  354. }
  355. function openFile() {
  356. return new Promise((resolve, reject) => {
  357. fileInput.onchange = async () => {
  358. const files = fileInput.files;
  359. if (!files)
  360. return resolve(null);
  361. const file = files.item(0);
  362. if (!file)
  363. return resolve(null);
  364. return resolve({ text: await file.text(), file });
  365. };
  366. // @ts-ignore: TODO: changed from 4.3 to 4.4
  367. fileInput.oncancel = () => resolve(null);
  368. fileInput.onerror = reject;
  369. fileInput.click();
  370. });
  371. }
  372. return openFile;
  373. }
  374. async function actionGlobalOpenStateFile(pinia) {
  375. try {
  376. const open = getFileOpener();
  377. const result = await open();
  378. if (!result)
  379. return;
  380. const { text, file } = result;
  381. loadStoresState(pinia, JSON.parse(text));
  382. toastMessage(`Global state imported from "${file.name}".`);
  383. }
  384. catch (error) {
  385. toastMessage(`Failed to import the state from JSON. Check the console for more details.`, 'error');
  386. console.error(error);
  387. }
  388. }
  389. function loadStoresState(pinia, state) {
  390. for (const key in state) {
  391. const storeState = pinia.state.value[key];
  392. // store is already instantiated, patch it
  393. if (storeState) {
  394. Object.assign(storeState, state[key]);
  395. }
  396. else {
  397. // store is not instantiated, set the initial state
  398. pinia.state.value[key] = state[key];
  399. }
  400. }
  401. }
  402. function formatDisplay(display) {
  403. return {
  404. _custom: {
  405. display,
  406. },
  407. };
  408. }
  409. const PINIA_ROOT_LABEL = '🍍 Pinia (root)';
  410. const PINIA_ROOT_ID = '_root';
  411. function formatStoreForInspectorTree(store) {
  412. return isPinia(store)
  413. ? {
  414. id: PINIA_ROOT_ID,
  415. label: PINIA_ROOT_LABEL,
  416. }
  417. : {
  418. id: store.$id,
  419. label: store.$id,
  420. };
  421. }
  422. function formatStoreForInspectorState(store) {
  423. if (isPinia(store)) {
  424. const storeNames = Array.from(store._s.keys());
  425. const storeMap = store._s;
  426. const state = {
  427. state: storeNames.map((storeId) => ({
  428. editable: true,
  429. key: storeId,
  430. value: store.state.value[storeId],
  431. })),
  432. getters: storeNames
  433. .filter((id) => storeMap.get(id)._getters)
  434. .map((id) => {
  435. const store = storeMap.get(id);
  436. return {
  437. editable: false,
  438. key: id,
  439. value: store._getters.reduce((getters, key) => {
  440. getters[key] = store[key];
  441. return getters;
  442. }, {}),
  443. };
  444. }),
  445. };
  446. return state;
  447. }
  448. const state = {
  449. state: Object.keys(store.$state).map((key) => ({
  450. editable: true,
  451. key,
  452. value: store.$state[key],
  453. })),
  454. };
  455. // avoid adding empty getters
  456. if (store._getters && store._getters.length) {
  457. state.getters = store._getters.map((getterName) => ({
  458. editable: false,
  459. key: getterName,
  460. value: store[getterName],
  461. }));
  462. }
  463. if (store._customProperties.size) {
  464. state.customProperties = Array.from(store._customProperties).map((key) => ({
  465. editable: true,
  466. key,
  467. value: store[key],
  468. }));
  469. }
  470. return state;
  471. }
  472. function formatEventData(events) {
  473. if (!events)
  474. return {};
  475. if (Array.isArray(events)) {
  476. // TODO: handle add and delete for arrays and objects
  477. return events.reduce((data, event) => {
  478. data.keys.push(event.key);
  479. data.operations.push(event.type);
  480. data.oldValue[event.key] = event.oldValue;
  481. data.newValue[event.key] = event.newValue;
  482. return data;
  483. }, {
  484. oldValue: {},
  485. keys: [],
  486. operations: [],
  487. newValue: {},
  488. });
  489. }
  490. else {
  491. return {
  492. operation: formatDisplay(events.type),
  493. key: formatDisplay(events.key),
  494. oldValue: events.oldValue,
  495. newValue: events.newValue,
  496. };
  497. }
  498. }
  499. function formatMutationType(type) {
  500. switch (type) {
  501. case MutationType.direct:
  502. return 'mutation';
  503. case MutationType.patchFunction:
  504. return '$patch';
  505. case MutationType.patchObject:
  506. return '$patch';
  507. default:
  508. return 'unknown';
  509. }
  510. }
  511. // timeline can be paused when directly changing the state
  512. let isTimelineActive = true;
  513. const componentStateTypes = [];
  514. const MUTATIONS_LAYER_ID = 'pinia:mutations';
  515. const INSPECTOR_ID = 'pinia';
  516. const { assign: assign$1 } = Object;
  517. /**
  518. * Gets the displayed name of a store in devtools
  519. *
  520. * @param id - id of the store
  521. * @returns a formatted string
  522. */
  523. const getStoreType = (id) => '🍍 ' + id;
  524. /**
  525. * Add the pinia plugin without any store. Allows displaying a Pinia plugin tab
  526. * as soon as it is added to the application.
  527. *
  528. * @param app - Vue application
  529. * @param pinia - pinia instance
  530. */
  531. function registerPiniaDevtools(app, pinia) {
  532. setupDevtoolsPlugin({
  533. id: 'dev.esm.pinia',
  534. label: 'Pinia 🍍',
  535. logo: 'https://pinia.vuejs.org/logo.svg',
  536. packageName: 'pinia',
  537. homepage: 'https://pinia.vuejs.org',
  538. componentStateTypes,
  539. app,
  540. }, (api) => {
  541. if (typeof api.now !== 'function') {
  542. toastMessage('You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.');
  543. }
  544. api.addTimelineLayer({
  545. id: MUTATIONS_LAYER_ID,
  546. label: `Pinia 🍍`,
  547. color: 0xe5df88,
  548. });
  549. api.addInspector({
  550. id: INSPECTOR_ID,
  551. label: 'Pinia 🍍',
  552. icon: 'storage',
  553. treeFilterPlaceholder: 'Search stores',
  554. actions: [
  555. {
  556. icon: 'content_copy',
  557. action: () => {
  558. actionGlobalCopyState(pinia);
  559. },
  560. tooltip: 'Serialize and copy the state',
  561. },
  562. {
  563. icon: 'content_paste',
  564. action: async () => {
  565. await actionGlobalPasteState(pinia);
  566. api.sendInspectorTree(INSPECTOR_ID);
  567. api.sendInspectorState(INSPECTOR_ID);
  568. },
  569. tooltip: 'Replace the state with the content of your clipboard',
  570. },
  571. {
  572. icon: 'save',
  573. action: () => {
  574. actionGlobalSaveState(pinia);
  575. },
  576. tooltip: 'Save the state as a JSON file',
  577. },
  578. {
  579. icon: 'folder_open',
  580. action: async () => {
  581. await actionGlobalOpenStateFile(pinia);
  582. api.sendInspectorTree(INSPECTOR_ID);
  583. api.sendInspectorState(INSPECTOR_ID);
  584. },
  585. tooltip: 'Import the state from a JSON file',
  586. },
  587. ],
  588. nodeActions: [
  589. {
  590. icon: 'restore',
  591. tooltip: 'Reset the state (with "$reset")',
  592. action: (nodeId) => {
  593. const store = pinia._s.get(nodeId);
  594. if (!store) {
  595. toastMessage(`Cannot reset "${nodeId}" store because it wasn't found.`, 'warn');
  596. }
  597. else if (typeof store.$reset !== 'function') {
  598. toastMessage(`Cannot reset "${nodeId}" store because it doesn't have a "$reset" method implemented.`, 'warn');
  599. }
  600. else {
  601. store.$reset();
  602. toastMessage(`Store "${nodeId}" reset.`);
  603. }
  604. },
  605. },
  606. ],
  607. });
  608. api.on.inspectComponent((payload) => {
  609. const proxy = (payload.componentInstance &&
  610. payload.componentInstance.proxy);
  611. if (proxy && proxy._pStores) {
  612. const piniaStores = payload.componentInstance.proxy._pStores;
  613. Object.values(piniaStores).forEach((store) => {
  614. payload.instanceData.state.push({
  615. type: getStoreType(store.$id),
  616. key: 'state',
  617. editable: true,
  618. value: store._isOptionsAPI
  619. ? {
  620. _custom: {
  621. value: toRaw(store.$state),
  622. actions: [
  623. {
  624. icon: 'restore',
  625. tooltip: 'Reset the state of this store',
  626. action: () => store.$reset(),
  627. },
  628. ],
  629. },
  630. }
  631. : // NOTE: workaround to unwrap transferred refs
  632. Object.keys(store.$state).reduce((state, key) => {
  633. state[key] = store.$state[key];
  634. return state;
  635. }, {}),
  636. });
  637. if (store._getters && store._getters.length) {
  638. payload.instanceData.state.push({
  639. type: getStoreType(store.$id),
  640. key: 'getters',
  641. editable: false,
  642. value: store._getters.reduce((getters, key) => {
  643. try {
  644. getters[key] = store[key];
  645. }
  646. catch (error) {
  647. // @ts-expect-error: we just want to show it in devtools
  648. getters[key] = error;
  649. }
  650. return getters;
  651. }, {}),
  652. });
  653. }
  654. });
  655. }
  656. });
  657. api.on.getInspectorTree((payload) => {
  658. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  659. let stores = [pinia];
  660. stores = stores.concat(Array.from(pinia._s.values()));
  661. payload.rootNodes = (payload.filter
  662. ? stores.filter((store) => '$id' in store
  663. ? store.$id
  664. .toLowerCase()
  665. .includes(payload.filter.toLowerCase())
  666. : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase()))
  667. : stores).map(formatStoreForInspectorTree);
  668. }
  669. });
  670. // Expose pinia instance as $pinia to window
  671. globalThis.$pinia = pinia;
  672. api.on.getInspectorState((payload) => {
  673. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  674. const inspectedStore = payload.nodeId === PINIA_ROOT_ID
  675. ? pinia
  676. : pinia._s.get(payload.nodeId);
  677. if (!inspectedStore) {
  678. // this could be the selected store restored for a different project
  679. // so it's better not to say anything here
  680. return;
  681. }
  682. if (inspectedStore) {
  683. // Expose selected store as $store to window
  684. if (payload.nodeId !== PINIA_ROOT_ID)
  685. globalThis.$store = toRaw(inspectedStore);
  686. payload.state = formatStoreForInspectorState(inspectedStore);
  687. }
  688. }
  689. });
  690. api.on.editInspectorState((payload) => {
  691. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  692. const inspectedStore = payload.nodeId === PINIA_ROOT_ID
  693. ? pinia
  694. : pinia._s.get(payload.nodeId);
  695. if (!inspectedStore) {
  696. return toastMessage(`store "${payload.nodeId}" not found`, 'error');
  697. }
  698. const { path } = payload;
  699. if (!isPinia(inspectedStore)) {
  700. // access only the state
  701. if (path.length !== 1 ||
  702. !inspectedStore._customProperties.has(path[0]) ||
  703. path[0] in inspectedStore.$state) {
  704. path.unshift('$state');
  705. }
  706. }
  707. else {
  708. // Root access, we can omit the `.value` because the devtools API does it for us
  709. path.unshift('state');
  710. }
  711. isTimelineActive = false;
  712. payload.set(inspectedStore, path, payload.state.value);
  713. isTimelineActive = true;
  714. }
  715. });
  716. api.on.editComponentState((payload) => {
  717. if (payload.type.startsWith('🍍')) {
  718. const storeId = payload.type.replace(/^🍍\s*/, '');
  719. const store = pinia._s.get(storeId);
  720. if (!store) {
  721. return toastMessage(`store "${storeId}" not found`, 'error');
  722. }
  723. const { path } = payload;
  724. if (path[0] !== 'state') {
  725. return toastMessage(`Invalid path for store "${storeId}":\n${path}\nOnly state can be modified.`);
  726. }
  727. // rewrite the first entry to be able to directly set the state as
  728. // well as any other path
  729. path[0] = '$state';
  730. isTimelineActive = false;
  731. payload.set(store, path, payload.state.value);
  732. isTimelineActive = true;
  733. }
  734. });
  735. });
  736. }
  737. function addStoreToDevtools(app, store) {
  738. if (!componentStateTypes.includes(getStoreType(store.$id))) {
  739. componentStateTypes.push(getStoreType(store.$id));
  740. }
  741. setupDevtoolsPlugin({
  742. id: 'dev.esm.pinia',
  743. label: 'Pinia 🍍',
  744. logo: 'https://pinia.vuejs.org/logo.svg',
  745. packageName: 'pinia',
  746. homepage: 'https://pinia.vuejs.org',
  747. componentStateTypes,
  748. app,
  749. settings: {
  750. logStoreChanges: {
  751. label: 'Notify about new/deleted stores',
  752. type: 'boolean',
  753. defaultValue: true,
  754. },
  755. // useEmojis: {
  756. // label: 'Use emojis in messages ⚡️',
  757. // type: 'boolean',
  758. // defaultValue: true,
  759. // },
  760. },
  761. }, (api) => {
  762. // gracefully handle errors
  763. const now = typeof api.now === 'function' ? api.now.bind(api) : Date.now;
  764. store.$onAction(({ after, onError, name, args }) => {
  765. const groupId = runningActionId++;
  766. api.addTimelineEvent({
  767. layerId: MUTATIONS_LAYER_ID,
  768. event: {
  769. time: now(),
  770. title: '🛫 ' + name,
  771. subtitle: 'start',
  772. data: {
  773. store: formatDisplay(store.$id),
  774. action: formatDisplay(name),
  775. args,
  776. },
  777. groupId,
  778. },
  779. });
  780. after((result) => {
  781. activeAction = undefined;
  782. api.addTimelineEvent({
  783. layerId: MUTATIONS_LAYER_ID,
  784. event: {
  785. time: now(),
  786. title: '🛬 ' + name,
  787. subtitle: 'end',
  788. data: {
  789. store: formatDisplay(store.$id),
  790. action: formatDisplay(name),
  791. args,
  792. result,
  793. },
  794. groupId,
  795. },
  796. });
  797. });
  798. onError((error) => {
  799. activeAction = undefined;
  800. api.addTimelineEvent({
  801. layerId: MUTATIONS_LAYER_ID,
  802. event: {
  803. time: now(),
  804. logType: 'error',
  805. title: '💥 ' + name,
  806. subtitle: 'end',
  807. data: {
  808. store: formatDisplay(store.$id),
  809. action: formatDisplay(name),
  810. args,
  811. error,
  812. },
  813. groupId,
  814. },
  815. });
  816. });
  817. }, true);
  818. store._customProperties.forEach((name) => {
  819. watch(() => unref(store[name]), (newValue, oldValue) => {
  820. api.notifyComponentUpdate();
  821. api.sendInspectorState(INSPECTOR_ID);
  822. if (isTimelineActive) {
  823. api.addTimelineEvent({
  824. layerId: MUTATIONS_LAYER_ID,
  825. event: {
  826. time: now(),
  827. title: 'Change',
  828. subtitle: name,
  829. data: {
  830. newValue,
  831. oldValue,
  832. },
  833. groupId: activeAction,
  834. },
  835. });
  836. }
  837. }, { deep: true });
  838. });
  839. store.$subscribe(({ events, type }, state) => {
  840. api.notifyComponentUpdate();
  841. api.sendInspectorState(INSPECTOR_ID);
  842. if (!isTimelineActive)
  843. return;
  844. // rootStore.state[store.id] = state
  845. const eventData = {
  846. time: now(),
  847. title: formatMutationType(type),
  848. data: assign$1({ store: formatDisplay(store.$id) }, formatEventData(events)),
  849. groupId: activeAction,
  850. };
  851. if (type === MutationType.patchFunction) {
  852. eventData.subtitle = '⤵️';
  853. }
  854. else if (type === MutationType.patchObject) {
  855. eventData.subtitle = '🧩';
  856. }
  857. else if (events && !Array.isArray(events)) {
  858. eventData.subtitle = events.type;
  859. }
  860. if (events) {
  861. eventData.data['rawEvent(s)'] = {
  862. _custom: {
  863. display: 'DebuggerEvent',
  864. type: 'object',
  865. tooltip: 'raw DebuggerEvent[]',
  866. value: events,
  867. },
  868. };
  869. }
  870. api.addTimelineEvent({
  871. layerId: MUTATIONS_LAYER_ID,
  872. event: eventData,
  873. });
  874. }, { detached: true, flush: 'sync' });
  875. const hotUpdate = store._hotUpdate;
  876. store._hotUpdate = markRaw((newStore) => {
  877. hotUpdate(newStore);
  878. api.addTimelineEvent({
  879. layerId: MUTATIONS_LAYER_ID,
  880. event: {
  881. time: now(),
  882. title: '🔥 ' + store.$id,
  883. subtitle: 'HMR update',
  884. data: {
  885. store: formatDisplay(store.$id),
  886. info: formatDisplay(`HMR update`),
  887. },
  888. },
  889. });
  890. // update the devtools too
  891. api.notifyComponentUpdate();
  892. api.sendInspectorTree(INSPECTOR_ID);
  893. api.sendInspectorState(INSPECTOR_ID);
  894. });
  895. const { $dispose } = store;
  896. store.$dispose = () => {
  897. $dispose();
  898. api.notifyComponentUpdate();
  899. api.sendInspectorTree(INSPECTOR_ID);
  900. api.sendInspectorState(INSPECTOR_ID);
  901. api.getSettings().logStoreChanges &&
  902. toastMessage(`Disposed "${store.$id}" store 🗑`);
  903. };
  904. // trigger an update so it can display new registered stores
  905. api.notifyComponentUpdate();
  906. api.sendInspectorTree(INSPECTOR_ID);
  907. api.sendInspectorState(INSPECTOR_ID);
  908. api.getSettings().logStoreChanges &&
  909. toastMessage(`"${store.$id}" store installed 🆕`);
  910. });
  911. }
  912. let runningActionId = 0;
  913. let activeAction;
  914. /**
  915. * Patches a store to enable action grouping in devtools by wrapping the store with a Proxy that is passed as the
  916. * context of all actions, allowing us to set `runningAction` on each access and effectively associating any state
  917. * mutation to the action.
  918. *
  919. * @param store - store to patch
  920. * @param actionNames - list of actionst to patch
  921. */
  922. function patchActionForGrouping(store, actionNames, wrapWithProxy) {
  923. // original actions of the store as they are given by pinia. We are going to override them
  924. const actions = actionNames.reduce((storeActions, actionName) => {
  925. // use toRaw to avoid tracking #541
  926. storeActions[actionName] = toRaw(store)[actionName];
  927. return storeActions;
  928. }, {});
  929. for (const actionName in actions) {
  930. store[actionName] = function () {
  931. // the running action id is incremented in a before action hook
  932. const _actionId = runningActionId;
  933. const trackedStore = wrapWithProxy
  934. ? new Proxy(store, {
  935. get(...args) {
  936. activeAction = _actionId;
  937. return Reflect.get(...args);
  938. },
  939. set(...args) {
  940. activeAction = _actionId;
  941. return Reflect.set(...args);
  942. },
  943. })
  944. : store;
  945. // For Setup Stores we need https://github.com/tc39/proposal-async-context
  946. activeAction = _actionId;
  947. const retValue = actions[actionName].apply(trackedStore, arguments);
  948. // this is safer as async actions in Setup Stores would associate mutations done outside of the action
  949. activeAction = undefined;
  950. return retValue;
  951. };
  952. }
  953. }
  954. /**
  955. * pinia.use(devtoolsPlugin)
  956. */
  957. function devtoolsPlugin({ app, store, options }) {
  958. // HMR module
  959. if (store.$id.startsWith('__hot:')) {
  960. return;
  961. }
  962. // detect option api vs setup api
  963. store._isOptionsAPI = !!options.state;
  964. // Do not overwrite actions mocked by @pinia/testing (#2298)
  965. if (!store._p._testing) {
  966. patchActionForGrouping(store, Object.keys(options.actions), store._isOptionsAPI);
  967. // Upgrade the HMR to also update the new actions
  968. const originalHotUpdate = store._hotUpdate;
  969. toRaw(store)._hotUpdate = function (newStore) {
  970. originalHotUpdate.apply(this, arguments);
  971. patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions), !!store._isOptionsAPI);
  972. };
  973. }
  974. addStoreToDevtools(app,
  975. // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric?
  976. store);
  977. }
  978. /**
  979. * Creates a Pinia instance to be used by the application
  980. */
  981. function createPinia() {
  982. const scope = effectScope(true);
  983. // NOTE: here we could check the window object for a state and directly set it
  984. // if there is anything like it with Vue 3 SSR
  985. const state = scope.run(() => ref({}));
  986. let _p = [];
  987. // plugins added before calling app.use(pinia)
  988. let toBeInstalled = [];
  989. const pinia = markRaw({
  990. install(app) {
  991. // this allows calling useStore() outside of a component setup after
  992. // installing pinia's plugin
  993. setActivePinia(pinia);
  994. pinia._a = app;
  995. app.provide(piniaSymbol, pinia);
  996. app.config.globalProperties.$pinia = pinia;
  997. /* istanbul ignore else */
  998. if ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {
  999. registerPiniaDevtools(app, pinia);
  1000. }
  1001. toBeInstalled.forEach((plugin) => _p.push(plugin));
  1002. toBeInstalled = [];
  1003. },
  1004. use(plugin) {
  1005. if (!this._a) {
  1006. toBeInstalled.push(plugin);
  1007. }
  1008. else {
  1009. _p.push(plugin);
  1010. }
  1011. return this;
  1012. },
  1013. _p,
  1014. // it's actually undefined here
  1015. // @ts-expect-error
  1016. _a: null,
  1017. _e: scope,
  1018. _s: new Map(),
  1019. state,
  1020. });
  1021. // pinia devtools rely on dev only features so they cannot be forced unless
  1022. // the dev build of Vue is used. Avoid old browsers like IE11.
  1023. if ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT && typeof Proxy !== 'undefined') {
  1024. pinia.use(devtoolsPlugin);
  1025. }
  1026. return pinia;
  1027. }
  1028. /**
  1029. * Dispose a Pinia instance by stopping its effectScope and removing the state, plugins and stores. This is mostly
  1030. * useful in tests, with both a testing pinia or a regular pinia and in applications that use multiple pinia instances.
  1031. * Once disposed, the pinia instance cannot be used anymore.
  1032. *
  1033. * @param pinia - pinia instance
  1034. */
  1035. function disposePinia(pinia) {
  1036. pinia._e.stop();
  1037. pinia._s.clear();
  1038. pinia._p.splice(0);
  1039. pinia.state.value = {};
  1040. // @ts-expect-error: non valid
  1041. pinia._a = null;
  1042. }
  1043. /**
  1044. * Checks if a function is a `StoreDefinition`.
  1045. *
  1046. * @param fn - object to test
  1047. * @returns true if `fn` is a StoreDefinition
  1048. */
  1049. const isUseStore = (fn) => {
  1050. return typeof fn === 'function' && typeof fn.$id === 'string';
  1051. };
  1052. /**
  1053. * Mutates in place `newState` with `oldState` to _hot update_ it. It will
  1054. * remove any key not existing in `newState` and recursively merge plain
  1055. * objects.
  1056. *
  1057. * @param newState - new state object to be patched
  1058. * @param oldState - old state that should be used to patch newState
  1059. * @returns - newState
  1060. */
  1061. function patchObject(newState, oldState) {
  1062. // no need to go through symbols because they cannot be serialized anyway
  1063. for (const key in oldState) {
  1064. const subPatch = oldState[key];
  1065. // skip the whole sub tree
  1066. if (!(key in newState)) {
  1067. continue;
  1068. }
  1069. const targetValue = newState[key];
  1070. if (isPlainObject(targetValue) &&
  1071. isPlainObject(subPatch) &&
  1072. !isRef(subPatch) &&
  1073. !isReactive(subPatch)) {
  1074. newState[key] = patchObject(targetValue, subPatch);
  1075. }
  1076. else {
  1077. // objects are either a bit more complex (e.g. refs) or primitives, so we
  1078. // just set the whole thing
  1079. newState[key] = subPatch;
  1080. }
  1081. }
  1082. return newState;
  1083. }
  1084. /**
  1085. * Creates an _accept_ function to pass to `import.meta.hot` in Vite applications.
  1086. *
  1087. * @example
  1088. * ```js
  1089. * const useUser = defineStore(...)
  1090. * if (import.meta.hot) {
  1091. * import.meta.hot.accept(acceptHMRUpdate(useUser, import.meta.hot))
  1092. * }
  1093. * ```
  1094. *
  1095. * @param initialUseStore - return of the defineStore to hot update
  1096. * @param hot - `import.meta.hot`
  1097. */
  1098. function acceptHMRUpdate(initialUseStore, hot) {
  1099. // strip as much as possible from iife.prod
  1100. if (!(process.env.NODE_ENV !== 'production')) {
  1101. return () => { };
  1102. }
  1103. return (newModule) => {
  1104. const pinia = hot.data.pinia || initialUseStore._pinia;
  1105. if (!pinia) {
  1106. // this store is still not used
  1107. return;
  1108. }
  1109. // preserve the pinia instance across loads
  1110. hot.data.pinia = pinia;
  1111. // console.log('got data', newStore)
  1112. for (const exportName in newModule) {
  1113. const useStore = newModule[exportName];
  1114. // console.log('checking for', exportName)
  1115. if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {
  1116. // console.log('Accepting update for', useStore.$id)
  1117. const id = useStore.$id;
  1118. if (id !== initialUseStore.$id) {
  1119. console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`);
  1120. // return import.meta.hot.invalidate()
  1121. return hot.invalidate();
  1122. }
  1123. const existingStore = pinia._s.get(id);
  1124. if (!existingStore) {
  1125. console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
  1126. return;
  1127. }
  1128. useStore(pinia, existingStore);
  1129. }
  1130. }
  1131. };
  1132. }
  1133. const noop = () => { };
  1134. function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
  1135. subscriptions.add(callback);
  1136. const removeSubscription = () => {
  1137. const isDel = subscriptions.delete(callback);
  1138. isDel && onCleanup();
  1139. };
  1140. if (!detached && getCurrentScope()) {
  1141. onScopeDispose(removeSubscription);
  1142. }
  1143. return removeSubscription;
  1144. }
  1145. function triggerSubscriptions(subscriptions, ...args) {
  1146. subscriptions.forEach((callback) => {
  1147. callback(...args);
  1148. });
  1149. }
  1150. const fallbackRunWithContext = (fn) => fn();
  1151. /**
  1152. * Marks a function as an action for `$onAction`
  1153. * @internal
  1154. */
  1155. const ACTION_MARKER = Symbol();
  1156. /**
  1157. * Action name symbol. Allows to add a name to an action after defining it
  1158. * @internal
  1159. */
  1160. const ACTION_NAME = Symbol();
  1161. function mergeReactiveObjects(target, patchToApply) {
  1162. // Handle Map instances
  1163. if (target instanceof Map && patchToApply instanceof Map) {
  1164. patchToApply.forEach((value, key) => target.set(key, value));
  1165. }
  1166. else if (target instanceof Set && patchToApply instanceof Set) {
  1167. // Handle Set instances
  1168. patchToApply.forEach(target.add, target);
  1169. }
  1170. // no need to go through symbols because they cannot be serialized anyway
  1171. for (const key in patchToApply) {
  1172. if (!patchToApply.hasOwnProperty(key))
  1173. continue;
  1174. const subPatch = patchToApply[key];
  1175. const targetValue = target[key];
  1176. if (isPlainObject(targetValue) &&
  1177. isPlainObject(subPatch) &&
  1178. target.hasOwnProperty(key) &&
  1179. !isRef(subPatch) &&
  1180. !isReactive(subPatch)) {
  1181. // NOTE: here I wanted to warn about inconsistent types but it's not possible because in setup stores one might
  1182. // start the value of a property as a certain type e.g. a Map, and then for some reason, during SSR, change that
  1183. // to `undefined`. When trying to hydrate, we want to override the Map with `undefined`.
  1184. target[key] = mergeReactiveObjects(targetValue, subPatch);
  1185. }
  1186. else {
  1187. // @ts-expect-error: subPatch is a valid value
  1188. target[key] = subPatch;
  1189. }
  1190. }
  1191. return target;
  1192. }
  1193. const skipHydrateSymbol = (process.env.NODE_ENV !== 'production')
  1194. ? Symbol('pinia:skipHydration')
  1195. : /* istanbul ignore next */ Symbol();
  1196. /**
  1197. * Tells Pinia to skip the hydration process of a given object. This is useful in setup stores (only) when you return a
  1198. * stateful object in the store but it isn't really state. e.g. returning a router instance in a setup store.
  1199. *
  1200. * @param obj - target object
  1201. * @returns obj
  1202. */
  1203. function skipHydrate(obj) {
  1204. return Object.defineProperty(obj, skipHydrateSymbol, {});
  1205. }
  1206. /**
  1207. * Returns whether a value should be hydrated
  1208. *
  1209. * @param obj - target variable
  1210. * @returns true if `obj` should be hydrated
  1211. */
  1212. function shouldHydrate(obj) {
  1213. return (!isPlainObject(obj) ||
  1214. !Object.prototype.hasOwnProperty.call(obj, skipHydrateSymbol));
  1215. }
  1216. const { assign } = Object;
  1217. function isComputed(o) {
  1218. return !!(isRef(o) && o.effect);
  1219. }
  1220. function createOptionsStore(id, options, pinia, hot) {
  1221. const { state, actions, getters } = options;
  1222. const initialState = pinia.state.value[id];
  1223. let store;
  1224. function setup() {
  1225. if (!initialState && (!(process.env.NODE_ENV !== 'production') || !hot)) {
  1226. /* istanbul ignore if */
  1227. pinia.state.value[id] = state ? state() : {};
  1228. }
  1229. // avoid creating a state in pinia.state.value
  1230. const localState = (process.env.NODE_ENV !== 'production') && hot
  1231. ? // use ref() to unwrap refs inside state TODO: check if this is still necessary
  1232. toRefs(ref(state ? state() : {}).value)
  1233. : toRefs(pinia.state.value[id]);
  1234. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  1235. if ((process.env.NODE_ENV !== 'production') && name in localState) {
  1236. console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`);
  1237. }
  1238. computedGetters[name] = markRaw(computed(() => {
  1239. setActivePinia(pinia);
  1240. // it was created just before
  1241. const store = pinia._s.get(id);
  1242. // allow cross using stores
  1243. // @ts-expect-error
  1244. // return getters![name].call(context, context)
  1245. // TODO: avoid reading the getter while assigning with a global variable
  1246. return getters[name].call(store, store);
  1247. }));
  1248. return computedGetters;
  1249. }, {}));
  1250. }
  1251. store = createSetupStore(id, setup, options, pinia, hot, true);
  1252. return store;
  1253. }
  1254. function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  1255. let scope;
  1256. const optionsForPlugin = assign({ actions: {} }, options);
  1257. /* istanbul ignore if */
  1258. if ((process.env.NODE_ENV !== 'production') && !pinia._e.active) {
  1259. throw new Error('Pinia destroyed');
  1260. }
  1261. // watcher options for $subscribe
  1262. const $subscribeOptions = { deep: true };
  1263. /* istanbul ignore else */
  1264. if ((process.env.NODE_ENV !== 'production')) {
  1265. $subscribeOptions.onTrigger = (event) => {
  1266. /* istanbul ignore else */
  1267. if (isListening) {
  1268. debuggerEvents = event;
  1269. // avoid triggering this while the store is being built and the state is being set in pinia
  1270. }
  1271. else if (isListening == false && !store._hotUpdating) {
  1272. // let patch send all the events together later
  1273. /* istanbul ignore else */
  1274. if (Array.isArray(debuggerEvents)) {
  1275. debuggerEvents.push(event);
  1276. }
  1277. else {
  1278. console.error('🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.');
  1279. }
  1280. }
  1281. };
  1282. }
  1283. // internal state
  1284. let isListening; // set to true at the end
  1285. let isSyncListening; // set to true at the end
  1286. let subscriptions = new Set();
  1287. let actionSubscriptions = new Set();
  1288. let debuggerEvents;
  1289. const initialState = pinia.state.value[$id];
  1290. // avoid setting the state for option stores if it is set
  1291. // by the setup
  1292. if (!isOptionsStore && !initialState && (!(process.env.NODE_ENV !== 'production') || !hot)) {
  1293. /* istanbul ignore if */
  1294. pinia.state.value[$id] = {};
  1295. }
  1296. const hotState = ref({});
  1297. // avoid triggering too many listeners
  1298. // https://github.com/vuejs/pinia/issues/1129
  1299. let activeListener;
  1300. function $patch(partialStateOrMutator) {
  1301. let subscriptionMutation;
  1302. isListening = isSyncListening = false;
  1303. // reset the debugger events since patches are sync
  1304. /* istanbul ignore else */
  1305. if ((process.env.NODE_ENV !== 'production')) {
  1306. debuggerEvents = [];
  1307. }
  1308. if (typeof partialStateOrMutator === 'function') {
  1309. partialStateOrMutator(pinia.state.value[$id]);
  1310. subscriptionMutation = {
  1311. type: MutationType.patchFunction,
  1312. storeId: $id,
  1313. events: debuggerEvents,
  1314. };
  1315. }
  1316. else {
  1317. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  1318. subscriptionMutation = {
  1319. type: MutationType.patchObject,
  1320. payload: partialStateOrMutator,
  1321. storeId: $id,
  1322. events: debuggerEvents,
  1323. };
  1324. }
  1325. const myListenerId = (activeListener = Symbol());
  1326. nextTick().then(() => {
  1327. if (activeListener === myListenerId) {
  1328. isListening = true;
  1329. }
  1330. });
  1331. isSyncListening = true;
  1332. // because we paused the watcher, we need to manually call the subscriptions
  1333. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  1334. }
  1335. const $reset = isOptionsStore
  1336. ? function $reset() {
  1337. const { state } = options;
  1338. const newState = state ? state() : {};
  1339. // we use a patch to group all changes into one single subscription
  1340. this.$patch(($state) => {
  1341. // @ts-expect-error: FIXME: shouldn't error?
  1342. assign($state, newState);
  1343. });
  1344. }
  1345. : /* istanbul ignore next */
  1346. (process.env.NODE_ENV !== 'production')
  1347. ? () => {
  1348. throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
  1349. }
  1350. : noop;
  1351. function $dispose() {
  1352. scope.stop();
  1353. subscriptions.clear();
  1354. actionSubscriptions.clear();
  1355. pinia._s.delete($id);
  1356. }
  1357. /**
  1358. * Helper that wraps function so it can be tracked with $onAction
  1359. * @param fn - action to wrap
  1360. * @param name - name of the action
  1361. */
  1362. const action = (fn, name = '') => {
  1363. if (ACTION_MARKER in fn) {
  1364. fn[ACTION_NAME] = name;
  1365. return fn;
  1366. }
  1367. const wrappedAction = function () {
  1368. setActivePinia(pinia);
  1369. const args = Array.from(arguments);
  1370. const afterCallbackSet = new Set();
  1371. const onErrorCallbackSet = new Set();
  1372. function after(callback) {
  1373. afterCallbackSet.add(callback);
  1374. }
  1375. function onError(callback) {
  1376. onErrorCallbackSet.add(callback);
  1377. }
  1378. // @ts-expect-error
  1379. triggerSubscriptions(actionSubscriptions, {
  1380. args,
  1381. name: wrappedAction[ACTION_NAME],
  1382. store,
  1383. after,
  1384. onError,
  1385. });
  1386. let ret;
  1387. try {
  1388. ret = fn.apply(this && this.$id === $id ? this : store, args);
  1389. // handle sync errors
  1390. }
  1391. catch (error) {
  1392. triggerSubscriptions(onErrorCallbackSet, error);
  1393. throw error;
  1394. }
  1395. if (ret instanceof Promise) {
  1396. return ret
  1397. .then((value) => {
  1398. triggerSubscriptions(afterCallbackSet, value);
  1399. return value;
  1400. })
  1401. .catch((error) => {
  1402. triggerSubscriptions(onErrorCallbackSet, error);
  1403. return Promise.reject(error);
  1404. });
  1405. }
  1406. // trigger after callbacks
  1407. triggerSubscriptions(afterCallbackSet, ret);
  1408. return ret;
  1409. };
  1410. wrappedAction[ACTION_MARKER] = true;
  1411. wrappedAction[ACTION_NAME] = name; // will be set later
  1412. // @ts-expect-error: we are intentionally limiting the returned type to just Fn
  1413. // because all the added properties are internals that are exposed through `$onAction()` only
  1414. return wrappedAction;
  1415. };
  1416. const _hmrPayload = /*#__PURE__*/ markRaw({
  1417. actions: {},
  1418. getters: {},
  1419. state: [],
  1420. hotState,
  1421. });
  1422. const partialStore = {
  1423. _p: pinia,
  1424. // _s: scope,
  1425. $id,
  1426. $onAction: addSubscription.bind(null, actionSubscriptions),
  1427. $patch,
  1428. $reset,
  1429. $subscribe(callback, options = {}) {
  1430. const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher());
  1431. const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => {
  1432. if (options.flush === 'sync' ? isSyncListening : isListening) {
  1433. callback({
  1434. storeId: $id,
  1435. type: MutationType.direct,
  1436. events: debuggerEvents,
  1437. }, state);
  1438. }
  1439. }, assign({}, $subscribeOptions, options)));
  1440. return removeSubscription;
  1441. },
  1442. $dispose,
  1443. };
  1444. const store = reactive((process.env.NODE_ENV !== 'production') || ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT)
  1445. ? assign({
  1446. _hmrPayload,
  1447. _customProperties: markRaw(new Set()), // devtools custom properties
  1448. }, partialStore
  1449. // must be added later
  1450. // setupStore
  1451. )
  1452. : partialStore);
  1453. // store the partial store now so the setup of stores can instantiate each other before they are finished without
  1454. // creating infinite loops.
  1455. pinia._s.set($id, store);
  1456. const runWithContext = (pinia._a && pinia._a.runWithContext) || fallbackRunWithContext;
  1457. // TODO: idea create skipSerialize that marks properties as non serializable and they are skipped
  1458. const setupStore = runWithContext(() => pinia._e.run(() => (scope = effectScope()).run(() => setup({ action }))));
  1459. // overwrite existing actions to support $onAction
  1460. for (const key in setupStore) {
  1461. const prop = setupStore[key];
  1462. if ((isRef(prop) && !isComputed(prop)) || isReactive(prop)) {
  1463. // mark it as a piece of state to be serialized
  1464. if ((process.env.NODE_ENV !== 'production') && hot) {
  1465. hotState.value[key] = toRef(setupStore, key);
  1466. // createOptionStore directly sets the state in pinia.state.value so we
  1467. // can just skip that
  1468. }
  1469. else if (!isOptionsStore) {
  1470. // in setup stores we must hydrate the state and sync pinia state tree with the refs the user just created
  1471. if (initialState && shouldHydrate(prop)) {
  1472. if (isRef(prop)) {
  1473. prop.value = initialState[key];
  1474. }
  1475. else {
  1476. // probably a reactive object, lets recursively assign
  1477. // @ts-expect-error: prop is unknown
  1478. mergeReactiveObjects(prop, initialState[key]);
  1479. }
  1480. }
  1481. // transfer the ref to the pinia state to keep everything in sync
  1482. pinia.state.value[$id][key] = prop;
  1483. }
  1484. /* istanbul ignore else */
  1485. if ((process.env.NODE_ENV !== 'production')) {
  1486. _hmrPayload.state.push(key);
  1487. }
  1488. // action
  1489. }
  1490. else if (typeof prop === 'function') {
  1491. const actionValue = (process.env.NODE_ENV !== 'production') && hot ? prop : action(prop, key);
  1492. // this a hot module replacement store because the hotUpdate method needs
  1493. // to do it with the right context
  1494. // @ts-expect-error
  1495. setupStore[key] = actionValue;
  1496. /* istanbul ignore else */
  1497. if ((process.env.NODE_ENV !== 'production')) {
  1498. _hmrPayload.actions[key] = prop;
  1499. }
  1500. // list actions so they can be used in plugins
  1501. // @ts-expect-error
  1502. optionsForPlugin.actions[key] = prop;
  1503. }
  1504. else if ((process.env.NODE_ENV !== 'production')) {
  1505. // add getters for devtools
  1506. if (isComputed(prop)) {
  1507. _hmrPayload.getters[key] = isOptionsStore
  1508. ? // @ts-expect-error
  1509. options.getters[key]
  1510. : prop;
  1511. if (IS_CLIENT) {
  1512. const getters = setupStore._getters ||
  1513. // @ts-expect-error: same
  1514. (setupStore._getters = markRaw([]));
  1515. getters.push(key);
  1516. }
  1517. }
  1518. }
  1519. }
  1520. // add the state, getters, and action properties
  1521. /* istanbul ignore if */
  1522. assign(store, setupStore);
  1523. // allows retrieving reactive objects with `storeToRefs()`. Must be called after assigning to the reactive object.
  1524. // Make `storeToRefs()` work with `reactive()` #799
  1525. assign(toRaw(store), setupStore);
  1526. // use this instead of a computed with setter to be able to create it anywhere
  1527. // without linking the computed lifespan to wherever the store is first
  1528. // created.
  1529. Object.defineProperty(store, '$state', {
  1530. get: () => ((process.env.NODE_ENV !== 'production') && hot ? hotState.value : pinia.state.value[$id]),
  1531. set: (state) => {
  1532. /* istanbul ignore if */
  1533. if ((process.env.NODE_ENV !== 'production') && hot) {
  1534. throw new Error('cannot set hotState');
  1535. }
  1536. $patch(($state) => {
  1537. // @ts-expect-error: FIXME: shouldn't error?
  1538. assign($state, state);
  1539. });
  1540. },
  1541. });
  1542. // add the hotUpdate before plugins to allow them to override it
  1543. /* istanbul ignore else */
  1544. if ((process.env.NODE_ENV !== 'production')) {
  1545. store._hotUpdate = markRaw((newStore) => {
  1546. store._hotUpdating = true;
  1547. newStore._hmrPayload.state.forEach((stateKey) => {
  1548. if (stateKey in store.$state) {
  1549. const newStateTarget = newStore.$state[stateKey];
  1550. const oldStateSource = store.$state[stateKey];
  1551. if (typeof newStateTarget === 'object' &&
  1552. isPlainObject(newStateTarget) &&
  1553. isPlainObject(oldStateSource)) {
  1554. patchObject(newStateTarget, oldStateSource);
  1555. }
  1556. else {
  1557. // transfer the ref
  1558. newStore.$state[stateKey] = oldStateSource;
  1559. }
  1560. }
  1561. // patch direct access properties to allow store.stateProperty to work as
  1562. // store.$state.stateProperty
  1563. // @ts-expect-error: any type
  1564. store[stateKey] = toRef(newStore.$state, stateKey);
  1565. });
  1566. // remove deleted state properties
  1567. Object.keys(store.$state).forEach((stateKey) => {
  1568. if (!(stateKey in newStore.$state)) {
  1569. // @ts-expect-error: noop if doesn't exist
  1570. delete store[stateKey];
  1571. }
  1572. });
  1573. // avoid devtools logging this as a mutation
  1574. isListening = false;
  1575. isSyncListening = false;
  1576. pinia.state.value[$id] = toRef(newStore._hmrPayload, 'hotState');
  1577. isSyncListening = true;
  1578. nextTick().then(() => {
  1579. isListening = true;
  1580. });
  1581. for (const actionName in newStore._hmrPayload.actions) {
  1582. const actionFn = newStore[actionName];
  1583. // @ts-expect-error: actionName is a string
  1584. store[actionName] =
  1585. //
  1586. action(actionFn, actionName);
  1587. }
  1588. // TODO: does this work in both setup and option store?
  1589. for (const getterName in newStore._hmrPayload.getters) {
  1590. const getter = newStore._hmrPayload.getters[getterName];
  1591. const getterValue = isOptionsStore
  1592. ? // special handling of options api
  1593. computed(() => {
  1594. setActivePinia(pinia);
  1595. return getter.call(store, store);
  1596. })
  1597. : getter;
  1598. // @ts-expect-error: getterName is a string
  1599. store[getterName] =
  1600. //
  1601. getterValue;
  1602. }
  1603. // remove deleted getters
  1604. Object.keys(store._hmrPayload.getters).forEach((key) => {
  1605. if (!(key in newStore._hmrPayload.getters)) {
  1606. // @ts-expect-error: noop if doesn't exist
  1607. delete store[key];
  1608. }
  1609. });
  1610. // remove old actions
  1611. Object.keys(store._hmrPayload.actions).forEach((key) => {
  1612. if (!(key in newStore._hmrPayload.actions)) {
  1613. // @ts-expect-error: noop if doesn't exist
  1614. delete store[key];
  1615. }
  1616. });
  1617. // update the values used in devtools and to allow deleting new properties later on
  1618. store._hmrPayload = newStore._hmrPayload;
  1619. store._getters = newStore._getters;
  1620. store._hotUpdating = false;
  1621. });
  1622. }
  1623. if ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {
  1624. const nonEnumerable = {
  1625. writable: true,
  1626. configurable: true,
  1627. // avoid warning on devtools trying to display this property
  1628. enumerable: false,
  1629. };
  1630. ['_p', '_hmrPayload', '_getters', '_customProperties'].forEach((p) => {
  1631. Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));
  1632. });
  1633. }
  1634. // apply all plugins
  1635. pinia._p.forEach((extender) => {
  1636. /* istanbul ignore else */
  1637. if ((((process.env.NODE_ENV !== 'production') || (typeof __VUE_PROD_DEVTOOLS__ !== 'undefined' && __VUE_PROD_DEVTOOLS__)) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {
  1638. const extensions = scope.run(() => extender({
  1639. store: store,
  1640. app: pinia._a,
  1641. pinia,
  1642. options: optionsForPlugin,
  1643. }));
  1644. Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
  1645. assign(store, extensions);
  1646. }
  1647. else {
  1648. assign(store, scope.run(() => extender({
  1649. store: store,
  1650. app: pinia._a,
  1651. pinia,
  1652. options: optionsForPlugin,
  1653. })));
  1654. }
  1655. });
  1656. if ((process.env.NODE_ENV !== 'production') &&
  1657. store.$state &&
  1658. typeof store.$state === 'object' &&
  1659. typeof store.$state.constructor === 'function' &&
  1660. !store.$state.constructor.toString().includes('[native code]')) {
  1661. console.warn(`[🍍]: The "state" must be a plain object. It cannot be\n` +
  1662. `\tstate: () => new MyClass()\n` +
  1663. `Found in store "${store.$id}".`);
  1664. }
  1665. // only apply hydrate to option stores with an initial state in pinia
  1666. if (initialState &&
  1667. isOptionsStore &&
  1668. options.hydrate) {
  1669. options.hydrate(store.$state, initialState);
  1670. }
  1671. isListening = true;
  1672. isSyncListening = true;
  1673. return store;
  1674. }
  1675. // allows unused stores to be tree shaken
  1676. /*! #__NO_SIDE_EFFECTS__ */
  1677. function defineStore(
  1678. // TODO: add proper types from above
  1679. id, setup, setupOptions) {
  1680. let options;
  1681. const isSetupStore = typeof setup === 'function';
  1682. // the option store setup will contain the actual options in this case
  1683. options = isSetupStore ? setupOptions : setup;
  1684. function useStore(pinia, hot) {
  1685. const hasContext = hasInjectionContext();
  1686. pinia =
  1687. // in test mode, ignore the argument provided as we can always retrieve a
  1688. // pinia instance with getActivePinia()
  1689. ((process.env.NODE_ENV === 'test') && activePinia && activePinia._testing ? null : pinia) ||
  1690. (hasContext ? inject(piniaSymbol, null) : null);
  1691. if (pinia)
  1692. setActivePinia(pinia);
  1693. if ((process.env.NODE_ENV !== 'production') && !activePinia) {
  1694. throw new Error(`[🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?\n` +
  1695. `See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.\n` +
  1696. `This will fail in production.`);
  1697. }
  1698. pinia = activePinia;
  1699. if (!pinia._s.has(id)) {
  1700. // creating the store registers it in `pinia._s`
  1701. if (isSetupStore) {
  1702. createSetupStore(id, setup, options, pinia);
  1703. }
  1704. else {
  1705. createOptionsStore(id, options, pinia);
  1706. }
  1707. /* istanbul ignore else */
  1708. if ((process.env.NODE_ENV !== 'production')) {
  1709. // @ts-expect-error: not the right inferred type
  1710. useStore._pinia = pinia;
  1711. }
  1712. }
  1713. const store = pinia._s.get(id);
  1714. if ((process.env.NODE_ENV !== 'production') && hot) {
  1715. const hotId = '__hot:' + id;
  1716. const newStore = isSetupStore
  1717. ? createSetupStore(hotId, setup, options, pinia, true)
  1718. : createOptionsStore(hotId, assign({}, options), pinia, true);
  1719. hot._hotUpdate(newStore);
  1720. // cleanup the state properties and the store from the cache
  1721. delete pinia.state.value[hotId];
  1722. pinia._s.delete(hotId);
  1723. }
  1724. if ((process.env.NODE_ENV !== 'production') && IS_CLIENT) {
  1725. const currentInstance = getCurrentInstance();
  1726. // save stores in instances to access them devtools
  1727. if (currentInstance &&
  1728. currentInstance.proxy &&
  1729. // avoid adding stores that are just built for hot module replacement
  1730. !hot) {
  1731. const vm = currentInstance.proxy;
  1732. const cache = '_pStores' in vm ? vm._pStores : (vm._pStores = {});
  1733. cache[id] = store;
  1734. }
  1735. }
  1736. // StoreGeneric cannot be casted towards Store
  1737. return store;
  1738. }
  1739. useStore.$id = id;
  1740. return useStore;
  1741. }
  1742. let mapStoreSuffix = 'Store';
  1743. /**
  1744. * Changes the suffix added by `mapStores()`. Can be set to an empty string.
  1745. * Defaults to `"Store"`. Make sure to extend the MapStoresCustomization
  1746. * interface if you are using TypeScript.
  1747. *
  1748. * @param suffix - new suffix
  1749. */
  1750. function setMapStoreSuffix(suffix // could be 'Store' but that would be annoying for JS
  1751. ) {
  1752. mapStoreSuffix = suffix;
  1753. }
  1754. /**
  1755. * Allows using stores without the composition API (`setup()`) by generating an
  1756. * object to be spread in the `computed` field of a component. It accepts a list
  1757. * of store definitions.
  1758. *
  1759. * @example
  1760. * ```js
  1761. * export default {
  1762. * computed: {
  1763. * // other computed properties
  1764. * ...mapStores(useUserStore, useCartStore)
  1765. * },
  1766. *
  1767. * created() {
  1768. * this.userStore // store with id "user"
  1769. * this.cartStore // store with id "cart"
  1770. * }
  1771. * }
  1772. * ```
  1773. *
  1774. * @param stores - list of stores to map to an object
  1775. */
  1776. function mapStores(...stores) {
  1777. if ((process.env.NODE_ENV !== 'production') && Array.isArray(stores[0])) {
  1778. console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:\n` +
  1779. `Replace\n` +
  1780. `\tmapStores([useAuthStore, useCartStore])\n` +
  1781. `with\n` +
  1782. `\tmapStores(useAuthStore, useCartStore)\n` +
  1783. `This will fail in production if not fixed.`);
  1784. stores = stores[0];
  1785. }
  1786. return stores.reduce((reduced, useStore) => {
  1787. // @ts-expect-error: $id is added by defineStore
  1788. reduced[useStore.$id + mapStoreSuffix] = function () {
  1789. return useStore(this.$pinia);
  1790. };
  1791. return reduced;
  1792. }, {});
  1793. }
  1794. /**
  1795. * Allows using state and getters from one store without using the composition
  1796. * API (`setup()`) by generating an object to be spread in the `computed` field
  1797. * of a component.
  1798. *
  1799. * @param useStore - store to map from
  1800. * @param keysOrMapper - array or object
  1801. */
  1802. function mapState(useStore, keysOrMapper) {
  1803. return Array.isArray(keysOrMapper)
  1804. ? keysOrMapper.reduce((reduced, key) => {
  1805. reduced[key] = function () {
  1806. // @ts-expect-error: FIXME: should work?
  1807. return useStore(this.$pinia)[key];
  1808. };
  1809. return reduced;
  1810. }, {})
  1811. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1812. // @ts-expect-error
  1813. reduced[key] = function () {
  1814. const store = useStore(this.$pinia);
  1815. const storeKey = keysOrMapper[key];
  1816. // for some reason TS is unable to infer the type of storeKey to be a
  1817. // function
  1818. return typeof storeKey === 'function'
  1819. ? storeKey.call(this, store)
  1820. : // @ts-expect-error: FIXME: should work?
  1821. store[storeKey];
  1822. };
  1823. return reduced;
  1824. }, {});
  1825. }
  1826. /**
  1827. * Alias for `mapState()`. You should use `mapState()` instead.
  1828. * @deprecated use `mapState()` instead.
  1829. */
  1830. const mapGetters = mapState;
  1831. /**
  1832. * Allows directly using actions from your store without using the composition
  1833. * API (`setup()`) by generating an object to be spread in the `methods` field
  1834. * of a component.
  1835. *
  1836. * @param useStore - store to map from
  1837. * @param keysOrMapper - array or object
  1838. */
  1839. function mapActions(useStore, keysOrMapper) {
  1840. return Array.isArray(keysOrMapper)
  1841. ? keysOrMapper.reduce((reduced, key) => {
  1842. // @ts-expect-error
  1843. reduced[key] = function (...args) {
  1844. // @ts-expect-error: FIXME: should work?
  1845. return useStore(this.$pinia)[key](...args);
  1846. };
  1847. return reduced;
  1848. }, {})
  1849. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1850. // @ts-expect-error
  1851. reduced[key] = function (...args) {
  1852. // @ts-expect-error: FIXME: should work?
  1853. return useStore(this.$pinia)[keysOrMapper[key]](...args);
  1854. };
  1855. return reduced;
  1856. }, {});
  1857. }
  1858. /**
  1859. * Allows using state and getters from one store without using the composition
  1860. * API (`setup()`) by generating an object to be spread in the `computed` field
  1861. * of a component.
  1862. *
  1863. * @param useStore - store to map from
  1864. * @param keysOrMapper - array or object
  1865. */
  1866. function mapWritableState(useStore, keysOrMapper) {
  1867. return Array.isArray(keysOrMapper)
  1868. ? keysOrMapper.reduce((reduced, key) => {
  1869. reduced[key] = {
  1870. get() {
  1871. return useStore(this.$pinia)[key];
  1872. },
  1873. set(value) {
  1874. return (useStore(this.$pinia)[key] = value);
  1875. },
  1876. };
  1877. return reduced;
  1878. }, {})
  1879. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1880. reduced[key] = {
  1881. get() {
  1882. return useStore(this.$pinia)[keysOrMapper[key]];
  1883. },
  1884. set(value) {
  1885. return (useStore(this.$pinia)[keysOrMapper[key]] = value);
  1886. },
  1887. };
  1888. return reduced;
  1889. }, {});
  1890. }
  1891. /**
  1892. * Creates an object of references with all the state, getters, and plugin-added
  1893. * state properties of the store. Similar to `toRefs()` but specifically
  1894. * designed for Pinia stores so methods and non reactive properties are
  1895. * completely ignored.
  1896. *
  1897. * @param store - store to extract the refs from
  1898. */
  1899. function storeToRefs(store) {
  1900. const rawStore = toRaw(store);
  1901. const refs = {};
  1902. for (const key in rawStore) {
  1903. const value = rawStore[key];
  1904. // There is no native method to check for a computed
  1905. // https://github.com/vuejs/core/pull/4165
  1906. if (value.effect) {
  1907. // @ts-expect-error: too hard to type correctly
  1908. refs[key] =
  1909. // ...
  1910. computed({
  1911. get: () => store[key],
  1912. set(value) {
  1913. store[key] = value;
  1914. },
  1915. });
  1916. }
  1917. else if (isRef(value) || isReactive(value)) {
  1918. // @ts-expect-error: the key is state or getter
  1919. refs[key] =
  1920. // ---
  1921. toRef(store, key);
  1922. }
  1923. }
  1924. return refs;
  1925. }
  1926. export { MutationType, acceptHMRUpdate, createPinia, defineStore, disposePinia, getActivePinia, mapActions, mapGetters, mapState, mapStores, mapWritableState, setActivePinia, setMapStoreSuffix, shouldHydrate, skipHydrate, storeToRefs };