pinia.esm-browser.js 72 KB

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