pinia.mjs 75 KB

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