pinia.iife.js 80 KB

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