You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2020 lines
73 KiB

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