pinia.cjs 73 KB

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