pinia.iife.js 82 KB

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