pinia.iife.js 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  1. /*!
  2. * pinia v2.1.3
  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.hasInjectionContext() && 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 (with "$reset")',
  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 (typeof store.$reset !== 'function') {
  727. toastMessage(`Cannot reset "${nodeId}" store because it doesn't have a "$reset" method implemented.`, '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. const fallbackRunWithContext = (fn) => fn();
  1267. function mergeReactiveObjects(target, patchToApply) {
  1268. // Handle Map instances
  1269. if (target instanceof Map && patchToApply instanceof Map) {
  1270. patchToApply.forEach((value, key) => target.set(key, value));
  1271. }
  1272. // Handle Set instances
  1273. if (target instanceof Set && patchToApply instanceof Set) {
  1274. patchToApply.forEach(target.add, target);
  1275. }
  1276. // no need to go through symbols because they cannot be serialized anyway
  1277. for (const key in patchToApply) {
  1278. if (!patchToApply.hasOwnProperty(key))
  1279. continue;
  1280. const subPatch = patchToApply[key];
  1281. const targetValue = target[key];
  1282. if (isPlainObject(targetValue) &&
  1283. isPlainObject(subPatch) &&
  1284. target.hasOwnProperty(key) &&
  1285. !vueDemi.isRef(subPatch) &&
  1286. !vueDemi.isReactive(subPatch)) {
  1287. // NOTE: here I wanted to warn about inconsistent types but it's not possible because in setup stores one might
  1288. // start the value of a property as a certain type e.g. a Map, and then for some reason, during SSR, change that
  1289. // to `undefined`. When trying to hydrate, we want to override the Map with `undefined`.
  1290. target[key] = mergeReactiveObjects(targetValue, subPatch);
  1291. }
  1292. else {
  1293. // @ts-expect-error: subPatch is a valid value
  1294. target[key] = subPatch;
  1295. }
  1296. }
  1297. return target;
  1298. }
  1299. const skipHydrateSymbol = Symbol('pinia:skipHydration')
  1300. ;
  1301. const skipHydrateMap = /*#__PURE__*/ new WeakMap();
  1302. /**
  1303. * Tells Pinia to skip the hydration process of a given object. This is useful in setup stores (only) when you return a
  1304. * stateful object in the store but it isn't really state. e.g. returning a router instance in a setup store.
  1305. *
  1306. * @param obj - target object
  1307. * @returns obj
  1308. */
  1309. function skipHydrate(obj) {
  1310. return vueDemi.isVue2
  1311. ? // in @vue/composition-api, the refs are sealed so defineProperty doesn't work...
  1312. /* istanbul ignore next */ skipHydrateMap.set(obj, 1) && obj
  1313. : Object.defineProperty(obj, skipHydrateSymbol, {});
  1314. }
  1315. /**
  1316. * Returns whether a value should be hydrated
  1317. *
  1318. * @param obj - target variable
  1319. * @returns true if `obj` should be hydrated
  1320. */
  1321. function shouldHydrate(obj) {
  1322. return vueDemi.isVue2
  1323. ? /* istanbul ignore next */ !skipHydrateMap.has(obj)
  1324. : !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
  1325. }
  1326. const { assign } = Object;
  1327. function isComputed(o) {
  1328. return !!(vueDemi.isRef(o) && o.effect);
  1329. }
  1330. function createOptionsStore(id, options, pinia, hot) {
  1331. const { state, actions, getters } = options;
  1332. const initialState = pinia.state.value[id];
  1333. let store;
  1334. function setup() {
  1335. if (!initialState && (!hot)) {
  1336. /* istanbul ignore if */
  1337. if (vueDemi.isVue2) {
  1338. vueDemi.set(pinia.state.value, id, state ? state() : {});
  1339. }
  1340. else {
  1341. pinia.state.value[id] = state ? state() : {};
  1342. }
  1343. }
  1344. // avoid creating a state in pinia.state.value
  1345. const localState = hot
  1346. ? // use ref() to unwrap refs inside state TODO: check if this is still necessary
  1347. vueDemi.toRefs(vueDemi.ref(state ? state() : {}).value)
  1348. : vueDemi.toRefs(pinia.state.value[id]);
  1349. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  1350. if (name in localState) {
  1351. console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`);
  1352. }
  1353. computedGetters[name] = vueDemi.markRaw(vueDemi.computed(() => {
  1354. setActivePinia(pinia);
  1355. // it was created just before
  1356. const store = pinia._s.get(id);
  1357. // allow cross using stores
  1358. /* istanbul ignore next */
  1359. if (vueDemi.isVue2 && !store._r)
  1360. return;
  1361. // @ts-expect-error
  1362. // return getters![name].call(context, context)
  1363. // TODO: avoid reading the getter while assigning with a global variable
  1364. return getters[name].call(store, store);
  1365. }));
  1366. return computedGetters;
  1367. }, {}));
  1368. }
  1369. store = createSetupStore(id, setup, options, pinia, hot, true);
  1370. return store;
  1371. }
  1372. function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  1373. let scope;
  1374. const optionsForPlugin = assign({ actions: {} }, options);
  1375. /* istanbul ignore if */
  1376. if (!pinia._e.active) {
  1377. throw new Error('Pinia destroyed');
  1378. }
  1379. // watcher options for $subscribe
  1380. const $subscribeOptions = {
  1381. deep: true,
  1382. // flush: 'post',
  1383. };
  1384. /* istanbul ignore else */
  1385. if (!vueDemi.isVue2) {
  1386. $subscribeOptions.onTrigger = (event) => {
  1387. /* istanbul ignore else */
  1388. if (isListening) {
  1389. debuggerEvents = event;
  1390. // avoid triggering this while the store is being built and the state is being set in pinia
  1391. }
  1392. else if (isListening == false && !store._hotUpdating) {
  1393. // let patch send all the events together later
  1394. /* istanbul ignore else */
  1395. if (Array.isArray(debuggerEvents)) {
  1396. debuggerEvents.push(event);
  1397. }
  1398. else {
  1399. console.error('🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.');
  1400. }
  1401. }
  1402. };
  1403. }
  1404. // internal state
  1405. let isListening; // set to true at the end
  1406. let isSyncListening; // set to true at the end
  1407. let subscriptions = [];
  1408. let actionSubscriptions = [];
  1409. let debuggerEvents;
  1410. const initialState = pinia.state.value[$id];
  1411. // avoid setting the state for option stores if it is set
  1412. // by the setup
  1413. if (!isOptionsStore && !initialState && (!hot)) {
  1414. /* istanbul ignore if */
  1415. if (vueDemi.isVue2) {
  1416. vueDemi.set(pinia.state.value, $id, {});
  1417. }
  1418. else {
  1419. pinia.state.value[$id] = {};
  1420. }
  1421. }
  1422. const hotState = vueDemi.ref({});
  1423. // avoid triggering too many listeners
  1424. // https://github.com/vuejs/pinia/issues/1129
  1425. let activeListener;
  1426. function $patch(partialStateOrMutator) {
  1427. let subscriptionMutation;
  1428. isListening = isSyncListening = false;
  1429. // reset the debugger events since patches are sync
  1430. /* istanbul ignore else */
  1431. {
  1432. debuggerEvents = [];
  1433. }
  1434. if (typeof partialStateOrMutator === 'function') {
  1435. partialStateOrMutator(pinia.state.value[$id]);
  1436. subscriptionMutation = {
  1437. type: exports.MutationType.patchFunction,
  1438. storeId: $id,
  1439. events: debuggerEvents,
  1440. };
  1441. }
  1442. else {
  1443. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  1444. subscriptionMutation = {
  1445. type: exports.MutationType.patchObject,
  1446. payload: partialStateOrMutator,
  1447. storeId: $id,
  1448. events: debuggerEvents,
  1449. };
  1450. }
  1451. const myListenerId = (activeListener = Symbol());
  1452. vueDemi.nextTick().then(() => {
  1453. if (activeListener === myListenerId) {
  1454. isListening = true;
  1455. }
  1456. });
  1457. isSyncListening = true;
  1458. // because we paused the watcher, we need to manually call the subscriptions
  1459. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  1460. }
  1461. const $reset = isOptionsStore
  1462. ? function $reset() {
  1463. const { state } = options;
  1464. const newState = state ? state() : {};
  1465. // we use a patch to group all changes into one single subscription
  1466. this.$patch(($state) => {
  1467. assign($state, newState);
  1468. });
  1469. }
  1470. : /* istanbul ignore next */
  1471. () => {
  1472. throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
  1473. }
  1474. ;
  1475. function $dispose() {
  1476. scope.stop();
  1477. subscriptions = [];
  1478. actionSubscriptions = [];
  1479. pinia._s.delete($id);
  1480. }
  1481. /**
  1482. * Wraps an action to handle subscriptions.
  1483. *
  1484. * @param name - name of the action
  1485. * @param action - action to wrap
  1486. * @returns a wrapped action to handle subscriptions
  1487. */
  1488. function wrapAction(name, action) {
  1489. return function () {
  1490. setActivePinia(pinia);
  1491. const args = Array.from(arguments);
  1492. const afterCallbackList = [];
  1493. const onErrorCallbackList = [];
  1494. function after(callback) {
  1495. afterCallbackList.push(callback);
  1496. }
  1497. function onError(callback) {
  1498. onErrorCallbackList.push(callback);
  1499. }
  1500. // @ts-expect-error
  1501. triggerSubscriptions(actionSubscriptions, {
  1502. args,
  1503. name,
  1504. store,
  1505. after,
  1506. onError,
  1507. });
  1508. let ret;
  1509. try {
  1510. ret = action.apply(this && this.$id === $id ? this : store, args);
  1511. // handle sync errors
  1512. }
  1513. catch (error) {
  1514. triggerSubscriptions(onErrorCallbackList, error);
  1515. throw error;
  1516. }
  1517. if (ret instanceof Promise) {
  1518. return ret
  1519. .then((value) => {
  1520. triggerSubscriptions(afterCallbackList, value);
  1521. return value;
  1522. })
  1523. .catch((error) => {
  1524. triggerSubscriptions(onErrorCallbackList, error);
  1525. return Promise.reject(error);
  1526. });
  1527. }
  1528. // trigger after callbacks
  1529. triggerSubscriptions(afterCallbackList, ret);
  1530. return ret;
  1531. };
  1532. }
  1533. const _hmrPayload = /*#__PURE__*/ vueDemi.markRaw({
  1534. actions: {},
  1535. getters: {},
  1536. state: [],
  1537. hotState,
  1538. });
  1539. const partialStore = {
  1540. _p: pinia,
  1541. // _s: scope,
  1542. $id,
  1543. $onAction: addSubscription.bind(null, actionSubscriptions),
  1544. $patch,
  1545. $reset,
  1546. $subscribe(callback, options = {}) {
  1547. const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher());
  1548. const stopWatcher = scope.run(() => vueDemi.watch(() => pinia.state.value[$id], (state) => {
  1549. if (options.flush === 'sync' ? isSyncListening : isListening) {
  1550. callback({
  1551. storeId: $id,
  1552. type: exports.MutationType.direct,
  1553. events: debuggerEvents,
  1554. }, state);
  1555. }
  1556. }, assign({}, $subscribeOptions, options)));
  1557. return removeSubscription;
  1558. },
  1559. $dispose,
  1560. };
  1561. /* istanbul ignore if */
  1562. if (vueDemi.isVue2) {
  1563. // start as non ready
  1564. partialStore._r = false;
  1565. }
  1566. const store = vueDemi.reactive(assign({
  1567. _hmrPayload,
  1568. _customProperties: vueDemi.markRaw(new Set()), // devtools custom properties
  1569. }, partialStore
  1570. // must be added later
  1571. // setupStore
  1572. )
  1573. );
  1574. // store the partial store now so the setup of stores can instantiate each other before they are finished without
  1575. // creating infinite loops.
  1576. pinia._s.set($id, store);
  1577. const runWithContext = (pinia._a && pinia._a.runWithContext) || fallbackRunWithContext;
  1578. // TODO: idea create skipSerialize that marks properties as non serializable and they are skipped
  1579. const setupStore = pinia._e.run(() => {
  1580. scope = vueDemi.effectScope();
  1581. return runWithContext(() => scope.run(setup));
  1582. });
  1583. // overwrite existing actions to support $onAction
  1584. for (const key in setupStore) {
  1585. const prop = setupStore[key];
  1586. if ((vueDemi.isRef(prop) && !isComputed(prop)) || vueDemi.isReactive(prop)) {
  1587. // mark it as a piece of state to be serialized
  1588. if (hot) {
  1589. vueDemi.set(hotState.value, key, vueDemi.toRef(setupStore, key));
  1590. // createOptionStore directly sets the state in pinia.state.value so we
  1591. // can just skip that
  1592. }
  1593. else if (!isOptionsStore) {
  1594. // in setup stores we must hydrate the state and sync pinia state tree with the refs the user just created
  1595. if (initialState && shouldHydrate(prop)) {
  1596. if (vueDemi.isRef(prop)) {
  1597. prop.value = initialState[key];
  1598. }
  1599. else {
  1600. // probably a reactive object, lets recursively assign
  1601. // @ts-expect-error: prop is unknown
  1602. mergeReactiveObjects(prop, initialState[key]);
  1603. }
  1604. }
  1605. // transfer the ref to the pinia state to keep everything in sync
  1606. /* istanbul ignore if */
  1607. if (vueDemi.isVue2) {
  1608. vueDemi.set(pinia.state.value[$id], key, prop);
  1609. }
  1610. else {
  1611. pinia.state.value[$id][key] = prop;
  1612. }
  1613. }
  1614. /* istanbul ignore else */
  1615. {
  1616. _hmrPayload.state.push(key);
  1617. }
  1618. // action
  1619. }
  1620. else if (typeof prop === 'function') {
  1621. // @ts-expect-error: we are overriding the function we avoid wrapping if
  1622. const actionValue = hot ? prop : wrapAction(key, prop);
  1623. // this a hot module replacement store because the hotUpdate method needs
  1624. // to do it with the right context
  1625. /* istanbul ignore if */
  1626. if (vueDemi.isVue2) {
  1627. vueDemi.set(setupStore, key, actionValue);
  1628. }
  1629. else {
  1630. // @ts-expect-error
  1631. setupStore[key] = actionValue;
  1632. }
  1633. /* istanbul ignore else */
  1634. {
  1635. _hmrPayload.actions[key] = prop;
  1636. }
  1637. // list actions so they can be used in plugins
  1638. // @ts-expect-error
  1639. optionsForPlugin.actions[key] = prop;
  1640. }
  1641. else {
  1642. // add getters for devtools
  1643. if (isComputed(prop)) {
  1644. _hmrPayload.getters[key] = isOptionsStore
  1645. ? // @ts-expect-error
  1646. options.getters[key]
  1647. : prop;
  1648. if (IS_CLIENT) {
  1649. const getters = setupStore._getters ||
  1650. // @ts-expect-error: same
  1651. (setupStore._getters = vueDemi.markRaw([]));
  1652. getters.push(key);
  1653. }
  1654. }
  1655. }
  1656. }
  1657. // add the state, getters, and action properties
  1658. /* istanbul ignore if */
  1659. if (vueDemi.isVue2) {
  1660. Object.keys(setupStore).forEach((key) => {
  1661. vueDemi.set(store, key, setupStore[key]);
  1662. });
  1663. }
  1664. else {
  1665. assign(store, setupStore);
  1666. // allows retrieving reactive objects with `storeToRefs()`. Must be called after assigning to the reactive object.
  1667. // Make `storeToRefs()` work with `reactive()` #799
  1668. assign(vueDemi.toRaw(store), setupStore);
  1669. }
  1670. // use this instead of a computed with setter to be able to create it anywhere
  1671. // without linking the computed lifespan to wherever the store is first
  1672. // created.
  1673. Object.defineProperty(store, '$state', {
  1674. get: () => (hot ? hotState.value : pinia.state.value[$id]),
  1675. set: (state) => {
  1676. /* istanbul ignore if */
  1677. if (hot) {
  1678. throw new Error('cannot set hotState');
  1679. }
  1680. $patch(($state) => {
  1681. assign($state, state);
  1682. });
  1683. },
  1684. });
  1685. // add the hotUpdate before plugins to allow them to override it
  1686. /* istanbul ignore else */
  1687. {
  1688. store._hotUpdate = vueDemi.markRaw((newStore) => {
  1689. store._hotUpdating = true;
  1690. newStore._hmrPayload.state.forEach((stateKey) => {
  1691. if (stateKey in store.$state) {
  1692. const newStateTarget = newStore.$state[stateKey];
  1693. const oldStateSource = store.$state[stateKey];
  1694. if (typeof newStateTarget === 'object' &&
  1695. isPlainObject(newStateTarget) &&
  1696. isPlainObject(oldStateSource)) {
  1697. patchObject(newStateTarget, oldStateSource);
  1698. }
  1699. else {
  1700. // transfer the ref
  1701. newStore.$state[stateKey] = oldStateSource;
  1702. }
  1703. }
  1704. // patch direct access properties to allow store.stateProperty to work as
  1705. // store.$state.stateProperty
  1706. vueDemi.set(store, stateKey, vueDemi.toRef(newStore.$state, stateKey));
  1707. });
  1708. // remove deleted state properties
  1709. Object.keys(store.$state).forEach((stateKey) => {
  1710. if (!(stateKey in newStore.$state)) {
  1711. vueDemi.del(store, stateKey);
  1712. }
  1713. });
  1714. // avoid devtools logging this as a mutation
  1715. isListening = false;
  1716. isSyncListening = false;
  1717. pinia.state.value[$id] = vueDemi.toRef(newStore._hmrPayload, 'hotState');
  1718. isSyncListening = true;
  1719. vueDemi.nextTick().then(() => {
  1720. isListening = true;
  1721. });
  1722. for (const actionName in newStore._hmrPayload.actions) {
  1723. const action = newStore[actionName];
  1724. vueDemi.set(store, actionName, wrapAction(actionName, action));
  1725. }
  1726. // TODO: does this work in both setup and option store?
  1727. for (const getterName in newStore._hmrPayload.getters) {
  1728. const getter = newStore._hmrPayload.getters[getterName];
  1729. const getterValue = isOptionsStore
  1730. ? // special handling of options api
  1731. vueDemi.computed(() => {
  1732. setActivePinia(pinia);
  1733. return getter.call(store, store);
  1734. })
  1735. : getter;
  1736. vueDemi.set(store, getterName, getterValue);
  1737. }
  1738. // remove deleted getters
  1739. Object.keys(store._hmrPayload.getters).forEach((key) => {
  1740. if (!(key in newStore._hmrPayload.getters)) {
  1741. vueDemi.del(store, key);
  1742. }
  1743. });
  1744. // remove old actions
  1745. Object.keys(store._hmrPayload.actions).forEach((key) => {
  1746. if (!(key in newStore._hmrPayload.actions)) {
  1747. vueDemi.del(store, key);
  1748. }
  1749. });
  1750. // update the values used in devtools and to allow deleting new properties later on
  1751. store._hmrPayload = newStore._hmrPayload;
  1752. store._getters = newStore._getters;
  1753. store._hotUpdating = false;
  1754. });
  1755. }
  1756. if (USE_DEVTOOLS) {
  1757. const nonEnumerable = {
  1758. writable: true,
  1759. configurable: true,
  1760. // avoid warning on devtools trying to display this property
  1761. enumerable: false,
  1762. };
  1763. ['_p', '_hmrPayload', '_getters', '_customProperties'].forEach((p) => {
  1764. Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));
  1765. });
  1766. }
  1767. /* istanbul ignore if */
  1768. if (vueDemi.isVue2) {
  1769. // mark the store as ready before plugins
  1770. store._r = true;
  1771. }
  1772. // apply all plugins
  1773. pinia._p.forEach((extender) => {
  1774. /* istanbul ignore else */
  1775. if (USE_DEVTOOLS) {
  1776. const extensions = scope.run(() => extender({
  1777. store,
  1778. app: pinia._a,
  1779. pinia,
  1780. options: optionsForPlugin,
  1781. }));
  1782. Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
  1783. assign(store, extensions);
  1784. }
  1785. else {
  1786. assign(store, scope.run(() => extender({
  1787. store,
  1788. app: pinia._a,
  1789. pinia,
  1790. options: optionsForPlugin,
  1791. })));
  1792. }
  1793. });
  1794. if (store.$state &&
  1795. typeof store.$state === 'object' &&
  1796. typeof store.$state.constructor === 'function' &&
  1797. !store.$state.constructor.toString().includes('[native code]')) {
  1798. console.warn(`[🍍]: The "state" must be a plain object. It cannot be\n` +
  1799. `\tstate: () => new MyClass()\n` +
  1800. `Found in store "${store.$id}".`);
  1801. }
  1802. // only apply hydrate to option stores with an initial state in pinia
  1803. if (initialState &&
  1804. isOptionsStore &&
  1805. options.hydrate) {
  1806. options.hydrate(store.$state, initialState);
  1807. }
  1808. isListening = true;
  1809. isSyncListening = true;
  1810. return store;
  1811. }
  1812. function defineStore(
  1813. // TODO: add proper types from above
  1814. idOrOptions, setup, setupOptions) {
  1815. let id;
  1816. let options;
  1817. const isSetupStore = typeof setup === 'function';
  1818. if (typeof idOrOptions === 'string') {
  1819. id = idOrOptions;
  1820. // the option store setup will contain the actual options in this case
  1821. options = isSetupStore ? setupOptions : setup;
  1822. }
  1823. else {
  1824. options = idOrOptions;
  1825. id = idOrOptions.id;
  1826. if (typeof id !== 'string') {
  1827. throw new Error(`[🍍]: "defineStore()" must be passed a store id as its first argument.`);
  1828. }
  1829. }
  1830. function useStore(pinia, hot) {
  1831. const hasContext = vueDemi.hasInjectionContext();
  1832. pinia =
  1833. // in test mode, ignore the argument provided as we can always retrieve a
  1834. // pinia instance with getActivePinia()
  1835. (pinia) ||
  1836. (hasContext ? vueDemi.inject(piniaSymbol, null) : null);
  1837. if (pinia)
  1838. setActivePinia(pinia);
  1839. if (!activePinia) {
  1840. throw new Error(`[🍍]: "getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?\n` +
  1841. `\tconst pinia = createPinia()\n` +
  1842. `\tapp.use(pinia)\n` +
  1843. `This will fail in production.`);
  1844. }
  1845. pinia = activePinia;
  1846. if (!pinia._s.has(id)) {
  1847. // creating the store registers it in `pinia._s`
  1848. if (isSetupStore) {
  1849. createSetupStore(id, setup, options, pinia);
  1850. }
  1851. else {
  1852. createOptionsStore(id, options, pinia);
  1853. }
  1854. /* istanbul ignore else */
  1855. {
  1856. // @ts-expect-error: not the right inferred type
  1857. useStore._pinia = pinia;
  1858. }
  1859. }
  1860. const store = pinia._s.get(id);
  1861. if (hot) {
  1862. const hotId = '__hot:' + id;
  1863. const newStore = isSetupStore
  1864. ? createSetupStore(hotId, setup, options, pinia, true)
  1865. : createOptionsStore(hotId, assign({}, options), pinia, true);
  1866. hot._hotUpdate(newStore);
  1867. // cleanup the state properties and the store from the cache
  1868. delete pinia.state.value[hotId];
  1869. pinia._s.delete(hotId);
  1870. }
  1871. if (IS_CLIENT) {
  1872. const currentInstance = vueDemi.getCurrentInstance();
  1873. // save stores in instances to access them devtools
  1874. if (currentInstance &&
  1875. currentInstance.proxy &&
  1876. // avoid adding stores that are just built for hot module replacement
  1877. !hot) {
  1878. const vm = currentInstance.proxy;
  1879. const cache = '_pStores' in vm ? vm._pStores : (vm._pStores = {});
  1880. cache[id] = store;
  1881. }
  1882. }
  1883. // StoreGeneric cannot be casted towards Store
  1884. return store;
  1885. }
  1886. useStore.$id = id;
  1887. return useStore;
  1888. }
  1889. let mapStoreSuffix = 'Store';
  1890. /**
  1891. * Changes the suffix added by `mapStores()`. Can be set to an empty string.
  1892. * Defaults to `"Store"`. Make sure to extend the MapStoresCustomization
  1893. * interface if you are using TypeScript.
  1894. *
  1895. * @param suffix - new suffix
  1896. */
  1897. function setMapStoreSuffix(suffix // could be 'Store' but that would be annoying for JS
  1898. ) {
  1899. mapStoreSuffix = suffix;
  1900. }
  1901. /**
  1902. * Allows using stores without the composition API (`setup()`) by generating an
  1903. * object to be spread in the `computed` field of a component. It accepts a list
  1904. * of store definitions.
  1905. *
  1906. * @example
  1907. * ```js
  1908. * export default {
  1909. * computed: {
  1910. * // other computed properties
  1911. * ...mapStores(useUserStore, useCartStore)
  1912. * },
  1913. *
  1914. * created() {
  1915. * this.userStore // store with id "user"
  1916. * this.cartStore // store with id "cart"
  1917. * }
  1918. * }
  1919. * ```
  1920. *
  1921. * @param stores - list of stores to map to an object
  1922. */
  1923. function mapStores(...stores) {
  1924. if (Array.isArray(stores[0])) {
  1925. console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:\n` +
  1926. `Replace\n` +
  1927. `\tmapStores([useAuthStore, useCartStore])\n` +
  1928. `with\n` +
  1929. `\tmapStores(useAuthStore, useCartStore)\n` +
  1930. `This will fail in production if not fixed.`);
  1931. stores = stores[0];
  1932. }
  1933. return stores.reduce((reduced, useStore) => {
  1934. // @ts-expect-error: $id is added by defineStore
  1935. reduced[useStore.$id + mapStoreSuffix] = function () {
  1936. return useStore(this.$pinia);
  1937. };
  1938. return reduced;
  1939. }, {});
  1940. }
  1941. /**
  1942. * Allows using state and getters from one store without using the composition
  1943. * API (`setup()`) by generating an object to be spread in the `computed` field
  1944. * of a component.
  1945. *
  1946. * @param useStore - store to map from
  1947. * @param keysOrMapper - array or object
  1948. */
  1949. function mapState(useStore, keysOrMapper) {
  1950. return Array.isArray(keysOrMapper)
  1951. ? keysOrMapper.reduce((reduced, key) => {
  1952. reduced[key] = function () {
  1953. return useStore(this.$pinia)[key];
  1954. };
  1955. return reduced;
  1956. }, {})
  1957. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1958. // @ts-expect-error
  1959. reduced[key] = function () {
  1960. const store = useStore(this.$pinia);
  1961. const storeKey = keysOrMapper[key];
  1962. // for some reason TS is unable to infer the type of storeKey to be a
  1963. // function
  1964. return typeof storeKey === 'function'
  1965. ? storeKey.call(this, store)
  1966. : store[storeKey];
  1967. };
  1968. return reduced;
  1969. }, {});
  1970. }
  1971. /**
  1972. * Alias for `mapState()`. You should use `mapState()` instead.
  1973. * @deprecated use `mapState()` instead.
  1974. */
  1975. const mapGetters = mapState;
  1976. /**
  1977. * Allows directly using actions from your store without using the composition
  1978. * API (`setup()`) by generating an object to be spread in the `methods` field
  1979. * of a component.
  1980. *
  1981. * @param useStore - store to map from
  1982. * @param keysOrMapper - array or object
  1983. */
  1984. function mapActions(useStore, keysOrMapper) {
  1985. return Array.isArray(keysOrMapper)
  1986. ? keysOrMapper.reduce((reduced, key) => {
  1987. // @ts-expect-error
  1988. reduced[key] = function (...args) {
  1989. return useStore(this.$pinia)[key](...args);
  1990. };
  1991. return reduced;
  1992. }, {})
  1993. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1994. // @ts-expect-error
  1995. reduced[key] = function (...args) {
  1996. return useStore(this.$pinia)[keysOrMapper[key]](...args);
  1997. };
  1998. return reduced;
  1999. }, {});
  2000. }
  2001. /**
  2002. * Allows using state and getters from one store without using the composition
  2003. * API (`setup()`) by generating an object to be spread in the `computed` field
  2004. * of a component.
  2005. *
  2006. * @param useStore - store to map from
  2007. * @param keysOrMapper - array or object
  2008. */
  2009. function mapWritableState(useStore, keysOrMapper) {
  2010. return Array.isArray(keysOrMapper)
  2011. ? keysOrMapper.reduce((reduced, key) => {
  2012. // @ts-ignore
  2013. reduced[key] = {
  2014. get() {
  2015. return useStore(this.$pinia)[key];
  2016. },
  2017. set(value) {
  2018. // it's easier to type it here as any
  2019. return (useStore(this.$pinia)[key] = value);
  2020. },
  2021. };
  2022. return reduced;
  2023. }, {})
  2024. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  2025. // @ts-ignore
  2026. reduced[key] = {
  2027. get() {
  2028. return useStore(this.$pinia)[keysOrMapper[key]];
  2029. },
  2030. set(value) {
  2031. // it's easier to type it here as any
  2032. return (useStore(this.$pinia)[keysOrMapper[key]] = value);
  2033. },
  2034. };
  2035. return reduced;
  2036. }, {});
  2037. }
  2038. /**
  2039. * Creates an object of references with all the state, getters, and plugin-added
  2040. * state properties of the store. Similar to `toRefs()` but specifically
  2041. * designed for Pinia stores so methods and non reactive properties are
  2042. * completely ignored.
  2043. *
  2044. * @param store - store to extract the refs from
  2045. */
  2046. function storeToRefs(store) {
  2047. // See https://github.com/vuejs/pinia/issues/852
  2048. // It's easier to just use toRefs() even if it includes more stuff
  2049. if (vueDemi.isVue2) {
  2050. // @ts-expect-error: toRefs include methods and others
  2051. return vueDemi.toRefs(store);
  2052. }
  2053. else {
  2054. store = vueDemi.toRaw(store);
  2055. const refs = {};
  2056. for (const key in store) {
  2057. const value = store[key];
  2058. if (vueDemi.isRef(value) || vueDemi.isReactive(value)) {
  2059. // @ts-expect-error: the key is state or getter
  2060. refs[key] =
  2061. // ---
  2062. vueDemi.toRef(store, key);
  2063. }
  2064. }
  2065. return refs;
  2066. }
  2067. }
  2068. /**
  2069. * Vue 2 Plugin that must be installed for pinia to work. Note **you don't need
  2070. * this plugin if you are using Nuxt.js**. Use the `buildModule` instead:
  2071. * https://pinia.vuejs.org/ssr/nuxt.html.
  2072. *
  2073. * @example
  2074. * ```js
  2075. * import Vue from 'vue'
  2076. * import { PiniaVuePlugin, createPinia } from 'pinia'
  2077. *
  2078. * Vue.use(PiniaVuePlugin)
  2079. * const pinia = createPinia()
  2080. *
  2081. * new Vue({
  2082. * el: '#app',
  2083. * // ...
  2084. * pinia,
  2085. * })
  2086. * ```
  2087. *
  2088. * @param _Vue - `Vue` imported from 'vue'.
  2089. */
  2090. const PiniaVuePlugin = function (_Vue) {
  2091. // Equivalent of
  2092. // app.config.globalProperties.$pinia = pinia
  2093. _Vue.mixin({
  2094. beforeCreate() {
  2095. const options = this.$options;
  2096. if (options.pinia) {
  2097. const pinia = options.pinia;
  2098. // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/main/src/apis/inject.ts#L31
  2099. /* istanbul ignore else */
  2100. if (!this._provided) {
  2101. const provideCache = {};
  2102. Object.defineProperty(this, '_provided', {
  2103. get: () => provideCache,
  2104. set: (v) => Object.assign(provideCache, v),
  2105. });
  2106. }
  2107. this._provided[piniaSymbol] = pinia;
  2108. // propagate the pinia instance in an SSR friendly way
  2109. // avoid adding it to nuxt twice
  2110. /* istanbul ignore else */
  2111. if (!this.$pinia) {
  2112. this.$pinia = pinia;
  2113. }
  2114. pinia._a = this;
  2115. if (IS_CLIENT) {
  2116. // this allows calling useStore() outside of a component setup after
  2117. // installing pinia's plugin
  2118. setActivePinia(pinia);
  2119. }
  2120. if (USE_DEVTOOLS) {
  2121. registerPiniaDevtools(pinia._a, pinia);
  2122. }
  2123. }
  2124. else if (!this.$pinia && options.parent && options.parent.$pinia) {
  2125. this.$pinia = options.parent.$pinia;
  2126. }
  2127. },
  2128. destroyed() {
  2129. delete this._pStores;
  2130. },
  2131. });
  2132. };
  2133. exports.PiniaVuePlugin = PiniaVuePlugin;
  2134. exports.acceptHMRUpdate = acceptHMRUpdate;
  2135. exports.createPinia = createPinia;
  2136. exports.defineStore = defineStore;
  2137. exports.getActivePinia = getActivePinia;
  2138. exports.mapActions = mapActions;
  2139. exports.mapGetters = mapGetters;
  2140. exports.mapState = mapState;
  2141. exports.mapStores = mapStores;
  2142. exports.mapWritableState = mapWritableState;
  2143. exports.setActivePinia = setActivePinia;
  2144. exports.setMapStoreSuffix = setMapStoreSuffix;
  2145. exports.skipHydrate = skipHydrate;
  2146. exports.storeToRefs = storeToRefs;
  2147. return exports;
  2148. })({}, VueDemi);