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.

1997 lines
71 KiB

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