{"version":3,"file":"unstorage-pinia-plugin.mjs","sources":["../src/index.ts"],"sourcesContent":["import type { PiniaPluginContext, StateTree, Store } from 'pinia';\nimport { createStorage } from 'unstorage';\nimport type { Driver, Storage } from 'unstorage';\n\nexport interface UnstorageStoreOptions {\n  driver: Driver,\n  filter?: Array<string>\n  storage?: Storage\n}\n\ndeclare module 'pinia' {\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  export interface DefineStoreOptionsBase<S extends StateTree, Store> {\n    unstorage?: UnstorageStoreOptions\n  }\n}\n\nconst configureStore = (store: Store, storage: Storage, filter?: Array<string>) => {\n  storage.getItem(store.$id).then((state) => {\n    store.$patch(state);\n  });\n\n  const _filter = (filter) ?? Object.keys(store.$state);\n\n  store.$subscribe(() => storage.setItem(store.$id,\n    JSON.stringify(Object.fromEntries(\n      Object.entries(store.$state).filter(([key]) => (_filter.indexOf(key) ?? 0) > -1)\n    ))\n  ));\n\n  storage.setItem(store.$id,\n    JSON.stringify(Object.fromEntries(\n      Object.entries(store.$state).filter(([key]) => (_filter.indexOf(key) ?? 0) > -1)\n    ))\n  );\n};\n\nconst unstorageOptionsBag: Record<string, UnstorageStoreOptions> = {};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const persistStore = (store: any, unstorageOptions: UnstorageStoreOptions) => {\n  unstorageOptionsBag[(store as Store).$id] = unstorageOptions;\n  return store;\n};\n\nexport interface UnstoragePluginOptions {\n  driver?: Driver\n}\n\nexport const createUnstoragePlugin = ({ driver }: UnstoragePluginOptions = {}) => ({ options, store }: PiniaPluginContext) => {\n  if(options.unstorage) {\n    configureStore(store, createStorage({ driver: options.unstorage.driver }), options.unstorage.filter);\n  }\n  else if(unstorageOptionsBag[store.$id]) {\n    configureStore(store, createStorage({ driver: unstorageOptionsBag[store.$id].driver }), unstorageOptionsBag[store.$id].filter );\n  }\n  else if(driver) {\n    configureStore(store, createStorage({ driver }));\n  }\n};\n"],"names":["configureStore","store","storage","filter","state","_filter","key","unstorageO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