Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
fix(common): personal workspace possible data loss issue (#6510)
Anwarul Islam342d0cbdf0c5
diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetRestUserHistory.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetRestUserHistory.graphqlindex 144861594..f92cf1503 100644--- a/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetRestUserHistory.graphql+++ b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetRestUserHistory.graphql@@ -1,6 +1,6 @@-query GetRESTUserHistory {+query GetRESTUserHistory($take: Int) {me {- RESTHistory {+ RESTHistory(take: $take) {iduserUidreqType@@ -10,7 +10,7 @@ query GetRESTUserHistory {executedOn}- GQLHistory {+ GQLHistory(take: $take) {iduserUidreqType@@ -21,3 +21,4 @@ query GetRESTUserHistory {}}}+diff --git a/packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.ts b/packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.tsindex 4c5d206aa..8f1f1c7f0 100644--- a/packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.ts+++ b/packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.ts@@ -25,7 +25,7 @@ import {import { getSettingSubject, settingsStore } from "~/newstore/settings"import { getSyncInitFunction, StoreSyncDefinitionOf } from ".."import { createMapper } from "../mapper"-import { applyDuplicatedCollectionResult, moveOrReorderRequests } from "./sync"+import { applyDuplicatedCollectionResult, moveOrReorderRequests, ensurePathSynced } from "./sync"import { ReqType } from "~/helpers/backend/graphql"import { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"@@ -108,6 +108,7 @@ const recursivelySyncCollections = async ()} else {parentCollectionID = undefined+ return}} else {// if parentUserCollectionID exists, create the collection as a child collection@@ -154,6 +155,9 @@ const recursivelySyncCollections = async (childCollectionId,`${collectionPath}`)+ } else {+ parentCollectionID = undefined+ return}}@@ -207,6 +211,9 @@ type OperationCollectionRemoved = {export const gqlCollectionsOperations: Array<OperationCollectionRemoved> = []+const ensureGQLPathSynced = (path: string | number | null) =>+ ensurePathSynced(path, graphqlCollectionStore, recursivelySyncCollections)+export const storeSyncDefinition: StoreSyncDefinitionOf<typeof graphqlCollectionStore> = {@@ -254,13 +261,14 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<await deleteUserCollection(collectionID)}},- editCollection({ collection, collectionIndex }) {- // Send the backend id when present, otherwise the index path — GraphQL- // collections on some platforms (e.g. hoppscotch-web) carry no backend id.- const collectionID =- navigateToFolderWithIndexPath(graphqlCollectionStore.value.state, [- collectionIndex,- ])?.id ?? `${collectionIndex}`+ async editCollection({ collection, collectionIndex }) {+ const isSynced = await ensureGQLPathSynced(collectionIndex)+ if (!isSynced) return++ const collectionID = navigateToFolderWithIndexPath(+ graphqlCollectionStore.value.state,+ [collectionIndex]+ )?.idconst data = {auth: collection.auth,@@ -269,9 +277,14 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<_ref_id: collection._ref_id,}- updateUserCollection(collectionID, collection.name, JSON.stringify(data))+ if (collectionID) {+ updateUserCollection(collectionID, collection.name, JSON.stringify(data))+ }},async addFolder({ name, path }) {+ const isSynced = await ensureGQLPathSynced(path)+ if (!isSynced) return+const parentCollection = navigateToFolderWithIndexPath(graphqlCollectionStore.value.state,path.split("/").map((index) => parseInt(index))@@ -279,35 +292,40 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<if (!parentCollection) return- // Send the parent backend id when present, otherwise its index path.- const parentCollectionBackendID = parentCollection.id ?? path-const foldersLength = parentCollection.folders.length+ if (foldersLength > 0 && parentCollection.folders[foldersLength - 1].id) {+ return+ }- const res = await createGQLChildUserCollection(- name,- parentCollectionBackendID- )+ const parentCollectionBackendID = parentCollection.id- if (E.isRight(res)) {- const { id } = res.right.createGQLChildUserCollection+ if (parentCollectionBackendID) {+ const res = await createGQLChildUserCollection(+ name,+ parentCollectionBackendID+ )- if (foldersLength) {- parentCollection.folders[foldersLength - 1].id = id- removeDuplicateGraphqlCollectionOrFolder(- id,- `${path}/${foldersLength - 1}`- )+ if (E.isRight(res)) {+ const { id } = res.right.createGQLChildUserCollection++ if (foldersLength) {+ parentCollection.folders[foldersLength - 1].id = id+ removeDuplicateGraphqlCollectionOrFolder(+ id,+ `${path}/${foldersLength - 1}`+ )+ }}}},- editFolder({ folder, path }) {- // Send the backend id when present, otherwise the index path.- const folderBackendId =- navigateToFolderWithIndexPath(- graphqlCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )?.id ?? path+ async editFolder({ folder, path }) {+ const isSynced = await ensureGQLPathSynced(path)+ if (!isSynced) return++ const folderBackendId = navigateToFolderWithIndexPath(+ graphqlCollectionStore.value.state,+ path.split("/").map((index) => parseInt(index))+ )?.idconst data = {auth: folder.auth,@@ -316,7 +334,9 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<_ref_id: folder._ref_id,}- updateUserCollection(folderBackendId, folder.name, JSON.stringify(data))+ if (folderBackendId) {+ updateUserCollection(folderBackendId, folder.name, JSON.stringify(data))+ }},async removeFolder({ folderID }) {if (folderID) {@@ -336,20 +356,36 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<}}},- editRequest({ path, requestIndex, requestNew }) {- const request = navigateToFolderWithIndexPath(+ async editRequest({ path, requestIndex, requestNew }) {+ const isSynced = await ensureGQLPathSynced(path)++ const folder = navigateToFolderWithIndexPath(graphqlCollectionStore.value.state,path.split("/").map((index) => parseInt(index))- )?.requests[requestIndex]+ )+ if (!folder) return- // Send the backend id when present, otherwise the index path.- const requestBackendID = request?.id ?? `${path}/${requestIndex}`+ const request = folder.requests[requestIndex]+ if (!request) return- editGQLUserRequest(- requestBackendID,- (requestNew as HoppRESTRequest).name,- JSON.stringify(requestNew)- )+ if (request.id) {+ editGQLUserRequest(+ request.id,+ (requestNew as HoppRESTRequest).name,+ JSON.stringify(requestNew)+ )+ } else {+ if (isSynced && folder.id) {+ const res = await createGQLUserRequest(+ (requestNew as HoppRESTRequest).name,+ JSON.stringify(requestNew),+ folder.id+ )+ if (res && E.isRight(res)) {+ request.id = res.right.createGQLUserRequest.id+ }+ }+ }},async saveRequestAs({ path, request }) {const folder = navigateToFolderWithIndexPath(@@ -359,8 +395,16 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<if (!folder) return- // Send the parent backend id when present, otherwise its index path.- const parentCollectionBackendID = folder.id ?? path+ const isSynced = await ensureGQLPathSynced(path)+ if (!isSynced) return++ const requestsLength = folder.requests.length+ if (requestsLength > 0 && folder.requests[requestsLength - 1].id) {+ return+ }++ const parentCollectionBackendID = folder.id+ if (!parentCollectionBackendID) returnconst newRequest = folder.requests[folder.requests.length - 1]@@ -386,7 +430,26 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<await deleteUserRequest(requestID)}},- moveRequest({ destinationPath, path, requestIndex }) {+ async moveRequest({ destinationPath, path, requestIndex }) {+ const collections = graphqlCollectionStore.value.state+ const sourceCollection = navigateToFolderWithIndexPath(+ collections,+ path.split("/").map((index) => parseInt(index))+ )+ const destCollection = navigateToFolderWithIndexPath(+ collections,+ destinationPath.split("/").map((index) => parseInt(index))+ )++ const wasSourceSynced = !!sourceCollection?.id+ const wasDestSynced = !!destCollection?.id++ const isSourceSynced = await ensureGQLPathSynced(path)+ const isDestSynced = await ensureGQLPathSynced(destinationPath)+ if (!isSourceSynced || !isDestSynced) return++ if (!wasSourceSynced || !wasDestSynced) return+moveOrReorderRequests(requestIndex, path, destinationPath, undefined, "GQL")},}diff --git a/packages/hoppscotch-common/src/lib/sync/collections/index.ts b/packages/hoppscotch-common/src/lib/sync/collections/index.tsindex f719a4130..2030655e6 100644--- a/packages/hoppscotch-common/src/lib/sync/collections/index.ts+++ b/packages/hoppscotch-common/src/lib/sync/collections/index.ts@@ -256,6 +256,108 @@ export function exportedCollectionToHoppCollection(})}+function mergeTwoCollections(+ local: HoppCollection,+ fetched: HoppCollection+): HoppCollection {+ const mergedFolders: HoppCollection[] = []+ const fetchedFoldersMap = new Map<string, HoppCollection>()+ for (const f of fetched.folders) {+ if (f.id) fetchedFoldersMap.set(f.id, f)+ }++ const processedFetchedFolderIds = new Set<string>()+ for (const localFolder of local.folders) {+ if (localFolder.id) {+ const fetchedFolder = fetchedFoldersMap.get(localFolder.id)+ if (fetchedFolder) {+ mergedFolders.push(mergeTwoCollections(localFolder, fetchedFolder))+ processedFetchedFolderIds.add(localFolder.id)+ } else {+ mergedFolders.push(localFolder)+ }+ } else {+ mergedFolders.push(localFolder)+ }+ }++ for (const fetchedFolder of fetched.folders) {+ if (fetchedFolder.id && !processedFetchedFolderIds.has(fetchedFolder.id)) {+ mergedFolders.push(fetchedFolder)+ }+ }++ const mergedRequests: typeof fetched.requests = []+ const fetchedRequestsMap = new Map<string, any>()+ for (const r of fetched.requests) {+ if (r.id) fetchedRequestsMap.set(r.id, r)+ }++ const processedFetchedRequestIds = new Set<string>()+ for (const localReq of local.requests) {+ if (localReq.id) {+ const fetchedReq = fetchedRequestsMap.get(localReq.id)+ if (fetchedReq) {+ mergedRequests.push(fetchedReq)+ processedFetchedRequestIds.add(localReq.id)+ } else {+ mergedRequests.push(localReq)+ }+ } else {+ mergedRequests.push(localReq)+ }+ }++ for (const fetchedReq of fetched.requests) {+ if (fetchedReq.id && !processedFetchedRequestIds.has(fetchedReq.id)) {+ mergedRequests.push(fetchedReq)+ }+ }++ return {+ ...fetched,+ folders: mergedFolders,+ requests: mergedRequests,+ }+}++function mergeCollections(+ localCollections: HoppCollection[],+ fetchedCollections: HoppCollection[]+): HoppCollection[] {+ const fetchedMap = new Map<string, HoppCollection>()+ for (const col of fetchedCollections) {+ if (col.id) {+ fetchedMap.set(col.id, col)+ }+ }++ const merged: HoppCollection[] = []+ const processedFetchedIds = new Set<string>()++ for (const localCol of localCollections) {+ if (localCol.id) {+ const fetchedCol = fetchedMap.get(localCol.id)+ if (fetchedCol) {+ merged.push(mergeTwoCollections(localCol, fetchedCol))+ processedFetchedIds.add(localCol.id)+ } else {+ merged.push(localCol)+ }+ } else {+ merged.push(localCol)+ }+ }++ for (const fetchedCol of fetchedCollections) {+ if (fetchedCol.id && !processedFetchedIds.has(fetchedCol.id)) {+ merged.push(fetchedCol)+ }+ }++ return merged+}+async function loadUserCollections(collectionType: "REST" | "GQL") {const res = await exportUserCollectionsToJSON(undefined,@@ -269,26 +371,26 @@ async function loadUserCollections(collectionType: "REST" | "GQL") {ExportedUserCollectionGQL | ExportedUserCollectionREST>).map((collection) => ({ v: 1, ...collection }))++ const fetchedCollections = exportedCollections.map(+ (collection) =>+ exportedCollectionToHoppCollection(+ collection,+ collectionType+ ) as HoppCollection+ )++ const localCollections =+ collectionType == "REST"+ ? restCollectionStore.value.state+ : graphqlCollectionStore.value.state++ const mergedCollections = mergeCollections(localCollections, fetchedCollections)+runDispatchWithOutSyncing(() => {collectionType == "REST"- ? setRESTCollections(- exportedCollections.map(- (collection) =>- exportedCollectionToHoppCollection(- collection,- "REST"- ) as HoppCollection- )- )- : setGraphqlCollections(- exportedCollections.map(- (collection) =>- exportedCollectionToHoppCollection(- collection,- "GQL"- ) as HoppCollection- )- )+ ? setRESTCollections(mergedCollections)+ : setGraphqlCollections(mergedCollections)})}}diff --git a/packages/hoppscotch-common/src/lib/sync/collections/sync.ts b/packages/hoppscotch-common/src/lib/sync/collections/sync.tsindex eb66acdc2..87037dbbc 100644--- a/packages/hoppscotch-common/src/lib/sync/collections/sync.ts+++ b/packages/hoppscotch-common/src/lib/sync/collections/sync.ts@@ -318,6 +318,7 @@ const recursivelySyncCollections = async ()} else {parentCollectionID = undefined+ return}} else {// if parentUserCollectionID exists, create the collection as a child collection@@ -366,6 +367,9 @@ const recursivelySyncCollections = async (childCollectionId,`${collectionPath}`)+ } else {+ parentCollectionID = undefined+ return}}@@ -419,6 +423,55 @@ type OperationCollectionRemoved = {export const restCollectionsOperations: Array<OperationCollectionRemoved> = []+export async function ensurePathSynced(+ path: string | number | null,+ collectionStore: typeof restCollectionStore | typeof graphqlCollectionStore,+ recursivelySyncFn: (+ collection: HoppCollection,+ collectionPath: string,+ parentUserCollectionID?: string+ ) => Promise<void>+): Promise<boolean> {+ if (path === null || path === undefined || path === "") return true++ const collections = collectionStore.value.state+ const pathIndexes = typeof path === "number" ? [path] : path.split("/").map((index) => parseInt(index))++ let highestUnsyncedPath: number[] | null = null+ let parentID: string | undefined = undefined++ for (let i = 0; i < pathIndexes.length; i++) {+ const subPath = pathIndexes.slice(0, i + 1)+ const collection = navigateToFolderWithIndexPath(collections, subPath)+ if (!collection) break++ if (!collection.id) {+ highestUnsyncedPath = subPath+ break+ } else {+ parentID = collection.id+ }+ }++ if (highestUnsyncedPath) {+ const collectionToSync = navigateToFolderWithIndexPath(collections, highestUnsyncedPath)+ if (collectionToSync) {+ await recursivelySyncFn(+ collectionToSync,+ highestUnsyncedPath.join("/"),+ parentID+ )+ const targetCollection = navigateToFolderWithIndexPath(collections, pathIndexes)+ return !!targetCollection?.id+ }+ }++ return true+}++const ensureRESTPathSynced = (path: string | number | null) =>+ ensurePathSynced(path, restCollectionStore, recursivelySyncCollections)+export const storeSyncDefinition: StoreSyncDefinitionOf<typeof restCollectionStore> = {@@ -465,7 +518,10 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<await deleteUserCollection(collectionID)}},- editCollection({ partialCollection: collection, collectionIndex }) {+ async editCollection({ partialCollection: collection, collectionIndex }) {+ const isSynced = await ensureRESTPathSynced(collectionIndex)+ if (!isSynced) return+const collectionID = navigateToFolderWithIndexPath(restCollectionStore.value.state,[collectionIndex]@@ -514,11 +570,21 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<},async addFolder({ name, path }) {+ const isSynced = await ensureRESTPathSynced(path)+ if (!isSynced) return+const parentCollection = navigateToFolderWithIndexPath(restCollectionStore.value.state,path.split("/").map((index) => parseInt(index)))+ if (parentCollection) {+ const foldersLength = parentCollection.folders.length+ if (foldersLength > 0 && parentCollection.folders[foldersLength - 1].id) {+ return+ }+ }+const parentCollectionBackendID = parentCollection?.idif (parentCollectionBackendID) {@@ -548,7 +614,10 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<}}},- editFolder({ folder, path }) {+ async editFolder({ folder, path }) {+ const isSynced = await ensureRESTPathSynced(path)+ if (!isSynced) return+const folderID = navigateToFolderWithIndexPath(restCollectionStore.value.state,path.split("/").map((index) => parseInt(index))@@ -578,6 +647,30 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<)if (newSourcePath) {+ const collections = restCollectionStore.value.state+ const sourceCollection = navigateToFolderWithIndexPath(+ collections,+ newSourcePath.split("/").map((index) => parseInt(index))+ )+ const destCollection = destinationPath && newDestinationPath+ ? navigateToFolderWithIndexPath(+ collections,+ newDestinationPath.split("/").map((index) => parseInt(index))+ )+ : null++ const wasSourceSynced = !!sourceCollection?.id+ const wasDestSynced = destinationPath ? !!destCollection?.id : true++ const isSourceSynced = await ensureRESTPathSynced(newSourcePath)+ const isDestSynced = newDestinationPath+ ? await ensureRESTPathSynced(newDestinationPath)+ : true++ if (!isSourceSynced || !isDestSynced) return++ if (!wasSourceSynced || !wasDestSynced) return+const sourceCollectionID = navigateToFolderWithIndexPath(restCollectionStore.value.state,newSourcePath.split("/").map((index) => parseInt(index))@@ -609,28 +702,53 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<}}},- editRequest({ path, requestIndex, requestNew }) {- const request = navigateToFolderWithIndexPath(+ async editRequest({ path, requestIndex, requestNew }) {+ const isSynced = await ensureRESTPathSynced(path)++ const folder = navigateToFolderWithIndexPath(restCollectionStore.value.state,path.split("/").map((index) => parseInt(index))- )?.requests[requestIndex]+ )+ if (!folder) return- const requestBackendID = request?.id+ const request = folder.requests[requestIndex]+ if (!request) return- if (requestBackendID) {+ if (request.id) {editUserRequest(- requestBackendID,+ request.id,(requestNew as HoppRESTRequest).name,JSON.stringify(requestNew))+ } else {+ if (isSynced && folder.id) {+ const res = await createRESTUserRequest(+ (requestNew as HoppRESTRequest).name,+ JSON.stringify(requestNew),+ folder.id+ )+ if (res && E.isRight(res)) {+ request.id = res.right.createRESTUserRequest.id+ }+ }}},async saveRequestAs({ path, request }) {+ const isSynced = await ensureRESTPathSynced(path)+ if (!isSynced) return+const folder = navigateToFolderWithIndexPath(restCollectionStore.value.state,path.split("/").map((index) => parseInt(index)))+ if (folder) {+ const requestsLength = folder.requests.length+ if (requestsLength > 0 && folder.requests[requestsLength - 1].id) {+ return+ }+ }+const parentCollectionBackendID = folder?.idif (parentCollectionBackendID) {@@ -667,10 +785,29 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<await deleteUserRequest(requestID)}},- moveRequest({ destinationPath, path, requestIndex }) {+ async moveRequest({ destinationPath, path, requestIndex }) {+ const collections = restCollectionStore.value.state+ const sourceCollection = navigateToFolderWithIndexPath(+ collections,+ path.split("/").map((index) => parseInt(index))+ )+ const destCollection = navigateToFolderWithIndexPath(+ collections,+ destinationPath.split("/").map((index) => parseInt(index))+ )++ const wasSourceSynced = !!sourceCollection?.id+ const wasDestSynced = !!destCollection?.id++ const isSourceSynced = await ensureRESTPathSynced(path)+ const isDestSynced = await ensureRESTPathSynced(destinationPath)+ if (!isSourceSynced || !isDestSynced) return++ if (!wasSourceSynced || !wasDestSynced) return+moveOrReorderRequests(requestIndex, path, destinationPath)},- updateRequestOrder({+ async updateRequestOrder({destinationCollectionPath,destinationRequestIndex,requestIndex,@@ -679,6 +816,18 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<* currently the FE implementation only supports reordering requests between the same collection,* so destinationCollectionPath and sourceCollectionPath will be same*/+ const collections = restCollectionStore.value.state+ const collection = navigateToFolderWithIndexPath(+ collections,+ destinationCollectionPath.split("/").map((index) => parseInt(index))+ )+ const wasSynced = !!collection?.id++ const isSynced = await ensureRESTPathSynced(destinationCollectionPath)+ if (!isSynced) return++ if (!wasSynced) return+moveOrReorderRequests(requestIndex,destinationCollectionPath,diff --git a/packages/hoppscotch-common/src/lib/sync/history/api.ts b/packages/hoppscotch-common/src/lib/sync/history/api.tsindex 6399bb1c0..e49af5411 100644--- a/packages/hoppscotch-common/src/lib/sync/history/api.ts+++ b/packages/hoppscotch-common/src/lib/sync/history/api.ts@@ -4,6 +4,8 @@ import {runGQLSubscription,} from "~/helpers/backend/GQLClient"+import { HISTORY_LIMIT } from "~/newstore/history"+import {CreateUserHistoryDocument,CreateUserHistoryMutation,@@ -28,10 +30,12 @@ import {UserHistoryAllDeletedDocument,} from "~/helpers/backend/graphql"-export const getUserHistoryEntries = () =>+export const getUserHistoryEntries = (take: number = HISTORY_LIMIT) =>runGQLQuery<GetRestUserHistoryQuery, GetRestUserHistoryQueryVariables, "">({query: GetRestUserHistoryDocument,- variables: {},+ variables: {+ take,+ },})export const createUserHistory = (diff --git a/packages/hoppscotch-common/src/lib/sync/history/index.ts b/packages/hoppscotch-common/src/lib/sync/history/index.tsindex c33531951..c2e505584 100644--- a/packages/hoppscotch-common/src/lib/sync/history/index.ts+++ b/packages/hoppscotch-common/src/lib/sync/history/index.ts@@ -86,12 +86,57 @@ function setupSubscriptions() {}}+function mergeHistoryEntries<+ T extends { id?: string; updatedOn?: Date | string | null }+>(local: T[], fetched: T[]): T[] {+ const fetchedMap = new Map<string, T>()+ for (const entry of fetched) {+ if (entry.id) {+ fetchedMap.set(entry.id, entry)+ }+ }++ const merged: T[] = []++ for (const localEntry of local) {+ if (!localEntry.id) {+ merged.push(localEntry)+ } else {+ const fetchedEntry = fetchedMap.get(localEntry.id)+ if (fetchedEntry) {+ merged.push(fetchedEntry)+ fetchedMap.delete(localEntry.id)+ } else {+ merged.push(localEntry)+ }+ }+ }++ for (const fetchedEntry of fetchedMap.values()) {+ merged.push(fetchedEntry)+ }++ const getSafeTimestamp = (date: Date | string | null | undefined): number => {+ if (!date) return 0+ const time = new Date(date).getTime()+ return isNaN(time) ? 0 : time+ }++ merged.sort((a, b) => {+ const timeA = getSafeTimestamp(a.updatedOn)+ const timeB = getSafeTimestamp(b.updatedOn)+ return timeB - timeA+ })++ return merged+}+async function loadHistoryEntries() {const res = await getUserHistoryEntries()if (E.isRight(res)) {- const restEntries = res.right.me.RESTHistory- const gqlEntries = res.right.me.GQLHistory+ const restEntries = res.right.me.RESTHistory ?? []+ const gqlEntries = res.right.me.GQLHistory ?? []const restHistoryEntries: RESTHistoryEntry[] = restEntries.map((entry) => ({v: 1,@@ -111,9 +156,15 @@ async function loadHistoryEntries() {id: entry.id,}))+ const localRESTHistory = restHistoryStore.value.state+ const localGQLHistory = graphqlHistoryStore.value.state++ const mergedREST = mergeHistoryEntries(localRESTHistory, restHistoryEntries)+ const mergedGQL = mergeHistoryEntries(localGQLHistory, gqlHistoryEntries)+runDispatchWithOutSyncing(() => {- setRESTHistoryEntries(restHistoryEntries)- setGraphqlHistoryEntries(gqlHistoryEntries)+ setRESTHistoryEntries(mergedREST)+ setGraphqlHistoryEntries(mergedGQL)})}}diff --git a/packages/hoppscotch-common/src/newstore/history.ts b/packages/hoppscotch-common/src/newstore/history.tsindex 3f3fcfc7c..2fe8d6f91 100644--- a/packages/hoppscotch-common/src/newstore/history.ts+++ b/packages/hoppscotch-common/src/newstore/history.ts@@ -60,7 +60,24 @@ export function makeGQLHistoryEntry(}export function translateToNewRESTHistory(x: any): RESTHistoryEntry {- if (x.v === 1) return x+ let responseMeta = x.responseMeta+ if (typeof responseMeta === "string") {+ try {+ responseMeta = JSON.parse(responseMeta)+ } catch {+ responseMeta = { duration: null, statusCode: null }+ }+ }++ if (x.v === 1) {+ return {+ ...x,+ responseMeta: {+ duration: responseMeta?.duration ?? null,+ statusCode: responseMeta?.statusCode ?? null,+ },+ }+ }// Legacyconst request = translateToNewRequest(x)diff --git a/packages/hoppscotch-common/src/services/persistence/__tests__/index.spec.ts b/packages/hoppscotch-common/src/services/persistence/__tests__/index.spec.tsindex f69f5af06..b72921f83 100644--- a/packages/hoppscotch-common/src/services/persistence/__tests__/index.spec.ts+++ b/packages/hoppscotch-common/src/services/persistence/__tests__/index.spec.ts@@ -56,6 +56,7 @@ import {STORE_KEYS,STORE_NAMESPACE,} from "../../persistence"+import { REST_HISTORY_ENTRY_SCHEMA } from "../validation-schemas"import {ENVIRONMENTS_MOCK,GLOBAL_ENV_MOCK,@@ -856,6 +857,51 @@ describe("PersistenceService", () => {expect.any(Function))})++ it("validates REST_HISTORY_ENTRY_SCHEMA responseMeta correctly", () => {+ // 1. Valid object responseMeta+ const entryWithValidObj = {+ ...REST_HISTORY_MOCK[0],+ responseMeta: { duration: 807, statusCode: 200 },+ }+ expect(+ REST_HISTORY_ENTRY_SCHEMA.safeParse(entryWithValidObj).success+ ).toBe(true)++ // 2. Valid stringified responseMeta+ const entryWithValidStr = {+ ...REST_HISTORY_MOCK[0],+ responseMeta: JSON.stringify({ duration: 807, statusCode: 200 }),+ }+ expect(+ REST_HISTORY_ENTRY_SCHEMA.safeParse(entryWithValidStr).success+ ).toBe(true)++ // 3. Malformed stringified responseMeta (non-numeric duration/statusCode) should fail and fall back to catch values+ const entryWithMalformedStr = {+ ...REST_HISTORY_MOCK[0],+ responseMeta: JSON.stringify({ duration: "invalid", statusCode: 200 }),+ }+ const parseResult = REST_HISTORY_ENTRY_SCHEMA.safeParse(entryWithMalformedStr)+ expect(parseResult.success).toBe(true)+ expect(parseResult.data?.responseMeta).toEqual({+ duration: null,+ statusCode: null,+ })++ // 4. Non-JSON string should fail and fall back to catch values+ const entryWithNonJSONStr = {+ ...REST_HISTORY_MOCK[0],+ responseMeta: "not-json",+ }+ const parseResultNonJSON =+ REST_HISTORY_ENTRY_SCHEMA.safeParse(entryWithNonJSONStr)+ expect(parseResultNonJSON.success).toBe(true)+ expect(parseResultNonJSON.data?.responseMeta).toEqual({+ duration: null,+ statusCode: null,+ })+ })})describe("setup collections persistence", () => {@@ -963,11 +1009,17 @@ describe("PersistenceService", () => {setGraphqlCollections: vi.fn(),setRESTCollections: vi.fn(),graphqlCollectionStore: {+ value: {+ state: [],+ },subject$: {subscribe: vi.fn(),},},restCollectionStore: {+ value: {+ state: [],+ },subject$: {subscribe: vi.fn(),},diff --git a/packages/hoppscotch-common/src/services/persistence/index.ts b/packages/hoppscotch-common/src/services/persistence/index.tsindex e722cb256..a3dee2f53 100644--- a/packages/hoppscotch-common/src/services/persistence/index.ts+++ b/packages/hoppscotch-common/src/services/persistence/index.ts@@ -541,6 +541,7 @@ export class PersistenceService extends Service {const translatedData = result.data.map(translateToNewRESTHistory)setRESTHistoryEntries(translatedData)} else {+ console.error(`Failed parsing persisted REST_HISTORY:`, result.error.message)this.showErrorToast(STORE_KEYS.REST_HISTORY)await Store.set(STORE_NAMESPACE,@@ -621,7 +622,7 @@ export class PersistenceService extends Service {)setRESTCollections(translatedData)} else {- console.error(`Failed with `, result.error, data)+ console.error(`Failed with `, result.error.message)this.showErrorToast(STORE_KEYS.REST_COLLECTIONS)await Store.set(STORE_NAMESPACE,diff --git a/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.ts b/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.tsindex 65716f339..d9e3f694d 100644--- a/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.ts+++ b/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.ts@@ -132,14 +132,35 @@ export const REST_HISTORY_ENTRY_SCHEMA = z//! Versioned entityrequest: HoppRESTRequestSchema,responseMeta: z- .object({- duration: z.nullable(z.number()),- statusCode: z.nullable(z.number()),- })- .strict(),+ .union([+ z.string().refine((val) => {+ try {+ const parsed = JSON.parse(val)+ return (+ typeof parsed === "object" &&+ parsed !== null &&+ (parsed.duration === undefined ||+ parsed.duration === null ||+ typeof parsed.duration === "number") &&+ (parsed.statusCode === undefined ||+ parsed.statusCode === null ||+ typeof parsed.statusCode === "number")+ )+ } catch {+ return false+ }+ }),+ z+ .object({+ duration: z.nullable(z.number()),+ statusCode: z.nullable(z.number()),+ })+ .strict(),+ ])+ .catch({ duration: null, statusCode: null }),star: z.boolean(),- id: z.optional(z.string()),- updatedOn: z.optional(z.union([z.date(), z.string()])),+ id: z.string().nullish(),+ updatedOn: z.union([z.date(), z.string()]).nullish(),}).strict()@@ -150,8 +171,8 @@ export const GQL_HISTORY_ENTRY_SCHEMA = zrequest: HoppGQLRequestSchema,response: z.string(),star: z.boolean(),- id: z.optional(z.string()),- updatedOn: z.optional(z.union([z.date(), z.string()])),+ id: z.string().nullish(),+ updatedOn: z.union([z.date(), z.string()]).nullish(),}).strict()diff --git a/packages/hoppscotch-selfhost-web/src/api/queries/GetRestUserHistory.graphql b/packages/hoppscotch-selfhost-web/src/api/queries/GetRestUserHistory.graphqlindex 144861594..f92cf1503 100644--- a/packages/hoppscotch-selfhost-web/src/api/queries/GetRestUserHistory.graphql+++ b/packages/hoppscotch-selfhost-web/src/api/queries/GetRestUserHistory.graphql@@ -1,6 +1,6 @@-query GetRESTUserHistory {+query GetRESTUserHistory($take: Int) {me {- RESTHistory {+ RESTHistory(take: $take) {iduserUidreqType@@ -10,7 +10,7 @@ query GetRESTUserHistory {executedOn}- GQLHistory {+ GQLHistory(take: $take) {iduserUidreqType@@ -21,3 +21,4 @@ query GetRESTUserHistory {}}}+