pinia.esm-browser.js 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036
  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 = (Symbol('pinia') );
  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 (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 (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. return (newModule) => {
  1084. const pinia = hot.data.pinia || initialUseStore._pinia;
  1085. if (!pinia) {
  1086. // this store is still not used
  1087. return;
  1088. }
  1089. // preserve the pinia instance across loads
  1090. hot.data.pinia = pinia;
  1091. // console.log('got data', newStore)
  1092. for (const exportName in newModule) {
  1093. const useStore = newModule[exportName];
  1094. // console.log('checking for', exportName)
  1095. if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {
  1096. // console.log('Accepting update for', useStore.$id)
  1097. const id = useStore.$id;
  1098. if (id !== initialUseStore.$id) {
  1099. console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`);
  1100. // return import.meta.hot.invalidate()
  1101. return hot.invalidate();
  1102. }
  1103. const existingStore = pinia._s.get(id);
  1104. if (!existingStore) {
  1105. console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
  1106. return;
  1107. }
  1108. useStore(pinia, existingStore);
  1109. }
  1110. }
  1111. };
  1112. }
  1113. const noop = () => { };
  1114. function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
  1115. subscriptions.push(callback);
  1116. const removeSubscription = () => {
  1117. const idx = subscriptions.indexOf(callback);
  1118. if (idx > -1) {
  1119. subscriptions.splice(idx, 1);
  1120. onCleanup();
  1121. }
  1122. };
  1123. if (!detached && getCurrentScope()) {
  1124. onScopeDispose(removeSubscription);
  1125. }
  1126. return removeSubscription;
  1127. }
  1128. function triggerSubscriptions(subscriptions, ...args) {
  1129. subscriptions.slice().forEach((callback) => {
  1130. callback(...args);
  1131. });
  1132. }
  1133. const fallbackRunWithContext = (fn) => fn();
  1134. /**
  1135. * Marks a function as an action for `$onAction`
  1136. * @internal
  1137. */
  1138. const ACTION_MARKER = Symbol();
  1139. /**
  1140. * Action name symbol. Allows to add a name to an action after defining it
  1141. * @internal
  1142. */
  1143. const ACTION_NAME = Symbol();
  1144. function mergeReactiveObjects(target, patchToApply) {
  1145. // Handle Map instances
  1146. if (target instanceof Map && patchToApply instanceof Map) {
  1147. patchToApply.forEach((value, key) => target.set(key, value));
  1148. }
  1149. else if (target instanceof Set && patchToApply instanceof Set) {
  1150. // Handle Set instances
  1151. patchToApply.forEach(target.add, target);
  1152. }
  1153. // no need to go through symbols because they cannot be serialized anyway
  1154. for (const key in patchToApply) {
  1155. if (!patchToApply.hasOwnProperty(key))
  1156. continue;
  1157. const subPatch = patchToApply[key];
  1158. const targetValue = target[key];
  1159. if (isPlainObject(targetValue) &&
  1160. isPlainObject(subPatch) &&
  1161. target.hasOwnProperty(key) &&
  1162. !isRef(subPatch) &&
  1163. !isReactive(subPatch)) {
  1164. // NOTE: here I wanted to warn about inconsistent types but it's not possible because in setup stores one might
  1165. // start the value of a property as a certain type e.g. a Map, and then for some reason, during SSR, change that
  1166. // to `undefined`. When trying to hydrate, we want to override the Map with `undefined`.
  1167. target[key] = mergeReactiveObjects(targetValue, subPatch);
  1168. }
  1169. else {
  1170. // @ts-expect-error: subPatch is a valid value
  1171. target[key] = subPatch;
  1172. }
  1173. }
  1174. return target;
  1175. }
  1176. const skipHydrateSymbol = Symbol('pinia:skipHydration')
  1177. ;
  1178. /**
  1179. * Tells Pinia to skip the hydration process of a given object. This is useful in setup stores (only) when you return a
  1180. * stateful object in the store but it isn't really state. e.g. returning a router instance in a setup store.
  1181. *
  1182. * @param obj - target object
  1183. * @returns obj
  1184. */
  1185. function skipHydrate(obj) {
  1186. return Object.defineProperty(obj, skipHydrateSymbol, {});
  1187. }
  1188. /**
  1189. * Returns whether a value should be hydrated
  1190. *
  1191. * @param obj - target variable
  1192. * @returns true if `obj` should be hydrated
  1193. */
  1194. function shouldHydrate(obj) {
  1195. return !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
  1196. }
  1197. const { assign } = Object;
  1198. function isComputed(o) {
  1199. return !!(isRef(o) && o.effect);
  1200. }
  1201. function createOptionsStore(id, options, pinia, hot) {
  1202. const { state, actions, getters } = options;
  1203. const initialState = pinia.state.value[id];
  1204. let store;
  1205. function setup() {
  1206. if (!initialState && (!hot)) {
  1207. /* istanbul ignore if */
  1208. if (isVue2) {
  1209. set(pinia.state.value, id, state ? state() : {});
  1210. }
  1211. else {
  1212. pinia.state.value[id] = state ? state() : {};
  1213. }
  1214. }
  1215. // avoid creating a state in pinia.state.value
  1216. const localState = hot
  1217. ? // use ref() to unwrap refs inside state TODO: check if this is still necessary
  1218. toRefs(ref(state ? state() : {}).value)
  1219. : toRefs(pinia.state.value[id]);
  1220. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  1221. if (name in localState) {
  1222. console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`);
  1223. }
  1224. computedGetters[name] = markRaw(computed(() => {
  1225. setActivePinia(pinia);
  1226. // it was created just before
  1227. const store = pinia._s.get(id);
  1228. // allow cross using stores
  1229. /* istanbul ignore if */
  1230. if (isVue2 && !store._r)
  1231. return;
  1232. // @ts-expect-error
  1233. // return getters![name].call(context, context)
  1234. // TODO: avoid reading the getter while assigning with a global variable
  1235. return getters[name].call(store, store);
  1236. }));
  1237. return computedGetters;
  1238. }, {}));
  1239. }
  1240. store = createSetupStore(id, setup, options, pinia, hot, true);
  1241. return store;
  1242. }
  1243. function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  1244. let scope;
  1245. const optionsForPlugin = assign({ actions: {} }, options);
  1246. /* istanbul ignore if */
  1247. if (!pinia._e.active) {
  1248. throw new Error('Pinia destroyed');
  1249. }
  1250. // watcher options for $subscribe
  1251. const $subscribeOptions = { deep: true };
  1252. /* istanbul ignore else */
  1253. if (!isVue2) {
  1254. $subscribeOptions.onTrigger = (event) => {
  1255. /* istanbul ignore else */
  1256. if (isListening) {
  1257. debuggerEvents = event;
  1258. // avoid triggering this while the store is being built and the state is being set in pinia
  1259. }
  1260. else if (isListening == false && !store._hotUpdating) {
  1261. // let patch send all the events together later
  1262. /* istanbul ignore else */
  1263. if (Array.isArray(debuggerEvents)) {
  1264. debuggerEvents.push(event);
  1265. }
  1266. else {
  1267. console.error('🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.');
  1268. }
  1269. }
  1270. };
  1271. }
  1272. // internal state
  1273. let isListening; // set to true at the end
  1274. let isSyncListening; // set to true at the end
  1275. let subscriptions = [];
  1276. let actionSubscriptions = [];
  1277. let debuggerEvents;
  1278. const initialState = pinia.state.value[$id];
  1279. // avoid setting the state for option stores if it is set
  1280. // by the setup
  1281. if (!isOptionsStore && !initialState && (!hot)) {
  1282. /* istanbul ignore if */
  1283. if (isVue2) {
  1284. set(pinia.state.value, $id, {});
  1285. }
  1286. else {
  1287. pinia.state.value[$id] = {};
  1288. }
  1289. }
  1290. const hotState = ref({});
  1291. // avoid triggering too many listeners
  1292. // https://github.com/vuejs/pinia/issues/1129
  1293. let activeListener;
  1294. function $patch(partialStateOrMutator) {
  1295. let subscriptionMutation;
  1296. isListening = isSyncListening = false;
  1297. // reset the debugger events since patches are sync
  1298. /* istanbul ignore else */
  1299. {
  1300. debuggerEvents = [];
  1301. }
  1302. if (typeof partialStateOrMutator === 'function') {
  1303. partialStateOrMutator(pinia.state.value[$id]);
  1304. subscriptionMutation = {
  1305. type: MutationType.patchFunction,
  1306. storeId: $id,
  1307. events: debuggerEvents,
  1308. };
  1309. }
  1310. else {
  1311. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  1312. subscriptionMutation = {
  1313. type: MutationType.patchObject,
  1314. payload: partialStateOrMutator,
  1315. storeId: $id,
  1316. events: debuggerEvents,
  1317. };
  1318. }
  1319. const myListenerId = (activeListener = Symbol());
  1320. nextTick().then(() => {
  1321. if (activeListener === myListenerId) {
  1322. isListening = true;
  1323. }
  1324. });
  1325. isSyncListening = true;
  1326. // because we paused the watcher, we need to manually call the subscriptions
  1327. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  1328. }
  1329. const $reset = isOptionsStore
  1330. ? function $reset() {
  1331. const { state } = options;
  1332. const newState = state ? state() : {};
  1333. // we use a patch to group all changes into one single subscription
  1334. this.$patch(($state) => {
  1335. // @ts-expect-error: FIXME: shouldn't error?
  1336. assign($state, newState);
  1337. });
  1338. }
  1339. : /* istanbul ignore next */
  1340. () => {
  1341. throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
  1342. }
  1343. ;
  1344. function $dispose() {
  1345. scope.stop();
  1346. subscriptions = [];
  1347. actionSubscriptions = [];
  1348. pinia._s.delete($id);
  1349. }
  1350. /**
  1351. * Helper that wraps function so it can be tracked with $onAction
  1352. * @param fn - action to wrap
  1353. * @param name - name of the action
  1354. */
  1355. const action = (fn, name = '') => {
  1356. if (ACTION_MARKER in fn) {
  1357. fn[ACTION_NAME] = name;
  1358. return fn;
  1359. }
  1360. const wrappedAction = function () {
  1361. setActivePinia(pinia);
  1362. const args = Array.from(arguments);
  1363. const afterCallbackList = [];
  1364. const onErrorCallbackList = [];
  1365. function after(callback) {
  1366. afterCallbackList.push(callback);
  1367. }
  1368. function onError(callback) {
  1369. onErrorCallbackList.push(callback);
  1370. }
  1371. // @ts-expect-error
  1372. triggerSubscriptions(actionSubscriptions, {
  1373. args,
  1374. name: wrappedAction[ACTION_NAME],
  1375. store,
  1376. after,
  1377. onError,
  1378. });
  1379. let ret;
  1380. try {
  1381. ret = fn.apply(this && this.$id === $id ? this : store, args);
  1382. // handle sync errors
  1383. }
  1384. catch (error) {
  1385. triggerSubscriptions(onErrorCallbackList, error);
  1386. throw error;
  1387. }
  1388. if (ret instanceof Promise) {
  1389. return ret
  1390. .then((value) => {
  1391. triggerSubscriptions(afterCallbackList, value);
  1392. return value;
  1393. })
  1394. .catch((error) => {
  1395. triggerSubscriptions(onErrorCallbackList, error);
  1396. return Promise.reject(error);
  1397. });
  1398. }
  1399. // trigger after callbacks
  1400. triggerSubscriptions(afterCallbackList, ret);
  1401. return ret;
  1402. };
  1403. wrappedAction[ACTION_MARKER] = true;
  1404. wrappedAction[ACTION_NAME] = name; // will be set later
  1405. // @ts-expect-error: we are intentionally limiting the returned type to just Fn
  1406. // because all the added properties are internals that are exposed through `$onAction()` only
  1407. return wrappedAction;
  1408. };
  1409. const _hmrPayload = /*#__PURE__*/ markRaw({
  1410. actions: {},
  1411. getters: {},
  1412. state: [],
  1413. hotState,
  1414. });
  1415. const partialStore = {
  1416. _p: pinia,
  1417. // _s: scope,
  1418. $id,
  1419. $onAction: addSubscription.bind(null, actionSubscriptions),
  1420. $patch,
  1421. $reset,
  1422. $subscribe(callback, options = {}) {
  1423. const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher());
  1424. const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => {
  1425. if (options.flush === 'sync' ? isSyncListening : isListening) {
  1426. callback({
  1427. storeId: $id,
  1428. type: MutationType.direct,
  1429. events: debuggerEvents,
  1430. }, state);
  1431. }
  1432. }, assign({}, $subscribeOptions, options)));
  1433. return removeSubscription;
  1434. },
  1435. $dispose,
  1436. };
  1437. /* istanbul ignore if */
  1438. if (isVue2) {
  1439. // start as non ready
  1440. partialStore._r = false;
  1441. }
  1442. const store = reactive(assign({
  1443. _hmrPayload,
  1444. _customProperties: markRaw(new Set()), // devtools custom properties
  1445. }, partialStore
  1446. // must be added later
  1447. // setupStore
  1448. )
  1449. );
  1450. // store the partial store now so the setup of stores can instantiate each other before they are finished without
  1451. // creating infinite loops.
  1452. pinia._s.set($id, store);
  1453. const runWithContext = (pinia._a && pinia._a.runWithContext) || fallbackRunWithContext;
  1454. // TODO: idea create skipSerialize that marks properties as non serializable and they are skipped
  1455. const setupStore = runWithContext(() => pinia._e.run(() => (scope = effectScope()).run(() => setup({ action }))));
  1456. // overwrite existing actions to support $onAction
  1457. for (const key in setupStore) {
  1458. const prop = setupStore[key];
  1459. if ((isRef(prop) && !isComputed(prop)) || isReactive(prop)) {
  1460. // mark it as a piece of state to be serialized
  1461. if (hot) {
  1462. set(hotState.value, key, toRef(setupStore, key));
  1463. // createOptionStore directly sets the state in pinia.state.value so we
  1464. // can just skip that
  1465. }
  1466. else if (!isOptionsStore) {
  1467. // in setup stores we must hydrate the state and sync pinia state tree with the refs the user just created
  1468. if (initialState && shouldHydrate(prop)) {
  1469. if (isRef(prop)) {
  1470. prop.value = initialState[key];
  1471. }
  1472. else {
  1473. // probably a reactive object, lets recursively assign
  1474. // @ts-expect-error: prop is unknown
  1475. mergeReactiveObjects(prop, initialState[key]);
  1476. }
  1477. }
  1478. // transfer the ref to the pinia state to keep everything in sync
  1479. /* istanbul ignore if */
  1480. if (isVue2) {
  1481. set(pinia.state.value[$id], key, prop);
  1482. }
  1483. else {
  1484. pinia.state.value[$id][key] = prop;
  1485. }
  1486. }
  1487. /* istanbul ignore else */
  1488. {
  1489. _hmrPayload.state.push(key);
  1490. }
  1491. // action
  1492. }
  1493. else if (typeof prop === 'function') {
  1494. const actionValue = hot ? prop : action(prop, key);
  1495. // this a hot module replacement store because the hotUpdate method needs
  1496. // to do it with the right context
  1497. /* istanbul ignore if */
  1498. if (isVue2) {
  1499. set(setupStore, key, actionValue);
  1500. }
  1501. else {
  1502. // @ts-expect-error
  1503. setupStore[key] = actionValue;
  1504. }
  1505. /* istanbul ignore else */
  1506. {
  1507. _hmrPayload.actions[key] = prop;
  1508. }
  1509. // list actions so they can be used in plugins
  1510. // @ts-expect-error
  1511. optionsForPlugin.actions[key] = prop;
  1512. }
  1513. else {
  1514. // add getters for devtools
  1515. if (isComputed(prop)) {
  1516. _hmrPayload.getters[key] = isOptionsStore
  1517. ? // @ts-expect-error
  1518. options.getters[key]
  1519. : prop;
  1520. if (IS_CLIENT) {
  1521. const getters = setupStore._getters ||
  1522. // @ts-expect-error: same
  1523. (setupStore._getters = markRaw([]));
  1524. getters.push(key);
  1525. }
  1526. }
  1527. }
  1528. }
  1529. // add the state, getters, and action properties
  1530. /* istanbul ignore if */
  1531. if (isVue2) {
  1532. Object.keys(setupStore).forEach((key) => {
  1533. set(store, key, setupStore[key]);
  1534. });
  1535. }
  1536. else {
  1537. assign(store, setupStore);
  1538. // allows retrieving reactive objects with `storeToRefs()`. Must be called after assigning to the reactive object.
  1539. // Make `storeToRefs()` work with `reactive()` #799
  1540. assign(toRaw(store), setupStore);
  1541. }
  1542. // use this instead of a computed with setter to be able to create it anywhere
  1543. // without linking the computed lifespan to wherever the store is first
  1544. // created.
  1545. Object.defineProperty(store, '$state', {
  1546. get: () => (hot ? hotState.value : pinia.state.value[$id]),
  1547. set: (state) => {
  1548. /* istanbul ignore if */
  1549. if (hot) {
  1550. throw new Error('cannot set hotState');
  1551. }
  1552. $patch(($state) => {
  1553. // @ts-expect-error: FIXME: shouldn't error?
  1554. assign($state, state);
  1555. });
  1556. },
  1557. });
  1558. // add the hotUpdate before plugins to allow them to override it
  1559. /* istanbul ignore else */
  1560. {
  1561. store._hotUpdate = markRaw((newStore) => {
  1562. store._hotUpdating = true;
  1563. newStore._hmrPayload.state.forEach((stateKey) => {
  1564. if (stateKey in store.$state) {
  1565. const newStateTarget = newStore.$state[stateKey];
  1566. const oldStateSource = store.$state[stateKey];
  1567. if (typeof newStateTarget === 'object' &&
  1568. isPlainObject(newStateTarget) &&
  1569. isPlainObject(oldStateSource)) {
  1570. patchObject(newStateTarget, oldStateSource);
  1571. }
  1572. else {
  1573. // transfer the ref
  1574. newStore.$state[stateKey] = oldStateSource;
  1575. }
  1576. }
  1577. // patch direct access properties to allow store.stateProperty to work as
  1578. // store.$state.stateProperty
  1579. set(store, stateKey, toRef(newStore.$state, stateKey));
  1580. });
  1581. // remove deleted state properties
  1582. Object.keys(store.$state).forEach((stateKey) => {
  1583. if (!(stateKey in newStore.$state)) {
  1584. del(store, stateKey);
  1585. }
  1586. });
  1587. // avoid devtools logging this as a mutation
  1588. isListening = false;
  1589. isSyncListening = false;
  1590. pinia.state.value[$id] = toRef(newStore._hmrPayload, 'hotState');
  1591. isSyncListening = true;
  1592. nextTick().then(() => {
  1593. isListening = true;
  1594. });
  1595. for (const actionName in newStore._hmrPayload.actions) {
  1596. const actionFn = newStore[actionName];
  1597. set(store, actionName, action(actionFn, actionName));
  1598. }
  1599. // TODO: does this work in both setup and option store?
  1600. for (const getterName in newStore._hmrPayload.getters) {
  1601. const getter = newStore._hmrPayload.getters[getterName];
  1602. const getterValue = isOptionsStore
  1603. ? // special handling of options api
  1604. computed(() => {
  1605. setActivePinia(pinia);
  1606. return getter.call(store, store);
  1607. })
  1608. : getter;
  1609. set(store, getterName, getterValue);
  1610. }
  1611. // remove deleted getters
  1612. Object.keys(store._hmrPayload.getters).forEach((key) => {
  1613. if (!(key in newStore._hmrPayload.getters)) {
  1614. del(store, key);
  1615. }
  1616. });
  1617. // remove old actions
  1618. Object.keys(store._hmrPayload.actions).forEach((key) => {
  1619. if (!(key in newStore._hmrPayload.actions)) {
  1620. del(store, key);
  1621. }
  1622. });
  1623. // update the values used in devtools and to allow deleting new properties later on
  1624. store._hmrPayload = newStore._hmrPayload;
  1625. store._getters = newStore._getters;
  1626. store._hotUpdating = false;
  1627. });
  1628. }
  1629. if (IS_CLIENT) {
  1630. const nonEnumerable = {
  1631. writable: true,
  1632. configurable: true,
  1633. // avoid warning on devtools trying to display this property
  1634. enumerable: false,
  1635. };
  1636. ['_p', '_hmrPayload', '_getters', '_customProperties'].forEach((p) => {
  1637. Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));
  1638. });
  1639. }
  1640. /* istanbul ignore if */
  1641. if (isVue2) {
  1642. // mark the store as ready before plugins
  1643. store._r = true;
  1644. }
  1645. // apply all plugins
  1646. pinia._p.forEach((extender) => {
  1647. /* istanbul ignore else */
  1648. if (IS_CLIENT) {
  1649. const extensions = scope.run(() => extender({
  1650. store: store,
  1651. app: pinia._a,
  1652. pinia,
  1653. options: optionsForPlugin,
  1654. }));
  1655. Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
  1656. assign(store, extensions);
  1657. }
  1658. else {
  1659. assign(store, scope.run(() => extender({
  1660. store: store,
  1661. app: pinia._a,
  1662. pinia,
  1663. options: optionsForPlugin,
  1664. })));
  1665. }
  1666. });
  1667. if (store.$state &&
  1668. typeof store.$state === 'object' &&
  1669. typeof store.$state.constructor === 'function' &&
  1670. !store.$state.constructor.toString().includes('[native code]')) {
  1671. console.warn(`[🍍]: The "state" must be a plain object. It cannot be\n` +
  1672. `\tstate: () => new MyClass()\n` +
  1673. `Found in store "${store.$id}".`);
  1674. }
  1675. // only apply hydrate to option stores with an initial state in pinia
  1676. if (initialState &&
  1677. isOptionsStore &&
  1678. options.hydrate) {
  1679. options.hydrate(store.$state, initialState);
  1680. }
  1681. isListening = true;
  1682. isSyncListening = true;
  1683. return store;
  1684. }
  1685. // allows unused stores to be tree shaken
  1686. /*! #__NO_SIDE_EFFECTS__ */
  1687. function defineStore(
  1688. // TODO: add proper types from above
  1689. idOrOptions, setup, setupOptions) {
  1690. let id;
  1691. let options;
  1692. const isSetupStore = typeof setup === 'function';
  1693. if (typeof idOrOptions === 'string') {
  1694. id = idOrOptions;
  1695. // the option store setup will contain the actual options in this case
  1696. options = isSetupStore ? setupOptions : setup;
  1697. }
  1698. else {
  1699. options = idOrOptions;
  1700. id = idOrOptions.id;
  1701. if (typeof id !== 'string') {
  1702. throw new Error(`[🍍]: "defineStore()" must be passed a store id as its first argument.`);
  1703. }
  1704. }
  1705. function useStore(pinia, hot) {
  1706. const hasContext = hasInjectionContext();
  1707. pinia =
  1708. // in test mode, ignore the argument provided as we can always retrieve a
  1709. // pinia instance with getActivePinia()
  1710. (pinia) ||
  1711. (hasContext ? inject(piniaSymbol, null) : null);
  1712. if (pinia)
  1713. setActivePinia(pinia);
  1714. if (!activePinia) {
  1715. 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` +
  1716. `See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.\n` +
  1717. `This will fail in production.`);
  1718. }
  1719. pinia = activePinia;
  1720. if (!pinia._s.has(id)) {
  1721. // creating the store registers it in `pinia._s`
  1722. if (isSetupStore) {
  1723. createSetupStore(id, setup, options, pinia);
  1724. }
  1725. else {
  1726. createOptionsStore(id, options, pinia);
  1727. }
  1728. /* istanbul ignore else */
  1729. {
  1730. // @ts-expect-error: not the right inferred type
  1731. useStore._pinia = pinia;
  1732. }
  1733. }
  1734. const store = pinia._s.get(id);
  1735. if (hot) {
  1736. const hotId = '__hot:' + id;
  1737. const newStore = isSetupStore
  1738. ? createSetupStore(hotId, setup, options, pinia, true)
  1739. : createOptionsStore(hotId, assign({}, options), pinia, true);
  1740. hot._hotUpdate(newStore);
  1741. // cleanup the state properties and the store from the cache
  1742. delete pinia.state.value[hotId];
  1743. pinia._s.delete(hotId);
  1744. }
  1745. if (IS_CLIENT) {
  1746. const currentInstance = getCurrentInstance();
  1747. // save stores in instances to access them devtools
  1748. if (currentInstance &&
  1749. currentInstance.proxy &&
  1750. // avoid adding stores that are just built for hot module replacement
  1751. !hot) {
  1752. const vm = currentInstance.proxy;
  1753. const cache = '_pStores' in vm ? vm._pStores : (vm._pStores = {});
  1754. cache[id] = store;
  1755. }
  1756. }
  1757. // StoreGeneric cannot be casted towards Store
  1758. return store;
  1759. }
  1760. useStore.$id = id;
  1761. return useStore;
  1762. }
  1763. let mapStoreSuffix = 'Store';
  1764. /**
  1765. * Changes the suffix added by `mapStores()`. Can be set to an empty string.
  1766. * Defaults to `"Store"`. Make sure to extend the MapStoresCustomization
  1767. * interface if you are using TypeScript.
  1768. *
  1769. * @param suffix - new suffix
  1770. */
  1771. function setMapStoreSuffix(suffix // could be 'Store' but that would be annoying for JS
  1772. ) {
  1773. mapStoreSuffix = suffix;
  1774. }
  1775. /**
  1776. * Allows using stores without the composition API (`setup()`) by generating an
  1777. * object to be spread in the `computed` field of a component. It accepts a list
  1778. * of store definitions.
  1779. *
  1780. * @example
  1781. * ```js
  1782. * export default {
  1783. * computed: {
  1784. * // other computed properties
  1785. * ...mapStores(useUserStore, useCartStore)
  1786. * },
  1787. *
  1788. * created() {
  1789. * this.userStore // store with id "user"
  1790. * this.cartStore // store with id "cart"
  1791. * }
  1792. * }
  1793. * ```
  1794. *
  1795. * @param stores - list of stores to map to an object
  1796. */
  1797. function mapStores(...stores) {
  1798. if (Array.isArray(stores[0])) {
  1799. console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:\n` +
  1800. `Replace\n` +
  1801. `\tmapStores([useAuthStore, useCartStore])\n` +
  1802. `with\n` +
  1803. `\tmapStores(useAuthStore, useCartStore)\n` +
  1804. `This will fail in production if not fixed.`);
  1805. stores = stores[0];
  1806. }
  1807. return stores.reduce((reduced, useStore) => {
  1808. // @ts-expect-error: $id is added by defineStore
  1809. reduced[useStore.$id + mapStoreSuffix] = function () {
  1810. return useStore(this.$pinia);
  1811. };
  1812. return reduced;
  1813. }, {});
  1814. }
  1815. /**
  1816. * Allows using state and getters from one store without using the composition
  1817. * API (`setup()`) by generating an object to be spread in the `computed` field
  1818. * of a component.
  1819. *
  1820. * @param useStore - store to map from
  1821. * @param keysOrMapper - array or object
  1822. */
  1823. function mapState(useStore, keysOrMapper) {
  1824. return Array.isArray(keysOrMapper)
  1825. ? keysOrMapper.reduce((reduced, key) => {
  1826. reduced[key] = function () {
  1827. // @ts-expect-error: FIXME: should work?
  1828. return useStore(this.$pinia)[key];
  1829. };
  1830. return reduced;
  1831. }, {})
  1832. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1833. // @ts-expect-error
  1834. reduced[key] = function () {
  1835. const store = useStore(this.$pinia);
  1836. const storeKey = keysOrMapper[key];
  1837. // for some reason TS is unable to infer the type of storeKey to be a
  1838. // function
  1839. return typeof storeKey === 'function'
  1840. ? storeKey.call(this, store)
  1841. : // @ts-expect-error: FIXME: should work?
  1842. store[storeKey];
  1843. };
  1844. return reduced;
  1845. }, {});
  1846. }
  1847. /**
  1848. * Alias for `mapState()`. You should use `mapState()` instead.
  1849. * @deprecated use `mapState()` instead.
  1850. */
  1851. const mapGetters = mapState;
  1852. /**
  1853. * Allows directly using actions from your store without using the composition
  1854. * API (`setup()`) by generating an object to be spread in the `methods` field
  1855. * of a component.
  1856. *
  1857. * @param useStore - store to map from
  1858. * @param keysOrMapper - array or object
  1859. */
  1860. function mapActions(useStore, keysOrMapper) {
  1861. return Array.isArray(keysOrMapper)
  1862. ? keysOrMapper.reduce((reduced, key) => {
  1863. // @ts-expect-error
  1864. reduced[key] = function (...args) {
  1865. // @ts-expect-error: FIXME: should work?
  1866. return useStore(this.$pinia)[key](...args);
  1867. };
  1868. return reduced;
  1869. }, {})
  1870. : Object.keys(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)[keysOrMapper[key]](...args);
  1875. };
  1876. return reduced;
  1877. }, {});
  1878. }
  1879. /**
  1880. * Allows using state and getters from one store without using the composition
  1881. * API (`setup()`) by generating an object to be spread in the `computed` field
  1882. * of a component.
  1883. *
  1884. * @param useStore - store to map from
  1885. * @param keysOrMapper - array or object
  1886. */
  1887. function mapWritableState(useStore, keysOrMapper) {
  1888. return Array.isArray(keysOrMapper)
  1889. ? keysOrMapper.reduce((reduced, key) => {
  1890. reduced[key] = {
  1891. get() {
  1892. return useStore(this.$pinia)[key];
  1893. },
  1894. set(value) {
  1895. return (useStore(this.$pinia)[key] = value);
  1896. },
  1897. };
  1898. return reduced;
  1899. }, {})
  1900. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1901. reduced[key] = {
  1902. get() {
  1903. return useStore(this.$pinia)[keysOrMapper[key]];
  1904. },
  1905. set(value) {
  1906. return (useStore(this.$pinia)[keysOrMapper[key]] = value);
  1907. },
  1908. };
  1909. return reduced;
  1910. }, {});
  1911. }
  1912. /**
  1913. * Creates an object of references with all the state, getters, and plugin-added
  1914. * state properties of the store. Similar to `toRefs()` but specifically
  1915. * designed for Pinia stores so methods and non reactive properties are
  1916. * completely ignored.
  1917. *
  1918. * @param store - store to extract the refs from
  1919. */
  1920. function storeToRefs(store) {
  1921. // See https://github.com/vuejs/pinia/issues/852
  1922. // It's easier to just use toRefs() even if it includes more stuff
  1923. if (isVue2) {
  1924. // @ts-expect-error: toRefs include methods and others
  1925. return toRefs(store);
  1926. }
  1927. else {
  1928. const rawStore = toRaw(store);
  1929. const refs = {};
  1930. for (const key in rawStore) {
  1931. const value = rawStore[key];
  1932. // There is no native method to check for a computed
  1933. // https://github.com/vuejs/core/pull/4165
  1934. if (value.effect) {
  1935. // @ts-expect-error: too hard to type correctly
  1936. refs[key] =
  1937. // ...
  1938. computed({
  1939. get: () => store[key],
  1940. set(value) {
  1941. store[key] = value;
  1942. },
  1943. });
  1944. }
  1945. else if (isRef(value) || isReactive(value)) {
  1946. // @ts-expect-error: the key is state or getter
  1947. refs[key] =
  1948. // ---
  1949. toRef(store, key);
  1950. }
  1951. }
  1952. return refs;
  1953. }
  1954. }
  1955. /**
  1956. * Vue 2 Plugin that must be installed for pinia to work. Note **you don't need
  1957. * this plugin if you are using Nuxt.js**. Use the `buildModule` instead:
  1958. * https://pinia.vuejs.org/ssr/nuxt.html.
  1959. *
  1960. * @example
  1961. * ```js
  1962. * import Vue from 'vue'
  1963. * import { PiniaVuePlugin, createPinia } from 'pinia'
  1964. *
  1965. * Vue.use(PiniaVuePlugin)
  1966. * const pinia = createPinia()
  1967. *
  1968. * new Vue({
  1969. * el: '#app',
  1970. * // ...
  1971. * pinia,
  1972. * })
  1973. * ```
  1974. *
  1975. * @param _Vue - `Vue` imported from 'vue'.
  1976. */
  1977. const PiniaVuePlugin = function (_Vue) {
  1978. // Equivalent of
  1979. // app.config.globalProperties.$pinia = pinia
  1980. _Vue.mixin({
  1981. beforeCreate() {
  1982. const options = this.$options;
  1983. if (options.pinia) {
  1984. const pinia = options.pinia;
  1985. // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/main/src/apis/inject.ts#L31
  1986. /* istanbul ignore else */
  1987. if (!this._provided) {
  1988. const provideCache = {};
  1989. Object.defineProperty(this, '_provided', {
  1990. get: () => provideCache,
  1991. set: (v) => Object.assign(provideCache, v),
  1992. });
  1993. }
  1994. this._provided[piniaSymbol] = pinia;
  1995. // propagate the pinia instance in an SSR friendly way
  1996. // avoid adding it to nuxt twice
  1997. /* istanbul ignore else */
  1998. if (!this.$pinia) {
  1999. this.$pinia = pinia;
  2000. }
  2001. pinia._a = this;
  2002. if (IS_CLIENT) {
  2003. // this allows calling useStore() outside of a component setup after
  2004. // installing pinia's plugin
  2005. setActivePinia(pinia);
  2006. }
  2007. if (IS_CLIENT) {
  2008. registerPiniaDevtools(pinia._a, pinia);
  2009. }
  2010. }
  2011. else if (!this.$pinia && options.parent && options.parent.$pinia) {
  2012. this.$pinia = options.parent.$pinia;
  2013. }
  2014. },
  2015. destroyed() {
  2016. delete this._pStores;
  2017. },
  2018. });
  2019. };
  2020. export { MutationType, PiniaVuePlugin, acceptHMRUpdate, createPinia, defineStore, disposePinia, getActivePinia, mapActions, mapGetters, mapState, mapStores, mapWritableState, setActivePinia, setMapStoreSuffix, shouldHydrate, skipHydrate, storeToRefs };