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
refactor(common): improve syncing systems and remove platform-wise duplications (#6334)
Anwarul Islam863b1b29a803
diff --git a/packages/hoppscotch-backend/src/errors.ts b/packages/hoppscotch-backend/src/errors.tsindex 56bcbfbec..fac347388 100644--- a/packages/hoppscotch-backend/src/errors.ts+++ b/packages/hoppscotch-backend/src/errors.ts@@ -424,8 +424,8 @@ export const USER_SETTINGS_NULL_SETTINGS =* Global environment doesn't exist for the user* (UserEnvironmentsService)*/-export const USER_ENVIRONMENT_GLOBAL_ENV_DOES_NOT_EXISTS =- 'user_environment/global_env_does_not_exists' as const;+export const USER_ENVIRONMENT_GLOBAL_ENV_DOES_NOT_EXIST =+ 'user_environment/global_env_does_not_exist' as const;/*** Global environment already exists for the user@@ -438,8 +438,8 @@ export const USER_ENVIRONMENT_GLOBAL_ENV_EXISTS =* User environment doesn't exist for the user* (UserEnvironmentsService)*/-export const USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS =- 'user_environment/user_env_does_not_exists' as const;+export const USER_ENVIRONMENT_ENV_DOES_NOT_EXIST =+ 'user_environment/user_env_does_not_exist' as const;/*** Cannot delete the global user environmentdiff --git a/packages/hoppscotch-backend/src/user-collection/user-collection.resolver.ts b/packages/hoppscotch-backend/src/user-collection/user-collection.resolver.tsindex e3870d9a8..0bc8d9250 100644--- a/packages/hoppscotch-backend/src/user-collection/user-collection.resolver.ts+++ b/packages/hoppscotch-backend/src/user-collection/user-collection.resolver.ts@@ -417,7 +417,7 @@ export class UserCollectionResolver {return updatedUserCollection.right;}- @Mutation(() => Boolean, {+ @Mutation(() => UserCollectionExportJSONData, {description: 'Duplicate a User Collection',})@UseGuards(GqlAuthGuard)diff --git a/packages/hoppscotch-backend/src/user-collection/user-collection.service.ts b/packages/hoppscotch-backend/src/user-collection/user-collection.service.tsindex 87b180f73..85212be4b 100644--- a/packages/hoppscotch-backend/src/user-collection/user-collection.service.ts+++ b/packages/hoppscotch-backend/src/user-collection/user-collection.service.ts@@ -1287,7 +1287,7 @@ export class UserCollectionService {* Duplicate a User Collection** @param collectionID The Collection ID- * @returns Boolean of duplication status+ * @returns An Either of the duplicated UserCollectionExportJSONData*/async duplicateUserCollection(collectionID: string,@@ -1321,7 +1321,7 @@ export class UserCollectionService {);if (E.isLeft(result)) return E.left(result.left as string);- return E.right(true);+ return E.right(result.right);}/**diff --git a/packages/hoppscotch-backend/src/user-environment/user-environments.service.spec.ts b/packages/hoppscotch-backend/src/user-environment/user-environments.service.spec.tsindex d98981b81..6ac16e98c 100644--- a/packages/hoppscotch-backend/src/user-environment/user-environments.service.spec.ts+++ b/packages/hoppscotch-backend/src/user-environment/user-environments.service.spec.ts@@ -3,8 +3,9 @@ import { mockDeep, mockReset } from 'jest-mock-extended';import { PrismaService } from '../prisma/prisma.service';import { UserEnvironmentsService } from './user-environments.service';import {- USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS,+ USER_ENVIRONMENT_ENV_DOES_NOT_EXIST,USER_ENVIRONMENT_GLOBAL_ENV_DELETION_FAILED,+ USER_ENVIRONMENT_GLOBAL_ENV_DOES_NOT_EXIST,USER_ENVIRONMENT_GLOBAL_ENV_EXISTS,USER_ENVIRONMENT_INVALID_ENVIRONMENT_NAME,} from '../errors';@@ -140,7 +141,7 @@ describe('UserEnvironmentsService', () => {expect(await userEnvironmentsService.fetchUserGlobalEnvironment('abc'),- ).toEqualLeft(USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS);+ ).toEqualLeft(USER_ENVIRONMENT_GLOBAL_ENV_DOES_NOT_EXIST);});});@@ -359,7 +360,7 @@ describe('UserEnvironmentsService', () => {'[{}]',mockUser,),- ).toEqualLeft(USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS);+ ).toEqualLeft(USER_ENVIRONMENT_ENV_DOES_NOT_EXIST);});test('Should update a users personal environment and publish an updated subscription ', async () => {@@ -458,7 +459,7 @@ describe('UserEnvironmentsService', () => {return expect(await userEnvironmentsService.deleteUserEnvironment('abc123', 'env1'),- ).toEqualLeft(USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS);+ ).toEqualLeft(USER_ENVIRONMENT_ENV_DOES_NOT_EXIST);});test('Should resolve right, delete a users personal environment and publish a deleted subscription', async () => {@@ -545,7 +546,7 @@ describe('UserEnvironmentsService', () => {return expect(await userEnvironmentsService.deleteUserEnvironment('abc123', 'genv1'),- ).toEqualLeft(USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS);+ ).toEqualLeft(USER_ENVIRONMENT_ENV_DOES_NOT_EXIST);});test('Should resolve right,delete all variables inside users global environment and publish an updated subscription', async () => {diff --git a/packages/hoppscotch-backend/src/user-environment/user-environments.service.ts b/packages/hoppscotch-backend/src/user-environment/user-environments.service.tsindex b1214d065..e91d294d1 100644--- a/packages/hoppscotch-backend/src/user-environment/user-environments.service.ts+++ b/packages/hoppscotch-backend/src/user-environment/user-environments.service.ts@@ -5,8 +5,8 @@ import { PubSubService } from '../pubsub/pubsub.service';import * as E from 'fp-ts/Either';import * as O from 'fp-ts/Option';import {- USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS,- USER_ENVIRONMENT_GLOBAL_ENV_DOES_NOT_EXISTS,+ USER_ENVIRONMENT_ENV_DOES_NOT_EXIST,+ USER_ENVIRONMENT_GLOBAL_ENV_DOES_NOT_EXIST,USER_ENVIRONMENT_GLOBAL_ENV_DELETION_FAILED,USER_ENVIRONMENT_GLOBAL_ENV_EXISTS,USER_ENVIRONMENT_IS_NOT_GLOBAL,@@ -72,7 +72,7 @@ export class UserEnvironmentsService {});}- return E.left(USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS);+ return E.left(USER_ENVIRONMENT_GLOBAL_ENV_DOES_NOT_EXIST);}/**@@ -163,7 +163,7 @@ export class UserEnvironmentsService {);return E.right(updatedUserEnvironment);} catch (e) {- return E.left(USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS);+ return E.left(USER_ENVIRONMENT_ENV_DOES_NOT_EXIST);}}@@ -205,7 +205,7 @@ export class UserEnvironmentsService {);return E.right(true);} catch (e) {- return E.left(USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS);+ return E.left(USER_ENVIRONMENT_ENV_DOES_NOT_EXIST);}}@@ -240,7 +240,7 @@ export class UserEnvironmentsService {async clearGlobalEnvironments(uid: string, id: string) {const globalEnvExists = await this.checkForExistingGlobalEnv(uid);if (O.isNone(globalEnvExists))- return E.left(USER_ENVIRONMENT_GLOBAL_ENV_DOES_NOT_EXISTS);+ return E.left(USER_ENVIRONMENT_GLOBAL_ENV_DOES_NOT_EXIST);const env = globalEnvExists.value;if (env.id === id) {diff --git a/packages/hoppscotch-backend/src/user-environment/user.resolver.ts b/packages/hoppscotch-backend/src/user-environment/user.resolver.tsindex d55637f3a..e4bab7719 100644--- a/packages/hoppscotch-backend/src/user-environment/user.resolver.ts+++ b/packages/hoppscotch-backend/src/user-environment/user.resolver.ts@@ -7,7 +7,7 @@ import * as E from 'fp-ts/Either';import { throwErr } from '../utils';import { GqlAuthGuard } from '../guards/gql-auth.guard';import { GqlUser } from '../decorators/gql-user.decorator';-import { USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS } from '../errors';+import { USER_ENVIRONMENT_ENV_DOES_NOT_EXIST } from '../errors';@Resolver(() => User)export class UserEnvsUserResolver {@@ -34,7 +34,7 @@ export class UserEnvsUserResolver {@GqlUser() requestingUser: User,): Promise<UserEnvironment | string> {if (requestingUser?.uid !== user.uid) {- throwErr(USER_ENVIRONMENT_ENV_DOES_NOT_EXISTS);+ throwErr(USER_ENVIRONMENT_ENV_DOES_NOT_EXIST);}const userEnvironment =await this.userEnvironmentsService.fetchUserGlobalEnvironment(user.uid);diff --git a/packages/hoppscotch-common/src/components/collections/ImportExport.vue b/packages/hoppscotch-common/src/components/collections/ImportExport.vueindex 4572a7f2d..051886f2f 100644--- a/packages/hoppscotch-common/src/components/collections/ImportExport.vue+++ b/packages/hoppscotch-common/src/components/collections/ImportExport.vue@@ -60,6 +60,7 @@ import IconUser from "~icons/lucide/user"import { getTeamCollectionJSON } from "~/helpers/backend/helpers"import { platform } from "~/platform"+import { sync } from "~/lib/sync/defs"import {initializeDownloadFile,@@ -142,12 +143,9 @@ const importToPersonalWorkspace = (collections: HoppCollection[]) => {sanitizedCollections.forEach(populateLocalStoresFromCollectionTree)- if (- platform.sync.collections.importToPersonalWorkspace &&- currentUser.value- ) {+ if (sync.collections.importToPersonalWorkspace && currentUser.value) {// The SH adds the id to the collection and folders but for safety we remove it by sanitizeCollection- return platform.sync.collections.importToPersonalWorkspace(+ return sync.collections.importToPersonalWorkspace(sanitizedCollections,ReqType.Rest)diff --git a/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vue b/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vueindex 77ebdf16c..f1b72ccc9 100644--- a/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vue+++ b/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vue@@ -25,6 +25,7 @@ import { initializeDownloadFile } from "~/helpers/import-export/export"import { useReadonlyStream } from "~/composables/stream"import { platform } from "~/platform"+import { sync } from "~/lib/sync/defs"import {appendGraphqlCollections,graphqlCollections$,@@ -239,11 +240,8 @@ const handleImportToStore = (gqlCollections: HoppCollection[]) => {const collectionsWithRefIds = gqlCollections.map(ensureRefIds)collectionsWithRefIds.forEach(populateLocalStoresFromCollectionTree)- if (- platform.sync.collections.importToPersonalWorkspace &&- currentUser.value- ) {- return platform.sync.collections.importToPersonalWorkspace(+ if (sync.collections.importToPersonalWorkspace && currentUser.value) {+ return sync.collections.importToPersonalWorkspace(collectionsWithRefIds,ReqType.Gql)diff --git a/packages/hoppscotch-common/src/components/history/Personal.vue b/packages/hoppscotch-common/src/components/history/Personal.vueindex e235a5c62..82600e87b 100644--- a/packages/hoppscotch-common/src/components/history/Personal.vue+++ b/packages/hoppscotch-common/src/components/history/Personal.vue@@ -160,39 +160,39 @@</template><script setup lang="ts">-import IconHelpCircle from "~icons/lucide/help-circle"-import IconTrash2 from "~icons/lucide/trash-2"-import IconTrash from "~icons/lucide/trash"-import IconFilter from "~icons/lucide/filter"-import { computed, ref, Ref, toRaw } from "vue"+import { useI18n } from "@composables/i18n"+import { useReadonlyStream } from "@composables/stream"import { useColorMode } from "@composables/theming"+import { useToast } from "@composables/toast"import { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"-import { groupBy, escapeRegExp, filter } from "lodash-es"import { useTimeAgo } from "@vueuse/core"-import { pipe } from "fp-ts/function"import * as A from "fp-ts/Array"-import { useI18n } from "@composables/i18n"-import { useReadonlyStream } from "@composables/stream"-import { useToast } from "@composables/toast"+import { pipe } from "fp-ts/function"+import { escapeRegExp, filter, groupBy } from "lodash-es"+import { computed, ref, Ref, toRaw } from "vue"import {- restHistory$,- graphqlHistory$,- clearRESTHistory,clearGraphqlHistory,- toggleGraphqlHistoryEntryStar,- toggleRESTHistoryEntryStar,+ clearRESTHistory,deleteGraphqlHistoryEntry,deleteRESTHistoryEntry,- RESTHistoryEntry,GQLHistoryEntry,+ graphqlHistory$,+ restHistory$,+ RESTHistoryEntry,+ toggleGraphqlHistoryEntryStar,+ toggleRESTHistoryEntryStar,} from "~/newstore/history"+import IconFilter from "~icons/lucide/filter"+import IconHelpCircle from "~icons/lucide/help-circle"+import IconTrash from "~icons/lucide/trash"+import IconTrash2 from "~icons/lucide/trash-2"-import HistoryRestCard from "./rest/Card.vue"-import HistoryGraphqlCard from "./graphql/Card.vue"-import { defineActionHandler, invokeAction } from "~/helpers/actions"import { useService } from "dioc/vue"+import { defineActionHandler, invokeAction } from "~/helpers/actions"+import { sync } from "~/lib/sync/defs"import { RESTTabService } from "~/services/tab/rest"-import { platform } from "~/platform"+import HistoryGraphqlCard from "./graphql/Card.vue"+import HistoryRestCard from "./rest/Card.vue"type HistoryEntry = GQLHistoryEntry | RESTHistoryEntry@@ -219,13 +219,7 @@ const history = useReadonlyStream<RESTHistoryEntry[] | GQLHistoryEntry[]>()const { isHistoryStoreEnabled, isFetchingHistoryStoreStatus } =- "requestHistoryStore" in platform.sync.history &&- platform.sync.history.requestHistoryStore- ? platform.sync.history.requestHistoryStore- : {- isHistoryStoreEnabled: ref(true),- isFetchingHistoryStoreStatus: ref(false),- }+ sync.history.requestHistoryStoreconst deepCheckForRegex = (value: unknown, regExp: RegExp): boolean => {if (value === null || value === undefined) return falsediff --git a/packages/hoppscotch-common/src/composables/useMockServer.ts b/packages/hoppscotch-common/src/composables/useMockServer.tsindex 8e02423da..13f6a9778 100644--- a/packages/hoppscotch-common/src/composables/useMockServer.ts+++ b/packages/hoppscotch-common/src/composables/useMockServer.ts@@ -9,6 +9,7 @@ import { computed } from "vue"import { WorkspaceType } from "~/helpers/backend/graphql"import type { MockServer } from "~/helpers/backend/types/MockServer"import { platform } from "~/platform"+import { sync } from "~/lib/sync/defs"import {createTeamEnvironment,updateTeamEnvironment,@@ -101,8 +102,8 @@ export function useMockServer() {teamCollectionsService.changeTeamID(currentWorkspace.value.teamID)} else {// For personal workspace, load REST collections only (mock servers are REST-based)- if (platform.sync.collections.loadUserCollections) {- await platform.sync.collections.loadUserCollections("REST")+ if (sync.collections.loadUserCollections) {+ await sync.collections.loadUserCollections("REST")}}} catch (error) {diff --git a/packages/hoppscotch-common/src/helpers/app/index.ts b/packages/hoppscotch-common/src/helpers/app/index.tsindex 75372e8d5..883cb92a6 100644--- a/packages/hoppscotch-common/src/helpers/app/index.ts+++ b/packages/hoppscotch-common/src/helpers/app/index.ts@@ -1,4 +1,5 @@import { platform } from "~/platform"+import { sync } from "~/lib/sync/defs"let initialized = false@@ -6,10 +7,10 @@ export function initializeApp() {if (!initialized) {try {platform.auth.performAuthInit()- platform.sync.settings.initSettingsSync()- platform.sync.collections.initCollectionsSync()- platform.sync.history.initHistorySync()- platform.sync.environments.initEnvironmentsSync()+ sync.settings.initSettingsSync()+ sync.collections.initCollectionsSync()+ sync.history.initHistorySync()+ sync.environments.initEnvironmentsSync()platform.analytics?.initAnalytics()initialized = truediff --git a/packages/hoppscotch-common/src/helpers/backend/GQLClient.ts b/packages/hoppscotch-common/src/helpers/backend/GQLClient.tsindex d79204de5..d3ac3baab 100644--- a/packages/hoppscotch-common/src/helpers/backend/GQLClient.ts+++ b/packages/hoppscotch-common/src/helpers/backend/GQLClient.ts@@ -192,6 +192,11 @@ export function initBackendGQLClient() {type RunQueryOptions<T = any, V = AnyVariables> = {query: TypedDocumentNode<T, V>variables: V+ // When true, skip awaiting `platform.auth.waitOrganizationInfoReady` before+ // issuing the request. This MUST be left unset for ordinary calls: it exists+ // for the org-info bootstrap query itself (GetOrganizationInfoByDomain),+ // which determines the org id and would otherwise deadlock waiting on itself.+ skipOrgInfoWait?: boolean}/**@@ -207,13 +212,28 @@ export type GQLError<T extends string> =error: T}-export const runGQLQuery = <+export const runGQLQuery = async <DocType,DocVarType extends AnyVariables,DocErrorType extends string,>(args: RunQueryOptions<DocType, DocVarType>): Promise<E.Either<GQLError<DocErrorType>, DocType>> => {+ // Gate the request on the org info lookup so `getBackendHeaders` has the+ // `x-organization-id` set by the time the call goes out. The bootstrap+ // query (which resolves the org id) passes `skipOrgInfoWait` to avoid+ // waiting on itself.+ if (!args.skipOrgInfoWait) {+ try {+ await platform.auth.waitOrganizationInfoReady?.()+ } catch (e: any) {+ return E.left({+ type: "network_error",+ error: e instanceof Error ? e : new Error(String(e)),+ })+ }+ }+const request = createRequest<DocType, DocVarType>(args.query, args.variables)const source = client.value!.executeQuery(request, {requestPolicy: "network-only",@@ -280,53 +300,87 @@ export const runGQLSubscription = <) => {const result$ = new Subject<E.Either<GQLError<DocErrorType>, DocType>>()- const source = client.value!.executeSubscription(- createRequest(args.query, args.variables)- )+ // The wonka subscription isn't created until after the org-info wait below,+ // so track it here and expose a stable handle that callers can unsubscribe+ // from immediately (matches the shape of the previously returned sub).+ let wonkaSub: { unsubscribe: () => void } | null = null+ let unsubscribeRequested = false+ const sub = {+ unsubscribe() {+ unsubscribeRequested = true+ wonkaSub?.unsubscribe()+ },+ }- const sub = wonkaPipe(- source,- subscribe((res) => {+ ;(async () => {+ // Gate the subscription on org info so `connectionParams` carries the+ // `x-organization-id`. See runGQLQuery for the bootstrap skip rationale.+ try {+ if (!args.skipOrgInfoWait) {+ await platform.auth.waitOrganizationInfoReady?.()+ }+ } catch (e: any) {result$.next(- pipe(- // The target- res.data as DocType | undefined,- // Define what happens if data does not exist (it is an error)- E.fromNullable(- pipe(- // Take the network error value- res.error?.networkError,- // If it null, set the left to the generic error name- E.fromNullable(res.error?.message),- E.match(- // The left case (network error was null)- (gqlErr) => {- if (res.error) {- gqlClientError$.next({- type: "GQL_CLIENT_REPORTED_ERROR",- opType: "subscription",- opResult: res,- })- }+ E.left({+ type: "network_error",+ error: e instanceof Error ? e : new Error(String(e)),+ })+ )+ return+ }- return <GQLError<DocErrorType>>{- type: "gql_error",- error: parseGQLErrorString(gqlErr ?? "") as DocErrorType,- }- },- // The right case (it was a GraphQL Error)- (networkErr) =>- <GQLError<DocErrorType>>{- type: "network_error",- error: networkErr,- }+ const source = client.value!.executeSubscription(+ createRequest(args.query, args.variables)+ )++ wonkaSub = wonkaPipe(+ source,+ subscribe((res) => {+ result$.next(+ pipe(+ // The target+ res.data as DocType | undefined,+ // Define what happens if data does not exist (it is an error)+ E.fromNullable(+ pipe(+ // Take the network error value+ res.error?.networkError,+ // If it null, set the left to the generic error name+ E.fromNullable(res.error?.message),+ E.match(+ // The left case (network error was null)+ (gqlErr) => {+ if (res.error) {+ gqlClientError$.next({+ type: "GQL_CLIENT_REPORTED_ERROR",+ opType: "subscription",+ opResult: res,+ })+ }++ return <GQLError<DocErrorType>>{+ type: "gql_error",+ error: parseGQLErrorString(gqlErr ?? "") as DocErrorType,+ }+ },+ // The right case (it was a GraphQL Error)+ (networkErr) =>+ <GQLError<DocErrorType>>{+ type: "network_error",+ error: networkErr,+ }+ )))))- )- })- )+ })+ )++ if (unsubscribeRequested) {+ wonkaSub.unsubscribe()+ }+ })()// Returns the stream and a subscription handle to unsubreturn [result$, sub] as const@@ -372,14 +426,23 @@ export const runMutation = <): TE.TaskEither<GQLError<DocErrors>, DocType> =>pipe(TE.tryCatch(- () =>- client+ async () => {+ // Gate the mutation on org info so the `x-organization-id` header is+ // present. Mutations are user-triggered and never part of the org-id+ // bootstrap, so they always wait.+ await platform.auth.waitOrganizationInfoReady?.()+ return client.value!.mutation(mutation, variables, {requestPolicy: "cache-and-network",...additionalConfig,})- .toPromise(),- () => constVoid() as never // The mutation function can never fail, so this will never be called ;)+ .toPromise()+ },+ (err) =>+ ({+ type: "network_error",+ error: err instanceof Error ? err : new Error(String(err)),+ }) as GQLError<DocErrors>),TE.chainEitherK((result) =>pipe(diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/ClearGlobalEnvironments.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/ClearGlobalEnvironments.graphqlnew file mode 100644index 000000000..5a184fcf8--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/ClearGlobalEnvironments.graphql@@ -0,0 +1,5 @@+mutation ClearGlobalEnvironments($id: ID!) {+ clearGlobalEnvironments(id: $id) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateGQLChildUserCollection.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateGQLChildUserCollection.graphqlnew file mode 100644index 000000000..736781a47--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateGQLChildUserCollection.graphql@@ -0,0 +1,14 @@+mutation CreateGQLChildUserCollection(+ $title: String!+ $parentUserCollectionID: ID!+ $data: String+) {+ createGQLChildUserCollection(+ title: $title+ parentUserCollectionID: $parentUserCollectionID+ data: $data+ ) {+ id+ data+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateGQLRootUserCollection.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateGQLRootUserCollection.graphqlnew file mode 100644index 000000000..bc30e96d2--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateGQLRootUserCollection.graphql@@ -0,0 +1,6 @@+mutation CreateGQLRootUserCollection($title: String!, $data: String) {+ createGQLRootUserCollection(title: $title, data: $data) {+ id+ data+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateGQLUserRequest.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateGQLUserRequest.graphqlnew file mode 100644index 000000000..02423e864--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateGQLUserRequest.graphql@@ -0,0 +1,13 @@+mutation CreateGQLUserRequest(+ $title: String!+ $request: String!+ $collectionID: ID!+) {+ createGQLUserRequest(+ title: $title+ request: $request+ collectionID: $collectionID+ ) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateRESTChildUserCollection.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateRESTChildUserCollection.graphqlnew file mode 100644index 000000000..eea3cdf75--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateRESTChildUserCollection.graphql@@ -0,0 +1,14 @@+mutation CreateRESTChildUserCollection(+ $title: String!+ $parentUserCollectionID: ID!+ $data: String+) {+ createRESTChildUserCollection(+ title: $title+ parentUserCollectionID: $parentUserCollectionID+ data: $data+ ) {+ id+ data+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserEnvironment.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserEnvironment.graphqlnew file mode 100644index 000000000..186510644--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserEnvironment.graphql@@ -0,0 +1,9 @@+mutation CreateUserEnvironment($name: String!, $variables: String!) {+ createUserEnvironment(name: $name, variables: $variables) {+ id+ userUid+ name+ variables+ isGlobal+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserGlobalEnvironment.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserGlobalEnvironment.graphqlnew file mode 100644index 000000000..8e7553f32--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserGlobalEnvironment.graphql@@ -0,0 +1,5 @@+mutation CreateUserGlobalEnvironment($variables: String!) {+ createUserGlobalEnvironment(variables: $variables) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserHistory.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserHistory.graphqlnew file mode 100644index 000000000..ef9da5c66--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserHistory.graphql@@ -0,0 +1,13 @@+mutation CreateUserHistory(+ $reqData: String!+ $resMetadata: String!+ $reqType: ReqType!+) {+ createUserHistory(+ reqData: $reqData+ resMetadata: $resMetadata+ reqType: $reqType+ ) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserSettings.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserSettings.graphqlnew file mode 100644index 000000000..2ada8a1fa--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/CreateUserSettings.graphql@@ -0,0 +1,5 @@+mutation CreateUserSettings($properties: String!) {+ createUserSettings(properties: $properties) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteAllUserHistory.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteAllUserHistory.graphqlnew file mode 100644index 000000000..3e5085870--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteAllUserHistory.graphql@@ -0,0 +1,6 @@+mutation DeleteAllUserHistory($reqType: ReqType!) {+ deleteAllUserHistory(reqType: $reqType) {+ count+ reqType+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteUserCollection.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteUserCollection.graphqlnew file mode 100644index 000000000..cafa7b08a--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteUserCollection.graphql@@ -0,0 +1,3 @@+mutation DeleteUserCollection($userCollectionID: ID!) {+ deleteUserCollection(userCollectionID: $userCollectionID)+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteUserEnvironments.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteUserEnvironments.graphqlnew file mode 100644index 000000000..148971933--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteUserEnvironments.graphql@@ -0,0 +1,3 @@+mutation DeleteUserEnvironment($id: ID!) {+ deleteUserEnvironment(id: $id)+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteUserRequest.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteUserRequest.graphqlnew file mode 100644index 000000000..c4855e807--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DeleteUserRequest.graphql@@ -0,0 +1,3 @@+mutation DeleteUserRequest($requestID: ID!) {+ deleteUserRequest(id: $requestID)+}diff --git a/packages/hoppscotch-selfhost-web/src/api/mutations/DuplicateUserCollection.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DuplicateUserCollection.graphqlsimilarity index 71%rename from packages/hoppscotch-selfhost-web/src/api/mutations/DuplicateUserCollection.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/mutations/DuplicateUserCollection.graphqlindex 78d68bcdb..c9de0cb51 100644--- a/packages/hoppscotch-selfhost-web/src/api/mutations/DuplicateUserCollection.graphql+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/DuplicateUserCollection.graphql@@ -1,3 +1,6 @@mutation DuplicateUserCollection($collectionID: String!, $reqType: ReqType!) {- duplicateUserCollection(collectionID: $collectionID, reqType: $reqType)+ duplicateUserCollection(collectionID: $collectionID, reqType: $reqType) {+ exportedCollection+ collectionType+ }}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/ImportUserCollectionsFromJSON.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/ImportUserCollectionsFromJSON.graphqlnew file mode 100644index 000000000..beddb8720--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/ImportUserCollectionsFromJSON.graphql@@ -0,0 +1,14 @@+mutation ImportUserCollectionsFromJSON(+ $jsonString: String!+ $reqType: ReqType!+ $parentCollectionID: ID+) {+ importUserCollectionsFromJSON(+ jsonString: $jsonString+ reqType: $reqType+ parentCollectionID: $parentCollectionID+ ) {+ exportedCollection+ collectionType+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/MoveUserCollection.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/MoveUserCollection.graphqlnew file mode 100644index 000000000..ac280122f--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/MoveUserCollection.graphql@@ -0,0 +1,8 @@+mutation MoveUserCollection($destCollectionID: ID, $userCollectionID: ID!) {+ moveUserCollection(+ destCollectionID: $destCollectionID+ userCollectionID: $userCollectionID+ ) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/MoveUserRequest.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/MoveUserRequest.graphqlnew file mode 100644index 000000000..38f8e6ca7--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/MoveUserRequest.graphql@@ -0,0 +1,15 @@+mutation MoveUserRequest(+ $sourceCollectionID: ID!+ $requestID: ID!+ $destinationCollectionID: ID!+ $nextRequestID: ID+) {+ moveUserRequest(+ sourceCollectionID: $sourceCollectionID+ requestID: $requestID+ destinationCollectionID: $destinationCollectionID+ nextRequestID: $nextRequestID+ ) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/RemoveRequestFromHistory.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/RemoveRequestFromHistory.graphqlnew file mode 100644index 000000000..a0dd3e988--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/RemoveRequestFromHistory.graphql@@ -0,0 +1,5 @@+mutation RemoveRequestFromHistory($id: ID!) {+ removeRequestFromHistory(id: $id) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/RenameUserCollection.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/RenameUserCollection.graphqlnew file mode 100644index 000000000..35603cea6--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/RenameUserCollection.graphql@@ -0,0 +1,8 @@+mutation RenameUserCollection($userCollectionID: ID!, $newTitle: String!) {+ renameUserCollection(+ userCollectionID: $userCollectionID+ newTitle: $newTitle+ ) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/SortUserCollections.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/SortUserCollections.graphqlnew file mode 100644index 000000000..6417fd9d5--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/SortUserCollections.graphql@@ -0,0 +1,9 @@+mutation SortUserCollections(+ $parentCollectionID: ID+ $sortOption: SortOptions!+) {+ sortUserCollections(+ parentCollectionID: $parentCollectionID+ sortOption: $sortOption+ )+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/ToggleHistoryStarStatus.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/ToggleHistoryStarStatus.graphqlnew file mode 100644index 000000000..33bf9c173--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/ToggleHistoryStarStatus.graphql@@ -0,0 +1,5 @@+mutation ToggleHistoryStarStatus($id: ID!) {+ toggleHistoryStarStatus(id: $id) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateGQLUserRequest.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateGQLUserRequest.graphqlnew file mode 100644index 000000000..253fed7db--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateGQLUserRequest.graphql@@ -0,0 +1,5 @@+mutation UpdateGQLUserRequest($id: ID!, $request: String!, $title: String) {+ updateGQLUserRequest(id: $id, request: $request, title: $title) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateRESTUserRequest.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateRESTUserRequest.graphqlnew file mode 100644index 000000000..b7899df9e--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateRESTUserRequest.graphql@@ -0,0 +1,7 @@+mutation UpdateRESTUserRequest($id: ID!, $title: String!, $request: String!) {+ updateRESTUserRequest(id: $id, title: $title, request: $request) {+ id+ collectionID+ request+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserCollection.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserCollection.graphqlnew file mode 100644index 000000000..c5e89d22c--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserCollection.graphql@@ -0,0 +1,15 @@+mutation UpdateUserCollection(+ $userCollectionID: ID!+ $newTitle: String+ $data: String+) {+ updateUserCollection(+ userCollectionID: $userCollectionID+ newTitle: $newTitle+ data: $data+ ) {+ id+ title+ data+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserCollectionOrder.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserCollectionOrder.graphqlnew file mode 100644index 000000000..c9e665be0--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserCollectionOrder.graphql@@ -0,0 +1,6 @@+mutation UpdateUserCollectionOrder($collectionID: ID!, $nextCollectionID: ID) {+ updateUserCollectionOrder(+ collectionID: $collectionID+ nextCollectionID: $nextCollectionID+ )+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserDisplayName.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserDisplayName.graphqlnew file mode 100644index 000000000..90a9eed92--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserDisplayName.graphql@@ -0,0 +1,5 @@+mutation UpdateUserDisplayName($updatedDisplayName: String!) {+ updateDisplayName(updatedDisplayName: $updatedDisplayName) {+ displayName+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserEnvironment.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserEnvironment.graphqlnew file mode 100644index 000000000..c849a1541--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserEnvironment.graphql@@ -0,0 +1,9 @@+mutation UpdateUserEnvironment($id: ID!, $name: String!, $variables: String!) {+ updateUserEnvironment(id: $id, name: $name, variables: $variables) {+ id+ userUid+ name+ variables+ isGlobal+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserSettings.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserSettings.graphqlnew file mode 100644index 000000000..85bb4b0e6--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/mutations/UpdateUserSettings.graphql@@ -0,0 +1,5 @@+mutation UpdateUserSettings($properties: String!) {+ updateUserSettings(properties: $properties) {+ id+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/queries/ExportUserCollectionsToJSON.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/queries/ExportUserCollectionsToJSON.graphqlnew file mode 100644index 000000000..09f54adb9--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/queries/ExportUserCollectionsToJSON.graphql@@ -0,0 +1,12 @@+query ExportUserCollectionsToJSON(+ $collectionID: ID+ $collectionType: ReqType!+) {+ exportUserCollectionsToJSON(+ collectionID: $collectionID+ collectionType: $collectionType+ ) {+ collectionType+ exportedCollection+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetGlobalEnvironments.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetGlobalEnvironments.graphqlnew file mode 100644index 000000000..08d3c2143--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetGlobalEnvironments.graphql@@ -0,0 +1,11 @@+query GetGlobalEnvironments {+ me {+ globalEnvironments {+ id+ isGlobal+ name+ userUid+ variables+ }+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetRestUserHistory.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetRestUserHistory.graphqlnew file mode 100644index 000000000..144861594--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetRestUserHistory.graphql@@ -0,0 +1,23 @@+query GetRESTUserHistory {+ me {+ RESTHistory {+ id+ userUid+ reqType+ request+ responseMetadata+ isStarred+ executedOn+ }++ GQLHistory {+ id+ userUid+ reqType+ request+ responseMetadata+ isStarred+ executedOn+ }+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetSMTPStatus.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetSMTPStatus.graphqlnew file mode 100644index 000000000..bb8458ddb--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetSMTPStatus.graphql@@ -0,0 +1,3 @@+query GetSMTPStatus {+ isSMTPEnabled+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetUserEnvironments.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetUserEnvironments.graphqlnew file mode 100644index 000000000..0bbeddbb4--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetUserEnvironments.graphql@@ -0,0 +1,11 @@+query GetUserEnvironments {+ me {+ environments {+ id+ isGlobal+ name+ userUid+ variables+ }+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetUserRootCollections.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetUserRootCollections.graphqlnew file mode 100644index 000000000..57a1e05a3--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetUserRootCollections.graphql@@ -0,0 +1,15 @@+query GetUserRootCollections {+ # the frontend doesn't paginate right now, so giving take a big enough value to get all collections at once+ rootRESTUserCollections(take: 99999) {+ id+ title+ type+ data+ childrenREST {+ id+ title+ type+ data+ }+ }+}diff --git a/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetUserSettings.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetUserSettings.graphqlnew file mode 100644index 000000000..1ac94553e--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/backend/gql/queries/GetUserSettings.graphql@@ -0,0 +1,8 @@+query GetUserSettings {+ me {+ settings {+ id+ properties+ }+ }+}diff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserChildCollectionSorted.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserChildCollectionSorted.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserChildCollectionSorted.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserChildCollectionSorted.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserCollectionCreated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserCollectionCreated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserCollectionCreated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserCollectionCreated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserCollectionMoved.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserCollectionMoved.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserCollectionMoved.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserCollectionMoved.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserCollectionOrderUpdated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserCollectionOrderUpdated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserCollectionOrderUpdated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserCollectionOrderUpdated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserCollectionRemoved.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserCollectionRemoved.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserCollectionRemoved.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserCollectionRemoved.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserCollectionUpdated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserCollectionUpdated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserCollectionUpdated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserCollectionUpdated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserEnvironmentCreated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserEnvironmentCreated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserEnvironmentCreated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserEnvironmentCreated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserEnvironmentDeleted.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserEnvironmentDeleted.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserEnvironmentDeleted.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserEnvironmentDeleted.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserEnvironmentUpdated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserEnvironmentUpdated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserEnvironmentUpdated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserEnvironmentUpdated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserHistoryAllDeleted.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserHistoryAllDeleted.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserHistoryAllDeleted.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserHistoryAllDeleted.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserHistoryCreated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserHistoryCreated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserHistoryCreated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserHistoryCreated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserHistoryDeleted.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserHistoryDeleted.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserHistoryDeleted.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserHistoryDeleted.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserHistoryDeletedMany.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserHistoryDeletedMany.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserHistoryDeletedMany.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserHistoryDeletedMany.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserHistoryUpdated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserHistoryUpdated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserHistoryUpdated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserHistoryUpdated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserRequestCreated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserRequestCreated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserRequestCreated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserRequestCreated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserRequestDeleted.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserRequestDeleted.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserRequestDeleted.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserRequestDeleted.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserRequestMoved.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserRequestMoved.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserRequestMoved.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserRequestMoved.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserRequestUpdated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserRequestUpdated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserRequestUpdated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserRequestUpdated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserRootCollectionsSorted.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserRootCollectionsSorted.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserRootCollectionsSorted.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserRootCollectionsSorted.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/UserSettingsUpdated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserSettingsUpdated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/UserSettingsUpdated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/UserSettingsUpdated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/api/subscriptions/userCollectionDuplicated.graphql b/packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/userCollectionDuplicated.graphqlsimilarity index 100%rename from packages/hoppscotch-selfhost-web/src/api/subscriptions/userCollectionDuplicated.graphqlrename to packages/hoppscotch-common/src/helpers/backend/gql/subscriptions/userCollectionDuplicated.graphqldiff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/web/api.ts b/packages/hoppscotch-common/src/lib/sync/collections/api.tssimilarity index 99%rename from packages/hoppscotch-selfhost-web/src/platform/collections/web/api.tsrename to packages/hoppscotch-common/src/lib/sync/collections/api.tsindex 697722e68..bae898733 100644--- a/packages/hoppscotch-selfhost-web/src/platform/collections/web/api.ts+++ b/packages/hoppscotch-common/src/lib/sync/collections/api.ts@@ -1,3 +1,9 @@+import {+ runGQLQuery,+ runGQLSubscription,+ runMutation,+} from "~/helpers/backend/GQLClient"+import {CreateGqlChildUserCollectionDocument,CreateGqlChildUserCollectionMutation,@@ -70,12 +76,7 @@ import {UserRequestMovedDocument,UserRequestUpdatedDocument,UserRootCollectionsSortedDocument,-} from "@app/api/generated/graphql"-import {- runGQLQuery,- runGQLSubscription,- runMutation,-} from "@hoppscotch/common/helpers/backend/GQLClient"+} from "~/helpers/backend/graphql"export const createRESTRootUserCollection = (title: string, data?: string) =>runMutation<diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/web/gqlCollections.sync.ts b/packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.tssimilarity index 69%rename from packages/hoppscotch-selfhost-web/src/platform/collections/web/gqlCollections.sync.tsrename to packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.tsindex 42db9ab16..1d6a1c1d3 100644--- a/packages/hoppscotch-selfhost-web/src/platform/collections/web/gqlCollections.sync.ts+++ b/packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.ts@@ -1,25 +1,9 @@-import {- graphqlCollectionStore,- navigateToFolderWithIndexPath,- removeDuplicateGraphqlCollectionOrFolder,-} from "@hoppscotch/common/newstore/collections"-import {- getSettingSubject,- settingsStore,-} from "@hoppscotch/common/newstore/settings"-import {generateUniqueRefId,HoppCollection,HoppRESTRequest,} from "@hoppscotch/data"-import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"--import { getSyncInitFunction, type StoreSyncDefinitionOf } from "@app/lib/sync"--import { createMapper } from "@app/lib/sync/mapper"-import {createGQLChildUserCollection,createGQLRootUserCollection,@@ -33,8 +17,17 @@ import {} from "./api"import * as E from "fp-ts/Either"-import { ReqType } from "@app/api/generated/graphql"-import { moveOrReorderRequests } from "./sync"+import {+ graphqlCollectionStore,+ navigateToFolderWithIndexPath,+ removeDuplicateGraphqlCollectionOrFolder,+} from "~/newstore/collections"+import { getSettingSubject, settingsStore } from "~/newstore/settings"+import { getSyncInitFunction, StoreSyncDefinitionOf } from ".."+import { createMapper } from "../mapper"+import { applyDuplicatedCollectionResult, moveOrReorderRequests } from "./sync"+import { ReqType } from "~/helpers/backend/graphql"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"// gqlCollectionsMapper uses the collectionPath as the local identifier// Helper function to transform HoppCollection to backend format@@ -47,9 +40,6 @@ const transformCollectionForBackend = (collection: HoppCollection): any => {headers: collection.headers ?? [],variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",}return {@@ -84,9 +74,6 @@ const recursivelySyncCollections = async (headers: collection.headers ?? [],variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",}const res = await createGQLRootUserCollection(collection.name,@@ -106,9 +93,6 @@ const recursivelySyncCollections = async (headers: [],variables: [],_ref_id: generateUniqueRefId("coll"),- description: null,- preRequestScript: "",- testScript: "",}collection.id = parentCollectionID@@ -116,10 +100,8 @@ const recursivelySyncCollections = async (collection.auth = returnedData.authcollection.headers = returnedData.headerscollection.variables = returnedData.variables- collection.description = returnedData.description ?? null- collection.preRequestScript = returnedData.preRequestScript ?? ""- collection.testScript = returnedData.testScript ?? ""+ // TODO: fix type issueremoveDuplicateGraphqlCollectionOrFolder(parentCollectionID,collectionPath@@ -138,9 +120,6 @@ const recursivelySyncCollections = async (headers: collection.headers ?? [],variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",}const res = await createGQLChildUserCollection(@@ -162,9 +141,6 @@ const recursivelySyncCollections = async (headers: [],variables: [],_ref_id: generateUniqueRefId("coll"),- description: null,- preRequestScript: "",- testScript: "",}collection.id = childCollectionId@@ -173,9 +149,6 @@ const recursivelySyncCollections = async (collection.headers = returnedData.headersparentCollectionID = childCollectionIdcollection.variables = returnedData.variables- collection.description = returnedData.description ?? null- collection.preRequestScript = returnedData.preRequestScript ?? ""- collection.testScript = returnedData.testScript ?? ""removeDuplicateGraphqlCollectionOrFolder(childCollectionId,@@ -186,7 +159,7 @@ const recursivelySyncCollections = async (// create the requestsif (parentCollectionID) {- collection.requests.forEach(async (request) => {+ for (const request of collection.requests) {const res = await createGQLUserRequest(request.name,JSON.stringify(request),@@ -198,18 +171,19 @@ const recursivelySyncCollections = async (request.id = requestId}- })+ }}// create the folders aka child collections- if (parentCollectionID)- collection.folders.forEach(async (folder, index) => {- recursivelySyncCollections(+ if (parentCollectionID) {+ for (const [index, folder] of collection.folders.entries()) {+ await recursivelySyncCollections(folder,`${collectionPath}/${index}`,parentCollectionID)- })+ }+ }}// TODO: generalize this@@ -259,10 +233,10 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<let indexStart =graphqlCollectionStore.value.state.length - entries.length- entries.forEach((collection) => {- recursivelySyncCollections(collection, `${indexStart}`)+ for (const collection of entries) {+ await recursivelySyncCollections(collection, `${indexStart}`)indexStart++- })+ }}},async addCollection({ collection }) {@@ -281,24 +255,21 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<}},editCollection({ collection, collectionIndex }) {- const collectionID = navigateToFolderWithIndexPath(- graphqlCollectionStore.value.state,- [collectionIndex]- )?.id+ // 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}`const data = {auth: collection.auth,headers: collection.headers,- variables: stripSecretVariableValuesForWire(collection.variables ?? []),+ variables: stripSecretVariableValuesForWire(collection.variables),_ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",}- if (collectionID) {- updateUserCollection(collectionID, collection.name, JSON.stringify(data))- }+ updateUserCollection(collectionID, collection.name, JSON.stringify(data))},async addFolder({ name, path }) {const parentCollection = navigateToFolderWithIndexPath(@@ -306,48 +277,46 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<path.split("/").map((index) => parseInt(index)))- const parentCollectionBackendID = parentCollection?.id+ if (!parentCollection) return- if (parentCollectionBackendID) {- const foldersLength = parentCollection.folders.length+ // Send the parent backend id when present, otherwise its index path.+ const parentCollectionBackendID = parentCollection.id ?? path- const res = await createGQLChildUserCollection(- name,- parentCollectionBackendID- )+ const foldersLength = parentCollection.folders.length- if (E.isRight(res)) {- const { id } = res.right.createGQLChildUserCollection-- if (foldersLength) {- parentCollection.folders[foldersLength - 1].id = id- removeDuplicateGraphqlCollectionOrFolder(- id,- `${path}/${foldersLength - 1}`- )- }+ const res = await createGQLChildUserCollection(+ name,+ parentCollectionBackendID+ )++ 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 }) {- const folderBackendId = navigateToFolderWithIndexPath(- graphqlCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )?.id+ // Send the backend id when present, otherwise the index path.+ const folderBackendId =+ navigateToFolderWithIndexPath(+ graphqlCollectionStore.value.state,+ path.split("/").map((index) => parseInt(index))+ )?.id ?? pathconst data = {auth: folder.auth,headers: folder.headers,- variables: stripSecretVariableValuesForWire(folder.variables ?? []),+ variables: stripSecretVariableValuesForWire(folder.variables),_ref_id: folder._ref_id,- description: folder.description ?? null,- preRequestScript: folder.preRequestScript ?? "",- testScript: folder.testScript ?? "",}- if (folderBackendId) {- updateUserCollection(folderBackendId, folder.name, JSON.stringify(data))- }+ updateUserCollection(folderBackendId, folder.name, JSON.stringify(data))},async removeFolder({ folderID }) {if (folderID) {@@ -356,7 +325,15 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<},async duplicateCollection({ collectionSyncID }) {if (collectionSyncID) {- await duplicateUserCollection(collectionSyncID, ReqType.Gql)+ const res = await duplicateUserCollection(collectionSyncID, ReqType.Gql)++ if (E.isRight(res)) {+ applyDuplicatedCollectionResult(+ "GQL",+ collectionSyncID,+ res.right.duplicateUserCollection.exportedCollection+ )+ }}},editRequest({ path, requestIndex, requestNew }) {@@ -365,15 +342,14 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<path.split("/").map((index) => parseInt(index)))?.requests[requestIndex]- const requestBackendID = request?.id+ // Send the backend id when present, otherwise the index path.+ const requestBackendID = request?.id ?? `${path}/${requestIndex}`- if (requestBackendID) {- editGQLUserRequest(- requestBackendID,- (requestNew as HoppRESTRequest).name,- JSON.stringify(requestNew)- )- }+ editGQLUserRequest(+ requestBackendID,+ (requestNew as HoppRESTRequest).name,+ JSON.stringify(requestNew)+ )},async saveRequestAs({ path, request }) {const folder = navigateToFolderWithIndexPath(@@ -381,27 +357,28 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<path.split("/").map((index) => parseInt(index)))- const parentCollectionBackendID = folder?.id+ if (!folder) return- if (parentCollectionBackendID) {- const newRequest = folder.requests[folder.requests.length - 1]+ // Send the parent backend id when present, otherwise its index path.+ const parentCollectionBackendID = folder.id ?? path- const res = await createGQLUserRequest(- (request as HoppRESTRequest).name,- JSON.stringify(request),- parentCollectionBackendID- )+ const newRequest = folder.requests[folder.requests.length - 1]- if (E.isRight(res)) {- const { id } = res.right.createGQLUserRequest+ const res = await createGQLUserRequest(+ (request as HoppRESTRequest).name,+ JSON.stringify(request),+ parentCollectionBackendID+ )- newRequest.id = id- removeDuplicateGraphqlCollectionOrFolder(- id,- `${path}/${folder.requests.length - 1}`,- "request"- )- }+ if (E.isRight(res)) {+ const { id } = res.right.createGQLUserRequest++ newRequest.id = id+ removeDuplicateGraphqlCollectionOrFolder(+ id,+ `${path}/${folder.requests.length - 1}`,+ "request"+ )}},async removeRequest({ requestID }) {diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/web/import.ts b/packages/hoppscotch-common/src/lib/sync/collections/import.tssimilarity index 87%rename from packages/hoppscotch-selfhost-web/src/platform/collections/web/import.tsrename to packages/hoppscotch-common/src/lib/sync/collections/import.tsindex 2a41eaa6e..ef95b7dca 100644--- a/packages/hoppscotch-selfhost-web/src/platform/collections/web/import.ts+++ b/packages/hoppscotch-common/src/lib/sync/collections/import.ts@@ -1,9 +1,7 @@-import { ReqType } from "@hoppscotch/common/helpers/backend/graphql"-import {- appendGraphqlCollections,- appendRESTCollections,-} from "@hoppscotch/common/newstore/collections"import { generateUniqueRefId, HoppCollection } from "@hoppscotch/data"+import * as E from "fp-ts/Either"+import { ReqType } from "~/helpers/backend/graphql"+import { CollectionDataProps } from "~/helpers/backend/helpers"import {ensureRefIds,flushUnmatchedRefIdsFromTree,@@ -12,16 +10,18 @@ import {repopulateLoadedCollectionTree,stripCollectionTreeForStore,stripSecretVariableValuesForWire,-} from "@hoppscotch/common/helpers/secretVariables"-import { CollectionDataProps } from "@hoppscotch/common/helpers/backend/helpers"-import * as E from "fp-ts/Either"+} from "~/helpers/secretVariables"+import {+ appendGraphqlCollections,+ appendRESTCollections,+} from "~/newstore/collections"import {exportedCollectionToHoppCollection,ExportedUserCollectionGQL,ExportedUserCollectionREST,-} from "../web"+} from "."+import { runDispatchWithOutSyncing } from ".."import { importUserCollectionsFromJSON } from "./api"-import { runDispatchWithOutSyncing } from "@app/lib/sync"/*** Platform-specific import for selfhost-web. Self-contained — re-stamps@@ -113,18 +113,31 @@ export const importToPersonalWorkspace = async (// idempotent in the normal flow; it exists so a future caller that// forgets the upstream populate doesn't silently lose secrets on// backend failure.- collectionsWithRefIds.forEach(populateLocalStoresFromCollectionTree)- return appendCollectionsToStore(- collectionsWithRefIds.map(stripCollectionTreeForStore),- reqType- )+ return appendImportedCollectionsLocally(collectionsWithRefIds, reqType)} catch {- collectionsWithRefIds.forEach(populateLocalStoresFromCollectionTree)- return appendCollectionsToStore(- collectionsWithRefIds.map(stripCollectionTreeForStore),+ return appendImportedCollectionsLocally(collectionsWithRefIds, reqType)+ }+}++/**+ * Local-only append used by the backend-failure fallback. The store+ * dispatch is suppressed via `runDispatchWithOutSyncing` so it does NOT+ * re-enter the unified `appendCollections` store-sync (which would fire a+ * second `importUserCollectionsFromJSON` for an import the backend already+ * rejected — see the double-trigger this guards against).+ */+function appendImportedCollectionsLocally(+ collections: HoppCollection[],+ reqType: ReqType+) {+ collections.forEach(populateLocalStoresFromCollectionTree)+ runDispatchWithOutSyncing(() =>+ appendCollectionsToStore(+ collections.map(stripCollectionTreeForStore),reqType)- }+ )+ return E.right({ success: true })}export const appendCollectionsToStore = (diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/index.ts b/packages/hoppscotch-common/src/lib/sync/collections/index.tssimilarity index 72%rename from packages/hoppscotch-selfhost-web/src/platform/collections/desktop/index.tsrename to packages/hoppscotch-common/src/lib/sync/collections/index.tsindex bd2452c61..9f2a6f32c 100644--- a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/index.ts+++ b/packages/hoppscotch-common/src/lib/sync/collections/index.ts@@ -1,6 +1,4 @@-import { CollectionsPlatformDef } from "@hoppscotch/common/platform/collections"-import { authEvents$, def as platformAuth } from "@app/platform/auth/desktop"-import { runDispatchWithOutSyncing } from "@app/lib/sync"+import { CollectionsPlatformDef } from "~/platform/collections"import {exportUserCollectionsToJSON,@@ -19,12 +17,23 @@ import {} from "./api"import { collectionsSyncer, getStoreByCollectionType } from "./sync"+import {+ generateUniqueRefId,+ GQLHeader,+ HoppCollection,+ HoppGQLRequest,+ HoppRESTHeaders,+ HoppRESTParam,+ HoppRESTRequest,+ makeCollection,+} from "@hoppscotch/data"+import * as E from "fp-ts/Either"+import { runGQLSubscription } from "~/helpers/backend/GQLClient"import {ReqType,UserCollectionDuplicatedData,UserRequest,-} from "@app/api/generated/graphql"-import { runGQLSubscription } from "@hoppscotch/common/helpers/backend/GQLClient"+} from "~/helpers/backend/graphql"import {addGraphqlCollection,addGraphqlFolder,@@ -36,6 +45,8 @@ import {editRESTCollection,editRESTFolder,editRESTRequest,+ graphqlCollectionStore,+ moveGraphqlFolder,moveGraphqlRequest,moveRESTFolder,moveRESTRequest,@@ -51,35 +62,27 @@ import {saveRESTRequestAs,setGraphqlCollections,setRESTCollections,+ sortGraphqlCollection,+ sortGraphqlFolder,sortRESTCollection,sortRESTFolder,+ updateGraphqlCollectionOrder,updateRESTCollectionOrder,updateRESTRequestOrder,-} from "@hoppscotch/common/newstore/collections"-import {- generateUniqueRefId,- GQLHeader,- HoppCollection,- HoppGQLRequest,- HoppRESTHeaders,- HoppRESTParam,- HoppRESTRequest,-} from "@hoppscotch/data"-import * as E from "fp-ts/Either"+} from "~/newstore/collections"+import { platform } from "~/platform"+import { runDispatchWithOutSyncing } from ".."import { gqlCollectionsSyncer } from "./gqlCollections.sync"+import { importToPersonalWorkspace } from "./import"function initCollectionsSync() {- const currentUser$ = platformAuth.getCurrentUserStream()+ const authEvents$ = platform.auth.getAuthEventsStream()+ const currentUser$ = platform.auth.getCurrentUserStream()collectionsSyncer.startStoreSync()collectionsSyncer.setupSubscriptions(setupSubscriptions)gqlCollectionsSyncer.startStoreSync()- // TODO: fix collection schema transformation on backend maybe?- loadUserCollections("REST")- loadUserCollections("GQL")-- // TODO: test & make sure the auth thing is working properlycurrentUser$.subscribe(async (user) => {if (user) {loadUserCollections("REST")@@ -136,19 +139,16 @@ export function exportedCollectionToHoppCollection(restCollection.data && restCollection.data !== "null"? JSON.parse(restCollection.data): {- auth: { authType: "inherit", authActive: false },+ auth: { authType: "inherit", authActive: true },headers: [],_ref_id: generateUniqueRefId("coll"),variables: [],description: null,- preRequestScript: "",- testScript: "",}- return {+ return makeCollection({id: restCollection.id,_ref_id: data._ref_id ?? generateUniqueRefId("coll"),- v: 12,name: restCollection.name,folders: restCollection.folders.map((folder) =>exportedCollectionToHoppCollection(folder, collectionType)@@ -198,66 +198,62 @@ export function exportedCollectionToHoppCollection(_ref_id: _ref_id ?? generateUniqueRefId("req"),}}),+ description: data.description ?? null,auth: data.auth,headers: addDescriptionField(data.headers),variables: data.variables ?? [],- description: data.description ?? null,preRequestScript: data.preRequestScript ?? "",testScript: data.testScript ?? "",- }- } else {- const gqlCollection = collection as ExportedUserCollectionGQL-- const data =- gqlCollection.data && gqlCollection.data !== "null"- ? JSON.parse(gqlCollection.data)- : {- auth: { authType: "inherit", authActive: true },- headers: [],- _ref_id: generateUniqueRefId("coll"),- variables: [],- description: null,- preRequestScript: "",- testScript: "",- }-- return {- id: gqlCollection.id,- _ref_id: data._ref_id ?? generateUniqueRefId("coll"),- v: 12,- name: gqlCollection.name,- folders: gqlCollection.folders.map((folder) =>- exportedCollectionToHoppCollection(folder, collectionType)- ),- requests: gqlCollection.requests.map((request) => {- const requestParsedResult = HoppGQLRequest.safeParse(request)- if (requestParsedResult.type === "ok") {- return requestParsedResult.value+ })+ }+ const gqlCollection = collection as ExportedUserCollectionGQL++ const data =+ gqlCollection.data && gqlCollection.data !== "null"+ ? JSON.parse(gqlCollection.data)+ : {+ auth: { authType: "inherit", authActive: true },+ headers: [],+ _ref_id: generateUniqueRefId("coll"),+ variables: [],+ description: null,}- const { v, auth, headers, name, id, query, url, variables } = request+ return makeCollection({+ id: gqlCollection.id,+ _ref_id: data._ref_id ?? generateUniqueRefId("coll"),+ name: gqlCollection.name,+ folders: gqlCollection.folders.map((folder) =>+ exportedCollectionToHoppCollection(folder, collectionType)+ ),+ requests: gqlCollection.requests.map((request) => {+ const requestParsedResult = HoppGQLRequest.safeParse(request)+ if (requestParsedResult.type === "ok") {+ return requestParsedResult.value+ }- const resolvedHeaders = addDescriptionField(headers)+ const { v, auth, headers, name, id, query, url, variables } = request- return {- id,- v,- auth,- headers: resolvedHeaders,- name,- query,- url,- variables,- }- }),- auth: data.auth,- headers: addDescriptionField(data.headers),- variables: data.variables ?? [],- description: data.description ?? null,- preRequestScript: data.preRequestScript ?? "",- testScript: data.testScript ?? "",- }- }+ const resolvedHeaders = addDescriptionField(headers)++ return {+ id,+ v,+ auth,+ headers: resolvedHeaders,+ name,+ query,+ url,+ variables,+ }+ }),+ auth: data.auth,+ headers: addDescriptionField(data.headers),+ variables: data.variables ?? [],+ description: data.description ?? null,+ preRequestScript: data.preRequestScript ?? "",+ testScript: data.testScript ?? "",+ })}async function loadUserCollections(collectionType: "REST" | "GQL") {@@ -407,38 +403,38 @@ function setupUserCollectionCreatedSubscription() {_ref_id: generateUniqueRefId("coll"),variables: [],description: null,- preRequestScript: "",- testScript: "",}runDispatchWithOutSyncing(() => {collectionType == "GQL"- ? addGraphqlCollection({- name: res.right.userCollectionCreated.title,- folders: [],- requests: [],- v: 12,- _ref_id: data._ref_id,- auth: data.auth,- headers: addDescriptionField(data.headers),- variables: data.variables ?? [],- description: data.description ?? null,- preRequestScript: data.preRequestScript ?? "",- testScript: data.testScript ?? "",- })- : addRESTCollection({- name: res.right.userCollectionCreated.title,- folders: [],- requests: [],- v: 12,- _ref_id: data._ref_id,- auth: data.auth,- headers: addDescriptionField(data.headers),- variables: data.variables ?? [],- description: data.description ?? null,- preRequestScript: data.preRequestScript ?? "",- testScript: data.testScript ?? "",- })+ ? addGraphqlCollection(+ makeCollection({+ name: res.right.userCollectionCreated.title,+ folders: [],+ requests: [],+ _ref_id: data._ref_id,+ auth: data.auth,+ headers: addDescriptionField(data.headers),+ variables: data.variables ?? [],+ description: data.description ?? null,+ preRequestScript: data.preRequestScript ?? "",+ testScript: data.testScript ?? "",+ })+ )+ : addRESTCollection(+ makeCollection({+ name: res.right.userCollectionCreated.title,+ folders: [],+ requests: [],+ _ref_id: data._ref_id,+ auth: data.auth,+ headers: addDescriptionField(data.headers),+ variables: data.variables ?? [],+ description: data.description ?? null,+ preRequestScript: data.preRequestScript ?? "",+ testScript: data.testScript ?? "",+ })+ )const localIndex = collectionStore.value.state.length - 1@@ -458,45 +454,71 @@ function setupUserCollectionUpdatedSubscription() {userCollectionUpdated$.subscribe((res) => {if (E.isRight(res)) {- const collectionType = res.right.userCollectionUpdated.type+ const {+ id: updatedCollectionBackendID,+ title,+ type: collectionType,+ data,+ } = res.right.userCollectionUpdatedconst { collectionStore } = getStoreByCollectionType(collectionType)- const updatedCollectionBackendID = res.right.userCollectionUpdated.idconst updatedCollectionLocalPath = getCollectionPathFromCollectionID(updatedCollectionBackendID,collectionStore.value.state)- const isFolder =- updatedCollectionLocalPath &&- updatedCollectionLocalPath.split("/").length > 1+ if (!updatedCollectionLocalPath) return- // updated collection is a folder- if (isFolder) {- runDispatchWithOutSyncing(() => {- collectionType == "REST"- ? editRESTFolder(updatedCollectionLocalPath, {- name: res.right.userCollectionUpdated.title,- })- : editGraphqlFolder(updatedCollectionLocalPath, {- name: res.right.userCollectionUpdated.title,- })- })+ const isFolder = updatedCollectionLocalPath.split("/").length > 1++ // Carry auth, headers, variables, and scripts from the data payload+ const {+ auth,+ headers,+ variables,+ description,+ preRequestScript,+ testScript,+ } =+ data && data != "null"+ ? JSON.parse(data)+ : {+ auth: { authType: "inherit", authActive: true },+ headers: [],+ variables: [],+ description: null,+ preRequestScript: "",+ testScript: "",+ }++ const partialUpdate: Partial<HoppCollection> = {+ name: title,+ auth,+ headers: addDescriptionField(headers),+ variables: variables ?? [],+ description: description ?? null,+ preRequestScript: preRequestScript ?? "",+ testScript: testScript ?? "",}- // updated collection is a root collection- if (updatedCollectionLocalPath && !isFolder) {- runDispatchWithOutSyncing(() => {+ runDispatchWithOutSyncing(() => {+ if (isFolder) {collectionType == "REST"- ? editRESTCollection(parseInt(updatedCollectionLocalPath), {- name: res.right.userCollectionUpdated.title,- })- : editGraphqlCollection(parseInt(updatedCollectionLocalPath), {- name: res.right.userCollectionUpdated.title,- })- })- }+ ? editRESTFolder(updatedCollectionLocalPath, partialUpdate)+ : editGraphqlFolder(updatedCollectionLocalPath, partialUpdate)+ } else {+ collectionType == "REST"+ ? editRESTCollection(+ parseInt(updatedCollectionLocalPath),+ partialUpdate+ )+ : editGraphqlCollection(+ parseInt(updatedCollectionLocalPath),+ partialUpdate+ )+ }+ })}})@@ -510,10 +532,13 @@ function setupUserCollectionMovedSubscription() {userCollectionMoved$.subscribe((res) => {if (E.isRight(res)) {const movedMetadata = res.right.userCollectionMoved+ const collectionType = movedMetadata.type++ const { collectionStore } = getStoreByCollectionType(collectionType)const sourcePath = getCollectionPathFromCollectionID(movedMetadata.id,- restCollectionStore.value.state+ collectionStore.value.state)let destinationPath: string | undefined@@ -522,13 +547,15 @@ function setupUserCollectionMovedSubscription() {destinationPath =getCollectionPathFromCollectionID(movedMetadata.parent?.id,- restCollectionStore.value.state+ collectionStore.value.state) ?? undefined}sourcePath &&runDispatchWithOutSyncing(() => {- moveRESTFolder(sourcePath, destinationPath ?? null)+ collectionType === "GQL"+ ? moveGraphqlFolder(sourcePath, destinationPath ?? null)+ : moveRESTFolder(sourcePath, destinationPath ?? null)})}})@@ -589,9 +616,16 @@ function setupUserCollectionOrderUpdatedSubscription() {const sourceCollectionID = userCollection.idconst destinationCollectionID = nextUserCollection?.id+ // The OrderUpdated payload does not include a `type` field, so+ // determine which store owns the source ID by lookup.+ const collectionType = locateCollectionType(sourceCollectionID)+ if (!collectionType) return++ const { collectionStore } = getStoreByCollectionType(collectionType)+const sourcePath = getCollectionPathFromCollectionID(sourceCollectionID,- restCollectionStore.value.state+ collectionStore.value.state)let destinationPath: string | null | undefined@@ -599,13 +633,15 @@ function setupUserCollectionOrderUpdatedSubscription() {if (destinationCollectionID) {destinationPath = getCollectionPathFromCollectionID(destinationCollectionID,- restCollectionStore.value.state+ collectionStore.value.state)}runDispatchWithOutSyncing(() => {if (sourcePath) {- updateRESTCollectionOrder(sourcePath, destinationPath ?? null)+ collectionType === "GQL"+ ? updateGraphqlCollectionOrder(sourcePath, destinationPath ?? null)+ : updateRESTCollectionOrder(sourcePath, destinationPath ?? null)}})}@@ -632,6 +668,13 @@ function setupUserCollectionDuplicatedSubscription() {const { collectionStore } = getStoreByCollectionType(collectionType)+ const duplicatedCollectionAlreadyApplied =+ getCollectionPathFromCollectionID(id, collectionStore.value.state)++ if (duplicatedCollectionAlreadyApplied) {+ return+ }+const parentCollectionPath =parentCollectionID &&getCollectionPathFromCollectionID(@@ -668,12 +711,11 @@ function setupUserCollectionDuplicatedSubscription() {)// New collection to be added to store with the transformed data- const effectiveDuplicatedCollection: HoppCollection = {+ const effectiveDuplicatedCollection: HoppCollection = makeCollection({id,name,folders,requests,- v: 12,_ref_id,auth,headers: addDescriptionField(headers),@@ -681,7 +723,7 @@ function setupUserCollectionDuplicatedSubscription() {description: description ?? null,preRequestScript: preRequestScript ?? "",testScript: testScript ?? "",- }+ })// only folders will have parent collection idif (parentCollectionID && parentCollectionPath) {@@ -704,37 +746,33 @@ function setupUserCollectionDuplicatedSubscription() {id?.endsWith(collectionCreatedFromStoreIDSuffix))- if (collectionInsertedViaStoreUpdateIdx === -1) {- return- }-- const collectionInsertedViaStoreUpdateIndexPath = `${parentCollectionPath}/${collectionInsertedViaStoreUpdateIdx}`-runDispatchWithOutSyncing(() => {- /**- * Step 1. Remove the collection inserted via store update with the ID suffix- * Step 2. Add the duplicated collection received from the GQL subscription- * Step 3. Update the duplicated collection with the relevant data- */-- if (collectionType === "GQL") {- removeGraphqlFolder(collectionInsertedViaStoreUpdateIndexPath)-- addGraphqlFolder(name, parentCollectionPath)-- editGraphqlFolder(- collectionInsertedViaStoreUpdateIndexPath,- effectiveDuplicatedCollection- )+ if (collectionInsertedViaStoreUpdateIdx === -1) {+ // Cross-device duplicate: no local placeholder to remove, just add it+ const newFolderPath = `${parentCollectionPath}/${parentCollection.folders.length}`++ if (collectionType === "GQL") {+ addGraphqlFolder(name, parentCollectionPath)+ editGraphqlFolder(newFolderPath, effectiveDuplicatedCollection)+ } else {+ addRESTFolder(name, parentCollectionPath)+ editRESTFolder(newFolderPath, effectiveDuplicatedCollection)+ }} else {- removeRESTFolder(collectionInsertedViaStoreUpdateIndexPath)-- addRESTFolder(name, parentCollectionPath)-- editRESTFolder(- collectionInsertedViaStoreUpdateIndexPath,- effectiveDuplicatedCollection- )+ const collectionInsertedViaStoreUpdateIndexPath = `${parentCollectionPath}/${collectionInsertedViaStoreUpdateIdx}`+ // After remove + append, the new folder sits at the last index;+ // editing the placeholder path now would hit a shifted sibling.+ const newFolderPath = `${parentCollectionPath}/${parentCollection.folders.length - 1}`++ if (collectionType === "GQL") {+ removeGraphqlFolder(collectionInsertedViaStoreUpdateIndexPath)+ addGraphqlFolder(name, parentCollectionPath)+ editGraphqlFolder(newFolderPath, effectiveDuplicatedCollection)+ } else {+ removeRESTFolder(collectionInsertedViaStoreUpdateIndexPath)+ addRESTFolder(name, parentCollectionPath)+ editRESTFolder(newFolderPath, effectiveDuplicatedCollection)+ }}})} else {@@ -747,23 +785,21 @@ function setupUserCollectionDuplicatedSubscription() {id?.endsWith(collectionCreatedFromStoreIDSuffix))- if (collectionInsertedViaStoreUpdateIdx === -1) {- return- }-runDispatchWithOutSyncing(() => {- /**- * Step 1. Remove the collection inserted via store update with the ID suffix- * Step 2. Add the duplicated collection received from the GQL subscription- */- if (collectionType === "GQL") {- removeGraphqlCollection(collectionInsertedViaStoreUpdateIdx)-- addGraphqlCollection(effectiveDuplicatedCollection)+ if (collectionInsertedViaStoreUpdateIdx === -1) {+ if (collectionType === "GQL") {+ addGraphqlCollection(effectiveDuplicatedCollection)+ } else {+ addRESTCollection(effectiveDuplicatedCollection)+ }} else {- removeRESTCollection(collectionInsertedViaStoreUpdateIdx)-- addRESTCollection(effectiveDuplicatedCollection)+ if (collectionType === "GQL") {+ removeGraphqlCollection(collectionInsertedViaStoreUpdateIdx)+ addGraphqlCollection(effectiveDuplicatedCollection)+ } else {+ removeRESTCollection(collectionInsertedViaStoreUpdateIdx)+ addRESTCollection(effectiveDuplicatedCollection)+ }}})}@@ -785,7 +821,23 @@ const setupUserRootCollectionsSortedSubscription = () => {const sortOrder = sortOption === "TITLE_ASC" ? "asc" : "desc"- sortRESTCollection(null, sortOrder)+ // TODO: UserCollectionSortData does not carry a REST/GQL type+ // discriminator, so we can't route a root-level sort event to the+ // correct store. Apply to whichever store is non-empty; if both+ // are populated this will be ambiguous — needs a backend schema+ // change to add `type` to UserCollectionSortData.+ const restHasState = restCollectionStore.value.state.length > 0+ const gqlHasState = graphqlCollectionStore.value.state.length > 0++ if (restHasState && !gqlHasState) {+ sortRESTCollection(null, sortOrder)+ } else if (gqlHasState && !restHasState) {+ sortGraphqlCollection(null, sortOrder)+ } else {+ // Ambiguous (both or neither store has state): skip until backend+ // includes a type discriminator in UserCollectionSortData.+ return+ }}})}@@ -808,14 +860,23 @@ const setupUserChildCollectionSortedSubscription = () => {const sortOrder = sortOption === "TITLE_ASC" ? "asc" : "desc"+ // ChildCollectionSorted payload does not include a `type` field,+ // so resolve store membership from the parent ID.+ const collectionType = locateCollectionType(parentCollectionID)+ if (!collectionType) return++ const { collectionStore } = getStoreByCollectionType(collectionType)+const sourcePath = getCollectionPathFromCollectionID(parentCollectionID,- restCollectionStore.value.state+ collectionStore.value.state)if (!sourcePath) return- sortRESTFolder(sourcePath, sortOrder)+ collectionType === "GQL"+ ? sortGraphqlFolder(sourcePath, sortOrder)+ : sortRESTFolder(sourcePath, sortOrder)}})}@@ -957,7 +1018,6 @@ function setupUserRequestMovedSubscription() {// there is no nextRequest, so request is movedif (- (destinationRequestIndex || destinationRequestIndex == 0) &&destinationCollectionPath &&sourceRequestPath &&!nextRequest@@ -979,7 +1039,8 @@ function setupUserRequestMovedSubscription() {// there is nextRequest, so request is reorderedif (- (destinationRequestIndex || destinationRequestIndex == 0) &&+ destinationRequestIndex != null &&+ destinationRequestIndex >= 0 &&destinationCollectionPath &&nextRequest &&// we don't have request reordering for graphql yet@@ -1002,7 +1063,8 @@ function setupUserRequestMovedSubscription() {): undefined- nextRequestIndex &&+ nextRequestIndex !== undefined &&+ nextRequestIndex !== -1 &&nextCollectionPath &&sourceRequestPath &&runDispatchWithOutSyncing(() => {@@ -1054,8 +1116,6 @@ function setupUserRequestDeletedSubscription() {return userRequestDeletedSub}-import { importToPersonalWorkspace } from "./import"-export const def: CollectionsPlatformDef = {initCollectionsSync,loadUserCollections,@@ -1072,15 +1132,14 @@ function getCollectionPathFromCollectionID(return parentPath? `${parentPath}/${collectionIndex}`: `${collectionIndex}`- } else {- const collectionPath = getCollectionPathFromCollectionID(- collectionID,- collections[collectionIndex].folders,- parentPath ? `${parentPath}/${collectionIndex}` : `${collectionIndex}`- )-- if (collectionPath) return collectionPath}+ const collectionPath = getCollectionPathFromCollectionID(+ collectionID,+ collections[collectionIndex].folders,+ parentPath ? `${parentPath}/${collectionIndex}` : `${collectionIndex}`+ )++ if (collectionPath) return collectionPath}return null@@ -1103,20 +1162,42 @@ function getRequestPathFromRequestID(: `${collectionIndex}`,requestIndex,}- } else {- const requestPath = getRequestPathFromRequestID(- requestID,- collections[collectionIndex].folders,- parentPath ? `${parentPath}/${collectionIndex}` : `${collectionIndex}`- )-- if (requestPath) return requestPath}+ const requestPath = getRequestPathFromRequestID(+ requestID,+ collections[collectionIndex].folders,+ parentPath ? `${parentPath}/${collectionIndex}` : `${collectionIndex}`+ )++ if (requestPath) return requestPath}return null}+// Resolves whether a collection ID belongs to the REST or GQL store. Returns+// null if neither store contains it (e.g. event for a workspace not loaded+// yet). Used to disambiguate subscription payloads that don't carry a `type`.+function locateCollectionType(collectionID: string): "REST" | "GQL" | null {+ if (+ getCollectionPathFromCollectionID(+ collectionID,+ restCollectionStore.value.state+ )+ ) {+ return "REST"+ }+ if (+ getCollectionPathFromCollectionID(+ collectionID,+ graphqlCollectionStore.value.state+ )+ ) {+ return "GQL"+ }+ return null+}+function getRequestIndex(requestID: string,parentCollectionPath: string,@@ -1173,20 +1254,19 @@ function transformDuplicatedCollections(const requests = transformDuplicatedCollectionRequests(userRequests)- return {+ return makeCollection({id,name,folders,requests,_ref_id,- v: 12,auth,headers: addDescriptionField(headers),variables: variables ?? [],description: description ?? null,preRequestScript: preRequestScript ?? "",testScript: testScript ?? "",- }+ })})}diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/web/sync.ts b/packages/hoppscotch-common/src/lib/sync/collections/sync.tssimilarity index 73%rename from packages/hoppscotch-selfhost-web/src/platform/collections/web/sync.tsrename to packages/hoppscotch-common/src/lib/sync/collections/sync.tsindex 303bf10d2..fb40ea581 100644--- a/packages/hoppscotch-selfhost-web/src/platform/collections/web/sync.ts+++ b/packages/hoppscotch-common/src/lib/sync/collections/sync.ts@@ -1,24 +1,10 @@-import {- graphqlCollectionStore,- navigateToFolderWithIndexPath,- removeDuplicateRESTCollectionOrFolder,- restCollectionStore,-} from "@hoppscotch/common/newstore/collections"-import {- getSettingSubject,- settingsStore,-} from "@hoppscotch/common/newstore/settings"-import {generateUniqueRefId,HoppCollection,HoppRESTRequest,+ makeCollection,} from "@hoppscotch/data"-import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"--import { getSyncInitFunction, StoreSyncDefinitionOf } from "@app/lib/sync"-import { createMapper } from "@app/lib/sync/mapper"import {createRESTChildUserCollection,createRESTRootUserCollection,@@ -36,7 +22,25 @@ import {} from "./api"import * as E from "fp-ts/Either"-import { ReqType, SortOptions } from "@app/api/generated/graphql"+import { ReqType, SortOptions } from "~/helpers/backend/graphql"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"+import {+ editGraphqlCollection,+ editGraphqlFolder,+ editRESTCollection,+ editRESTFolder,+ graphqlCollectionStore,+ navigateToFolderWithIndexPath,+ removeDuplicateRESTCollectionOrFolder,+ restCollectionStore,+} from "~/newstore/collections"+import { getSettingSubject, settingsStore } from "~/newstore/settings"+import {+ getSyncInitFunction,+ runDispatchWithOutSyncing,+ StoreSyncDefinitionOf,+} from ".."+import { createMapper } from "../mapper"// restCollectionsMapper uses the collectionPath as the local identifier// Helper function to transform HoppCollection to backend format@@ -50,8 +54,6 @@ const transformCollectionForBackend = (collection: HoppCollection): any => {variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",}return {@@ -67,6 +69,202 @@ export const restCollectionsMapper = createMapper<string, string>()// restRequestsMapper uses the collectionPath/requestIndex as the local identifierexport const restRequestsMapper = createMapper<string, string>()+type ExportedCollectionFolder = {+ id?: string+ folders: ExportedCollectionFolder[]+ requests: Array<Record<string, unknown> & { id: string }>+ name: string+ data?: string+}++const addDescriptionField = (candidate: Array<Record<string, unknown>>) =>+ candidate.map((item) => ({+ ...item,+ description: "description" in item ? item.description : "",+ }))++const exportedCollectionToHoppCollection = (+ collection: ExportedCollectionFolder+): HoppCollection => {+ const data =+ collection.data && collection.data !== "null"+ ? JSON.parse(collection.data)+ : {+ auth: { authType: "inherit", authActive: true },+ headers: [],+ _ref_id: generateUniqueRefId("coll"),+ variables: [],+ description: null,+ }++ return makeCollection({+ id: collection.id,+ _ref_id: data._ref_id ?? generateUniqueRefId("coll"),+ name: collection.name,+ folders: collection.folders.map((folder) =>+ exportedCollectionToHoppCollection(folder)+ ),+ requests: collection.requests.map((request) => ({ ...request })),+ auth: data.auth,+ headers: addDescriptionField(data.headers),+ variables: data.variables ?? [],+ description: data.description ?? null,+ preRequestScript: data.preRequestScript ?? "",+ testScript: data.testScript ?? "",+ })+}++function findCollectionPathByID(+ collections: HoppCollection[],+ collectionID: string,+ currentPath: number[] = []+): number[] | undefined {+ for (const [index, collection] of collections.entries()) {+ const nextPath = [...currentPath, index]++ if (collection.id === collectionID) {+ return nextPath+ }++ const childPath = findCollectionPathByID(+ collection.folders ?? [],+ collectionID,+ nextPath+ )++ if (childPath) {+ return childPath+ }+ }++ return undefined+}++// Suffix stamped onto the optimistically-inserted duplicate in the+// `duplicateCollection` store dispatcher. Used here to locate that placeholder+// so it can be swapped for the backend response carrying the real IDs.+const DUPLICATE_COLLECTION_ID_SUFFIX = "-duplicate-collection"++// Find the index of the optimistically-inserted duplicate (its ID ends with+// DUPLICATE_COLLECTION_ID_SUFFIX) within a sibling list. The original is+// duplicated into its own parent, so the placeholder always sits alongside it.+function findDuplicatePlaceholderIndex(collections: HoppCollection[]): number {+ return collections.findIndex((collection) =>+ collection.id?.endsWith(DUPLICATE_COLLECTION_ID_SUFFIX)+ )+}++// Graft the backend-assigned IDs from the duplicate's exported representation+// onto the optimistically-inserted collection, matching folders/requests by+// position. Everything else the frontend already set (name, `_ref_id`, auth,+// headers, variables, scripts, etc.) is preserved — only the IDs change, so the+// placeholder `-duplicate-collection` IDs are replaced with the real ones the+// backend just created.+function applyExportedIdsToCollection(+ target: HoppCollection,+ exported: ExportedCollectionFolder+): HoppCollection {+ return {+ ...target,+ ...(exported.id ? { id: exported.id } : {}),+ folders: (target.folders ?? []).map((folder, index) => {+ const exportedFolder = exported.folders?.[index]+ return exportedFolder+ ? applyExportedIdsToCollection(folder, exportedFolder)+ : folder+ }),+ requests: (target.requests ?? []).map((request, index) => {+ const exportedRequest = exported.requests?.[index]+ return exportedRequest?.id+ ? { ...request, id: exportedRequest.id }+ : request+ }),+ }+}++export function applyDuplicatedCollectionResult(+ collectionType: "REST" | "GQL",+ originalCollectionID: string,+ exportedCollectionJSON: string+) {+ const parsed = JSON.parse(exportedCollectionJSON) as+ | ExportedCollectionFolder+ | ExportedCollectionFolder[]++ // The backend may return either the duplicated collection directly or wrapped+ // in an array — normalize to the single duplicated collection.+ const duplicatedCollection = Array.isArray(parsed) ? parsed[0] : parsed+ if (!duplicatedCollection) return++ const { collectionStore } = getStoreByCollectionType(collectionType)+ const originalCollectionPath = findCollectionPathByID(+ collectionStore.value.state,+ originalCollectionID+ )++ if (!originalCollectionPath) return++ const parentCollectionPath = originalCollectionPath.slice(0, -1)++ runDispatchWithOutSyncing(() => {+ if (parentCollectionPath.length === 0) {+ // Locate the placeholder by its suffixed ID rather than assuming it's the+ // last root collection — otherwise a stale ID survives and subsequent+ // edits hit the backend with the bogus `-duplicate-collection` ID.+ const duplicateCollectionIndex = findDuplicatePlaceholderIndex(+ collectionStore.value.state+ )++ if (duplicateCollectionIndex === -1) return++ const placeholderCollection =+ collectionStore.value.state[duplicateCollectionIndex]++ const updatedCollection = applyExportedIdsToCollection(+ placeholderCollection,+ duplicatedCollection+ )++ if (collectionType === "REST") {+ editRESTCollection(duplicateCollectionIndex, updatedCollection)+ } else {+ editGraphqlCollection(duplicateCollectionIndex, updatedCollection)+ }++ return+ }++ const parentCollection = navigateToFolderWithIndexPath(+ collectionStore.value.state,+ parentCollectionPath+ )++ if (!parentCollection) return++ const duplicateCollectionIndex = findDuplicatePlaceholderIndex(+ parentCollection.folders+ )++ if (duplicateCollectionIndex === -1) return++ const placeholderCollection =+ parentCollection.folders[duplicateCollectionIndex]++ const updatedCollection = applyExportedIdsToCollection(+ placeholderCollection,+ duplicatedCollection+ )++ const duplicateCollectionPath = `${parentCollectionPath.join("/")}/${duplicateCollectionIndex}`++ if (collectionType === "REST") {+ editRESTFolder(duplicateCollectionPath, updatedCollection)+ } else {+ editGraphqlFolder(duplicateCollectionPath, updatedCollection)+ }+ })+}+// Optimized implementation using importUserCollectionsFromJSON for bulk operations// This replaces individual createRESTRootUserCollection/createRESTChildUserCollection/createRESTUserRequest callsconst recursivelySyncCollections = async (@@ -87,8 +285,6 @@ const recursivelySyncCollections = async (variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",}const res = await createRESTRootUserCollection(collection.name,@@ -108,8 +304,6 @@ const recursivelySyncCollections = async (variables: [],_ref_id: generateUniqueRefId("coll"),description: null,- preRequestScript: "",- testScript: "",}collection.id = parentCollectionID@@ -118,8 +312,6 @@ const recursivelySyncCollections = async (collection.headers = returnedData.headerscollection.variables = returnedData.variablescollection.description = returnedData.description ?? null- collection.preRequestScript = returnedData.preRequestScript ?? ""- collection.testScript = returnedData.testScript ?? ""removeDuplicateRESTCollectionOrFolder(parentCollectionID,`${collectionPath}`@@ -138,8 +330,6 @@ const recursivelySyncCollections = async (variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",}const res = await createRESTChildUserCollection(@@ -162,8 +352,6 @@ const recursivelySyncCollections = async (variables: [],_ref_id: generateUniqueRefId("coll"),description: null,- preRequestScript: "",- testScript: "",}collection.id = childCollectionId@@ -173,8 +361,6 @@ const recursivelySyncCollections = async (parentCollectionID = childCollectionIdcollection.variables = returnedData.variablescollection.description = returnedData.description ?? null- collection.preRequestScript = returnedData.preRequestScript ?? ""- collection.testScript = returnedData.testScript ?? ""removeDuplicateRESTCollectionOrFolder(childCollectionId,@@ -185,7 +371,7 @@ const recursivelySyncCollections = async (// create the requestsif (parentCollectionID) {- collection.requests.forEach(async (request) => {+ for (const request of collection.requests) {const res = await createRESTUserRequest(request.name,JSON.stringify(request),@@ -197,18 +383,19 @@ const recursivelySyncCollections = async (request.id = requestId}- })+ }}// create the folders aka child collections- if (parentCollectionID)- collection.folders.forEach(async (folder, index) => {- recursivelySyncCollections(+ if (parentCollectionID) {+ for (const [index, folder] of collection.folders.entries()) {+ await recursivelySyncCollections(folder,`${collectionPath}/${index}`,parentCollectionID)- })+ }+ }}// TODO: generalize this@@ -257,10 +444,10 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<// Fallback to individual calls if bulk import failslet indexStart = restCollectionStore.value.state.length - entries.length- entries.forEach((collection) => {- recursivelySyncCollections(collection, `${indexStart}`)+ for (const collection of entries) {+ await recursivelySyncCollections(collection, `${indexStart}`)indexStart++- })+ }}},async addCollection({ collection }) {@@ -268,7 +455,10 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const lastCreatedCollectionIndex =restCollectionStore.value.state.length - 1- recursivelySyncCollections(collection, `${lastCreatedCollectionIndex}`)+ await recursivelySyncCollections(+ collection,+ `${lastCreatedCollectionIndex}`+ )},async removeCollection({ collectionID }) {if (collectionID) {@@ -284,11 +474,9 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const data = {auth: collection.auth,headers: collection.headers,- variables: stripSecretVariableValuesForWire(collection.variables ?? []),+ variables: stripSecretVariableValuesForWire(collection.variables),_ref_id: collection._ref_id,description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",}if (collectionID) {@@ -370,11 +558,9 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const data = {auth: folder.auth,headers: folder.headers,- variables: stripSecretVariableValuesForWire(folder.variables ?? []),+ variables: stripSecretVariableValuesForWire(folder.variables),_ref_id: folder._ref_id,description: folder.description,- preRequestScript: folder.preRequestScript ?? "",- testScript: folder.testScript ?? "",}if (folderID) {updateUserCollection(folderID, folderName, JSON.stringify(data))@@ -412,7 +598,15 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<},async duplicateCollection({ collectionSyncID }) {if (collectionSyncID) {- await duplicateUserCollection(collectionSyncID, ReqType.Rest)+ const res = await duplicateUserCollection(collectionSyncID, ReqType.Rest)++ if (E.isRight(res)) {+ applyDuplicatedCollectionResult(+ "REST",+ collectionSyncID,+ res.right.duplicateUserCollection.exportedCollection+ )+ }}},editRequest({ path, requestIndex, requestNew }) {@@ -593,7 +787,7 @@ export async function moveOrReorderRequests(let nextRequestBackendID: string | undefined// we only need this for reordering requests, not for moving requests- if (nextRequestIndex) {+ if (nextRequestIndex !== undefined) {// reorderingconst [newRequestIndex, newDestinationIndex] = getIndexesAfterReorder(requestIndex,diff --git a/packages/hoppscotch-common/src/lib/sync/defs.ts b/packages/hoppscotch-common/src/lib/sync/defs.tsnew file mode 100644index 000000000..167910d0f--- /dev/null+++ b/packages/hoppscotch-common/src/lib/sync/defs.ts@@ -0,0 +1,17 @@+import { def as collections } from "./collections"+import { def as environments } from "./environments"+import { def as history } from "./history"+import { def as settings } from "./settings"++/**+ * Centralized sync handles. The dispatcher/subscriber wiring lives in+ * `lib/sync/{collections,environments,history,settings}` and talks to the+ * Postgres backend directly — every shell (web, desktop, selfhost) shares the+ * same code path, so there's no per-platform forking here.+ */+export const sync = {+ collections,+ environments,+ history,+ settings,+}diff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/web/api.ts b/packages/hoppscotch-common/src/lib/sync/environments/api.tssimilarity index 96%rename from packages/hoppscotch-selfhost-web/src/platform/environments/web/api.tsrename to packages/hoppscotch-common/src/lib/sync/environments/api.tsindex 31ddd9921..db3eb8411 100644--- a/packages/hoppscotch-selfhost-web/src/platform/environments/web/api.ts+++ b/packages/hoppscotch-common/src/lib/sync/environments/api.ts@@ -2,7 +2,7 @@ import {runMutation,runGQLQuery,runGQLSubscription,-} from "@helpers/backend/GQLClient"+} from "~/helpers/backend/GQLClient"import {CreateUserEnvironmentDocument,@@ -27,7 +27,7 @@ import {UserEnvironmentCreatedDocument,UserEnvironmentUpdatedDocument,UserEnvironmentDeletedDocument,-} from "@app/api/generated/graphql"+} from "~/helpers/backend/graphql"export const createUserEnvironment = (name: string, variables: string) =>runMutation<@@ -87,7 +87,7 @@ export const getGlobalEnvironments = () =>runGQLQuery<GetGlobalEnvironmentsQuery,GetGlobalEnvironmentsQueryVariables,- "user_environment/user_env_does_not_exists"+ "user_environment/global_env_does_not_exist">({query: GetGlobalEnvironmentsDocument,variables: {},diff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/web/index.ts b/packages/hoppscotch-common/src/lib/sync/environments/index.tssimilarity index 88%rename from packages/hoppscotch-selfhost-web/src/platform/environments/web/index.tsrename to packages/hoppscotch-common/src/lib/sync/environments/index.tsindex 96aee23c2..9583ef17a 100644--- a/packages/hoppscotch-selfhost-web/src/platform/environments/web/index.ts+++ b/packages/hoppscotch-common/src/lib/sync/environments/index.ts@@ -10,20 +10,21 @@ import {setGlobalEnvID,setGlobalEnvVariables,updateEnvironment,-} from "@hoppscotch/common/newstore/environments"-import { authEvents$, def as platformAuth } from "@app/platform/auth/web"+} from "~/newstore/environments"-import { runGQLSubscription } from "@hoppscotch/common/helpers/backend/GQLClient"-import { EnvironmentsPlatformDef } from "@hoppscotch/common/src/platform/environments"+import { runGQLSubscription } from "~/helpers/backend/GQLClient"+import { EnvironmentsPlatformDef } from "~/platform/environments"-import { environnmentsSyncer } from "@app/platform/environments/web/sync"+import { environnmentsSyncer } from "./sync"import {Environment,EnvironmentSchemaVersion,GlobalEnvironment,+ GlobalEnvironmentSchemaVersion,} from "@hoppscotch/data"-import { runDispatchWithOutSyncing } from "@app/lib/sync"+import { platform } from "~/platform"+import { runDispatchWithOutSyncing } from ".."import {createUserGlobalEnvironment,getGlobalEnvironments,@@ -33,8 +34,9 @@ import {runUserEnvironmentUpdatedSubscription,} from "./api"-export function initEnvironmentsSync() {- const currentUser$ = platformAuth.getCurrentUserStream()+function initEnvironmentsSync() {+ const authEvents$ = platform.auth.getAuthEventsStream()+ const currentUser$ = platform.auth.getCurrentUserStream()environnmentsSyncer.startStoreSync()environnmentsSyncer.setupSubscriptions(setupSubscriptions)@@ -126,19 +128,21 @@ async function loadGlobalEnvironments() {if (!result.success && Array.isArray(parsed)) {result = entityReference(GlobalEnvironment).safeParse({- v: 2,+ v: GlobalEnvironmentSchemaVersion,variables: parsed,})}runDispatchWithOutSyncing(() => {setGlobalEnvVariables(- result.success ? result.data : { v: 2, variables: [] }+ result.success+ ? result.data+ : { v: GlobalEnvironmentSchemaVersion, variables: [] })setGlobalEnvID(globalEnv.id)})}- } else if (res.left.error == "user_environment/user_env_does_not_exists") {+ } else if (res.left.error == "user_environment/global_env_does_not_exist") {const res = await createUserGlobalEnvironment(JSON.stringify([]))if (E.isRight(res)) {@@ -195,7 +199,7 @@ function setupUserEnvironmentUpdatedSubscription() {let result = entityReference(GlobalEnvironment).safeParse(parsed)if (!result.success && Array.isArray(parsed)) {result = entityReference(GlobalEnvironment).safeParse({- v: 2,+ v: GlobalEnvironmentSchemaVersion,variables: parsed,})}@@ -211,7 +215,7 @@ function setupUserEnvironmentUpdatedSubscription() {(env) => env.id == id)- if ((localIndex || localIndex == 0) && name) {+ if (localIndex !== -1 && name) {const environment = {id,name,@@ -250,7 +254,7 @@ function setupUserEnvironmentDeletedSubscription() {// TODO: move getLocalIndexByID to a getter in the environmentsStoreconst localIndex = getLocalIndexByEnvironmentID(id)- if (localIndex || localIndex === 0) {+ if (localIndex !== null) {runDispatchWithOutSyncing(() => {deleteEnvironment(localIndex)})diff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/sync.ts b/packages/hoppscotch-common/src/lib/sync/environments/sync.tssimilarity index 84%rename from packages/hoppscotch-selfhost-web/src/platform/environments/desktop/sync.tsrename to packages/hoppscotch-common/src/lib/sync/environments/sync.tsindex b28d65887..6e7af09f0 100644--- a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/sync.ts+++ b/packages/hoppscotch-common/src/lib/sync/environments/sync.ts@@ -2,28 +2,25 @@ import {environmentsStore,getGlobalVariableID,removeDuplicateEntry,-} from "@hoppscotch/common/newstore/environments"-import {- getSettingSubject,- settingsStore,-} from "@hoppscotch/common/newstore/settings"--import { getSyncInitFunction, type StoreSyncDefinitionOf } from "@app/lib/sync"+} from "~/newstore/environments"+import { getSettingSubject, settingsStore } from "~/newstore/settings"import * as E from "fp-ts/Either"-import { createMapper } from "@app/lib/sync/mapper"-+import { Environment } from "@hoppscotch/data"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"+import { getService } from "~/modules/dioc"+import { CurrentValueService } from "~/services/current-environment-value.service"+import { SecretEnvironmentService } from "~/services/secret-environment.service"+import { getSyncInitFunction, StoreSyncDefinitionOf } from ".."+import { createMapper } from "../mapper"+import { platform } from "~/platform"import {clearGlobalEnvironmentVariables,createUserEnvironment,deleteUserEnvironment,updateUserEnvironment,} from "./api"-import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"-import { SecretEnvironmentService } from "@hoppscotch/common/services/secret-environment.service"-import { getService } from "@hoppscotch/common/modules/dioc"-import { CurrentValueService } from "@hoppscotch/common/services/current-environment-value.service"export const environmentsMapper = createMapper<number, string>()export const globalEnvironmentMapper = createMapper<number, string>()@@ -74,7 +71,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<let appendStart =environmentsStore.value.environments.length - appendListLength - 1- envs.forEach((env) => {+ envs.forEach((env: Environment) => {const envId = ++appendStart;(async function () {@@ -190,14 +187,22 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<)return}- updateUserEnvironment(- backendId,- "",- JSON.stringify({- v: 2,- variables: stripSecretVariableValuesForWire(variables),- })- )()+ const payload = JSON.stringify({+ v: 2,+ variables: stripSecretVariableValuesForWire(variables),+ })+ // Feature-detect a platform-provided global-env updater. Newer+ // backends (cloud) split the global update into a dedicated+ // mutation and reject `updateUserEnvironment` for global ids with+ // `user_environment/env_does_not_exist`; older / selfhost backends+ // still accept the unified mutation with an empty `name`.+ const platformUpdate =+ platform.sync?.environment?.updateUserGlobalEnvironment+ if (platformUpdate) {+ platformUpdate(backendId, payload)+ } else {+ updateUserEnvironment(backendId, "", payload)()+ }}},clearGlobalVariables() {diff --git a/packages/hoppscotch-selfhost-web/src/platform/history/web/api.ts b/packages/hoppscotch-common/src/lib/sync/history/api.tssimilarity index 81%rename from packages/hoppscotch-selfhost-web/src/platform/history/web/api.tsrename to packages/hoppscotch-common/src/lib/sync/history/api.tsindex 9e49017a6..6399bb1c0 100644--- a/packages/hoppscotch-selfhost-web/src/platform/history/web/api.ts+++ b/packages/hoppscotch-common/src/lib/sync/history/api.ts@@ -2,7 +2,7 @@ import {runMutation,runGQLQuery,runGQLSubscription,-} from "@helpers/backend/GQLClient"+} from "~/helpers/backend/GQLClient"import {CreateUserHistoryDocument,@@ -25,12 +25,8 @@ import {UserHistoryDeletedDocument,UserHistoryDeletedManyDocument,UserHistoryUpdatedDocument,- IsUserHistoryEnabledQuery,- IsUserHistoryEnabledQueryVariables,- IsUserHistoryEnabledDocument,- UserHistoryStoreStatusChangedDocument,UserHistoryAllDeletedDocument,-} from "@app/api/generated/graphql"+} from "~/helpers/backend/graphql"export const getUserHistoryEntries = () =>runGQLQuery<GetRestUserHistoryQuery, GetRestUserHistoryQueryVariables, "">({@@ -38,16 +34,6 @@ export const getUserHistoryEntries = () =>variables: {},})-export const getUserHistoryStore = () =>- runGQLQuery<- IsUserHistoryEnabledQuery,- IsUserHistoryEnabledQueryVariables,- ""- >({- query: IsUserHistoryEnabledDocument,- variables: {},- })-export const createUserHistory = (reqData: string,resMetadata: string,@@ -114,12 +100,6 @@ export const runUserHistoryDeletedManySubscription = () =>variables: {},})-export const runUserHistoryStoreStatusChangedSubscription = () =>- runGQLSubscription({- query: UserHistoryStoreStatusChangedDocument,- variables: {},- })-export const runUserHistoryAllDeletedSubscription = () =>runGQLSubscription({query: UserHistoryAllDeletedDocument,diff --git a/packages/hoppscotch-selfhost-web/src/platform/history/desktop/index.ts b/packages/hoppscotch-common/src/lib/sync/history/index.tssimilarity index 86%rename from packages/hoppscotch-selfhost-web/src/platform/history/desktop/index.tsrename to packages/hoppscotch-common/src/lib/sync/history/index.tsindex dccf9e936..c33531951 100644--- a/packages/hoppscotch-selfhost-web/src/platform/history/desktop/index.ts+++ b/packages/hoppscotch-common/src/lib/sync/history/index.ts@@ -1,4 +1,3 @@-import { authEvents$, def as platformAuth } from "@app/platform/auth/desktop"import {restHistoryStore,RESTHistoryEntry,@@ -15,38 +14,34 @@ import {deleteGraphqlHistoryEntry,clearGraphqlHistory,decodeGQLHistoryResponse,-} from "@hoppscotch/common/newstore/history"+} from "~/newstore/history"import { translateToNewRequest, translateToGQLRequest } from "@hoppscotch/data"-import { HistoryPlatformDef } from "@hoppscotch/common/platform/history"+import { HistoryPlatformDef } from "~/platform/history"import {getUserHistoryEntries,- getUserHistoryStore,runUserHistoryAllDeletedSubscription,runUserHistoryCreatedSubscription,runUserHistoryDeletedManySubscription,runUserHistoryDeletedSubscription,- runUserHistoryStoreStatusChangedSubscription,runUserHistoryUpdatedSubscription,} from "./api"import * as E from "fp-ts/Either"import { restHistorySyncer, gqlHistorySyncer } from "./sync"-import { runGQLSubscription } from "@hoppscotch/common/helpers/backend/GQLClient"-import { runDispatchWithOutSyncing } from "@app/lib/sync"-import { ReqType, ServiceStatus } from "@app/api/generated/graphql"+import { runDispatchWithOutSyncing } from ".."+import { ReqType } from "~/helpers/backend/graphql"import { ref } from "vue"+import { platform } from "~/platform"function initHistorySync() {- const currentUser$ = platformAuth.getCurrentUserStream()+ const authEvents$ = platform.auth.getAuthEventsStream()+ const currentUser$ = platform.auth.getCurrentUserStream()restHistorySyncer.startStoreSync()restHistorySyncer.setupSubscriptions(setupSubscriptions)gqlHistorySyncer.startStoreSync()- getUserHistoryStatus()- loadHistoryEntries()-currentUser$.subscribe(async (user) => {getUserHistoryStatus()@@ -67,7 +62,7 @@ function initHistorySync() {}function setupSubscriptions() {- let subs: ReturnType<typeof runGQLSubscription>[1][] = []+ let subs: { unsubscribe: () => void }[] = []const userHistoryCreatedSub = setupUserHistoryCreatedSubscription()const userHistoryUpdatedSub = setupUserHistoryUpdatedSubscription()@@ -124,27 +119,30 @@ async function loadHistoryEntries() {}async function getUserHistoryStatus() {- const currentUser = platformAuth.getCurrentUser()+ const currentUser = platform.auth.getCurrentUser()if (!currentUser) {isHistoryStoreEnabled.value = truereturn}- isFetchingHistoryStoreStatus.value = true+ // The history-enabled toggle is a self-host infra-config concept. Backends+ // without it (e.g. cloud) omit this hook and history is always enabled.+ const getHistoryStoreStatus = platform.sync?.history?.getHistoryStoreStatus+ if (!getHistoryStoreStatus) {+ isHistoryStoreEnabled.value = true+ return+ }- const res = await getUserHistoryStore()+ isFetchingHistoryStoreStatus.value = true- if (E.isLeft(res)) {+ try {+ isHistoryStoreEnabled.value = await getHistoryStoreStatus()+ } catch {hasErrorFetchingHistoryStoreStatus.value = true+ } finally {isFetchingHistoryStoreStatus.value = false- return}-- isHistoryStoreEnabled.value =- res.right.isUserHistoryEnabled.value === ServiceStatus.Enable-- isFetchingHistoryStoreStatus.value = false}function setupUserHistoryCreatedSubscription() {@@ -281,19 +279,18 @@ function setupUserHistoryDeletedManySubscription() {}function setupUserHistoryStoreStatusChangedSubscription() {- const [userHistoryStoreStatusChanged$, userHistoryStoreStatusChangedSub] =- runUserHistoryStoreStatusChangedSubscription()+ // Only self-host exposes the infra-config toggle this subscription tracks;+ // backends without it (e.g. cloud) skip listening entirely.+ const subscribeToHistoryStoreStatus =+ platform.sync?.history?.subscribeToHistoryStoreStatus- userHistoryStoreStatusChanged$.subscribe((res) => {- if (E.isRight(res)) {- const status =- res.right.infraConfigUpdate == ServiceStatus.Enable ? true : false+ if (!subscribeToHistoryStoreStatus) {+ return { unsubscribe: () => {} }+ }- isHistoryStoreEnabled.value = status- }+ return subscribeToHistoryStoreStatus((enabled) => {+ isHistoryStoreEnabled.value = enabled})-- return userHistoryStoreStatusChangedSub}function setupUserHistoryAllDeletedSubscription() {diff --git a/packages/hoppscotch-selfhost-web/src/platform/history/web/sync.ts b/packages/hoppscotch-common/src/lib/sync/history/sync.tssimilarity index 91%rename from packages/hoppscotch-selfhost-web/src/platform/history/web/sync.tsrename to packages/hoppscotch-common/src/lib/sync/history/sync.tsindex e4b8c3190..aa9fa36f8 100644--- a/packages/hoppscotch-selfhost-web/src/platform/history/web/sync.ts+++ b/packages/hoppscotch-common/src/lib/sync/history/sync.ts@@ -3,13 +3,10 @@ import {removeDuplicateRestHistoryEntry,removeDuplicateGraphqlHistoryEntry,restHistoryStore,-} from "@hoppscotch/common/newstore/history"-import {- getSettingSubject,- settingsStore,-} from "@hoppscotch/common/newstore/settings"+} from "~/newstore/history"+import { getSettingSubject, settingsStore } from "~/newstore/settings"-import { getSyncInitFunction, type StoreSyncDefinitionOf } from "@app/lib/sync"+import { getSyncInitFunction, type StoreSyncDefinitionOf } from ".."import * as E from "fp-ts/Either"@@ -19,7 +16,7 @@ import {removeRequestFromHistory,toggleHistoryStarStatus,} from "./api"-import { ReqType } from "@app/api/generated/graphql"+import { ReqType } from "~/helpers/backend/graphql"import { isHistoryStoreEnabled } from "."diff --git a/packages/hoppscotch-selfhost-web/src/lib/sync/index.ts b/packages/hoppscotch-common/src/lib/sync/index.tssimilarity index 82%rename from packages/hoppscotch-selfhost-web/src/lib/sync/index.tsrename to packages/hoppscotch-common/src/lib/sync/index.tsindex 812093eaf..1a4b2cafd 100644--- a/packages/hoppscotch-selfhost-web/src/lib/sync/index.ts+++ b/packages/hoppscotch-common/src/lib/sync/index.ts@@ -1,5 +1,5 @@import { Observable } from "rxjs"-import DispatchingStore from "@hoppscotch/common/newstore/DispatchingStore"+import DispatchingStore from "~/newstore/DispatchingStore"export type DispatchersOf<T extends DispatchingStore<any, any>> =T extends DispatchingStore<any, infer U>@@ -18,14 +18,17 @@ export type StoreSyncDefinitionOf<T extends DispatchingStore<any, any>> = {: never}-let _isRunningDispatchWithoutSyncing = true+// True while dispatches should be forwarded to the sync layer. Flipped to+// false inside runDispatchWithOutSyncing so changes applied from incoming+// subscription payloads don't echo back to the backend.+let _shouldSync = trueexport function runDispatchWithOutSyncing(func: () => void) {- _isRunningDispatchWithoutSyncing = false+ _shouldSync = falsetry {func()} finally {- _isRunningDispatchWithoutSyncing = true+ _shouldSync = true}}@@ -35,8 +38,8 @@ export const getSyncInitFunction = <T extends DispatchingStore<any, any>>(shouldSyncValue: () => boolean,shouldSyncObservable?: Observable<boolean>) => {- let startSubscriptions: () => () => void | undefined- let stopSubscriptions: () => void | undefined+ let startSubscriptions: (() => () => void) | undefined+ let stopSubscriptions: (() => void) | undefinedlet oldSyncStatus = shouldSyncValue()@@ -60,11 +63,7 @@ export const getSyncInitFunction = <T extends DispatchingStore<any, any>>(const operationMapperFunction = (storeSyncDefinition as any)[dispatcher]- if (- operationMapperFunction &&- _isRunningDispatchWithoutSyncing &&- shouldSyncValue()- ) {+ if (operationMapperFunction && _shouldSync && shouldSyncValue()) {operationMapperFunction(payload)}}diff --git a/packages/hoppscotch-selfhost-web/src/lib/sync/mapper.ts b/packages/hoppscotch-common/src/lib/sync/mapper.tssimilarity index 74%rename from packages/hoppscotch-selfhost-web/src/lib/sync/mapper.tsrename to packages/hoppscotch-common/src/lib/sync/mapper.tsindex 8af731167..d3e164bb8 100644--- a/packages/hoppscotch-selfhost-web/src/lib/sync/mapper.ts+++ b/packages/hoppscotch-common/src/lib/sync/mapper.ts@@ -26,16 +26,16 @@ export const createMapper = <return localIDByBackendIDMap.get(backendId)},removeEntry(backendId?: BackendIDType, index?: LocalIDType) {- if (backendId) {- const index = localIDByBackendIDMap.get(backendId)+ if (backendId != null) {+ const localIndex = localIDByBackendIDMap.get(backendId)localIDByBackendIDMap.delete(backendId)- index && backendIDByLocalIDMap.delete(index)- } else if (index) {- const backendId = backendIDByLocalIDMap.get(index)+ localIndex != null && backendIDByLocalIDMap.delete(localIndex)+ } else if (index != null) {+ const backendIdForLocal = backendIDByLocalIDMap.get(index)backendIDByLocalIDMap.delete(index)- backendId && localIDByBackendIDMap.delete(backendId)+ backendIdForLocal != null && localIDByBackendIDMap.delete(backendIdForLocal)}},}diff --git a/packages/hoppscotch-selfhost-web/src/platform/settings/desktop/api.ts b/packages/hoppscotch-common/src/lib/sync/settings/api.tssimilarity index 97%rename from packages/hoppscotch-selfhost-web/src/platform/settings/desktop/api.tsrename to packages/hoppscotch-common/src/lib/sync/settings/api.tsindex dd726fe9a..590ed7577 100644--- a/packages/hoppscotch-selfhost-web/src/platform/settings/desktop/api.ts+++ b/packages/hoppscotch-common/src/lib/sync/settings/api.ts@@ -14,7 +14,7 @@ import {UpdateUserSettingsMutation,UpdateUserSettingsMutationVariables,UserSettingsUpdatedDocument,-} from "@app/api/generated/graphql"+} from "~/helpers/backend/graphql"export const getUserSettings = () =>runGQLQuery<diff --git a/packages/hoppscotch-selfhost-web/src/platform/settings/web/index.ts b/packages/hoppscotch-common/src/lib/sync/settings/index.tssimilarity index 67%rename from packages/hoppscotch-selfhost-web/src/platform/settings/web/index.tsrename to packages/hoppscotch-common/src/lib/sync/settings/index.tsindex cbcefe0b3..785b27af4 100644--- a/packages/hoppscotch-selfhost-web/src/platform/settings/web/index.ts+++ b/packages/hoppscotch-common/src/lib/sync/settings/index.ts@@ -1,28 +1,22 @@-import { SettingsPlatformDef } from "@hoppscotch/common/platform/settings"-import { settingsSyncer } from "./sync"-import { authEvents$, def as platformAuth } from "@app/platform/auth/web"+import * as E from "fp-ts/Either"+import { runGQLSubscription } from "~/helpers/backend/GQLClient"+import { bulkApplySettings, getDefaultSettings } from "~/newstore/settings"+import { platform } from "~/platform"+import { SettingsPlatformDef } from "~/platform/settings"+import { runDispatchWithOutSyncing } from ".."import {createUserSettings,getUserSettings,runUserSettingsUpdatedSubscription,} from "./api"-import * as E from "fp-ts/Either"-import { runGQLSubscription } from "@hoppscotch/common/helpers/backend/GQLClient"-import {- bulkApplySettings,- getDefaultSettings,-} from "@hoppscotch/common/newstore/settings"-import { runDispatchWithOutSyncing } from "@app/lib/sync"+import { settingsSyncer } from "./sync"function initSettingsSync() {- const currentUser$ = platformAuth.getCurrentUserStream()+ const authEvents$ = platform.auth.getAuthEventsStream()+ const currentUser$ = platform.auth.getCurrentUserStream()settingsSyncer.startStoreSync()settingsSyncer.setupSubscriptions(setupSubscriptions)- // load the settings-- loadUserSettings()-currentUser$.subscribe(async (user) => {if (user) {// load the settings@@ -45,11 +39,19 @@ async function loadUserSettings() {const res = await getUserSettings()// create user settings if it doesn't exist- E.isLeft(res) &&- res.left.error == "user_settings/not_found" &&- (await createUserSettings(JSON.stringify(getDefaultSettings())))+ if (E.isLeft(res) && res.left.error == "user_settings/not_found") {+ const createRes = await createUserSettings(+ JSON.stringify(getDefaultSettings())+ )- if (E.isRight(res)) {+ if (E.isRight(createRes)) {+ runDispatchWithOutSyncing(() => {+ bulkApplySettings(+ JSON.parse(createRes.right.createUserSettings.properties)+ )+ })+ }+ } else if (E.isRight(res)) {runDispatchWithOutSyncing(() => {bulkApplySettings(JSON.parse(res.right.me.settings.properties))})diff --git a/packages/hoppscotch-selfhost-web/src/platform/settings/web/sync.ts b/packages/hoppscotch-common/src/lib/sync/settings/sync.tssimilarity index 79%rename from packages/hoppscotch-selfhost-web/src/platform/settings/web/sync.tsrename to packages/hoppscotch-common/src/lib/sync/settings/sync.tsindex 17d9011c1..8a19eb143 100644--- a/packages/hoppscotch-selfhost-web/src/platform/settings/web/sync.ts+++ b/packages/hoppscotch-common/src/lib/sync/settings/sync.ts@@ -1,7 +1,5 @@-import { settingsStore } from "@hoppscotch/common/newstore/settings"--import { getSyncInitFunction, type StoreSyncDefinitionOf } from "@app/lib/sync"-+import { settingsStore } from "~/newstore/settings"+import { getSyncInitFunction, StoreSyncDefinitionOf } from ".."import { updateUserSettings } from "./api"export const settingsSyncDefinition: StoreSyncDefinitionOf<diff --git a/packages/hoppscotch-common/src/newstore/collections.ts b/packages/hoppscotch-common/src/newstore/collections.tsindex ee8212801..03b121af9 100644--- a/packages/hoppscotch-common/src/newstore/collections.ts+++ b/packages/hoppscotch-common/src/newstore/collections.ts@@ -508,6 +508,10 @@ const restCollectionDispatchers = defineDispatchers({return {}}+ if (folderIndex < 0 || folderIndex >= containingFolder.folders.length) {+ console.error(`Folder index ${folderIndex} out of bounds. Skipping request.`)+ return {}+ }const theFolder = containingFolder.folders.splice(folderIndex, 1)newState.push(theFolder[0] as HoppCollection)@@ -529,6 +533,23 @@ const restCollectionDispatchers = defineDispatchers({return {}}+ // Block self-move: moving a folder to its own location+ if (path === destinationPath) {+ console.error(+ `Cannot move folder to itself. Skipping request to move folder '${path}'.`+ )+ return {}+ }++ // Block descendant move: moving a folder into itself or its descendants+ // This would create a cyclic tree structure+ if (destinationPath.startsWith(path + "/")) {+ console.error(+ `Cannot move folder into its descendant. Destination '${destinationPath}' is inside source '${path}'. Skipping request.`+ )+ return {}+ }+const target = navigateToFolderWithIndexPath(newState,destinationIndexPaths@@ -545,10 +566,18 @@ const restCollectionDispatchers = defineDispatchers({const containingFolder = navigateToFolderWithIndexPath(newState, indexPaths)// We are moving a folder from the rootif (containingFolder === null) {+ if (folderIndex < 0 || folderIndex >= newState.length) {+ console.error(`Folder index ${folderIndex} out of bounds in root. Skipping request.`)+ return {}+ }const theFolder = newState.splice(folderIndex, 1)target.folders.push(theFolder[0])} else {+ if (folderIndex < 0 || folderIndex >= containingFolder.folders.length) {+ console.error(`Folder index ${folderIndex} out of bounds. Skipping request.`)+ return {}+ }const theFolder = containingFolder.folders.splice(folderIndex, 1)target.folders.push(theFolder[0])@@ -1136,6 +1165,245 @@ const gqlCollectionDispatchers = defineDispatchers({}},+ moveFolder(+ { state }: GraphqlCollectionStoreType,+ { path, destinationPath }: { path: string; destinationPath: string | null }+ ) {+ const newState = state++ // Move the folder to the root+ if (destinationPath === null) {+ const indexPaths = path.split("/").map((x) => parseInt(x))++ if (indexPaths.length === 0) {+ console.log("Given path too short. Skipping request.")+ return {}+ }++ const folderIndex = indexPaths.pop() as number++ const containingFolder = navigateToFolderWithIndexPath(+ newState,+ indexPaths+ )+ if (containingFolder === null) {+ console.error(+ `The folder to move is already in the root. Skipping request to move folder.`+ )+ return {}+ }++ if (folderIndex < 0 || folderIndex >= containingFolder.folders.length) {+ console.error(`Folder index ${folderIndex} out of bounds. Skipping request.`)+ return {}+ }+ const theFolder = containingFolder.folders.splice(folderIndex, 1)+ newState.push(theFolder[0] as HoppCollection)++ return {+ state: newState,+ }+ }++ const indexPaths = path.split("/").map((x) => parseInt(x))++ const destinationIndexPaths = destinationPath+ .split("/")+ .map((x) => parseInt(x))++ if (indexPaths.length === 0 || destinationIndexPaths.length === 0) {+ console.error(+ `Given path is too short. Skipping request to move folder '${path}' to destination '${destinationPath}'.`+ )+ return {}+ }++ // Block self-move: moving a folder to its own location+ if (path === destinationPath) {+ console.error(+ `Cannot move folder to itself. Skipping request to move folder '${path}'.`+ )+ return {}+ }++ // Block descendant move: moving a folder into itself or its descendants+ // This would create a cyclic tree structure+ if (destinationPath.startsWith(path + "/")) {+ console.error(+ `Cannot move folder into its descendant. Destination '${destinationPath}' is inside source '${path}'. Skipping request.`+ )+ return {}+ }++ const target = navigateToFolderWithIndexPath(+ newState,+ destinationIndexPaths+ )+ if (target === null) {+ console.error(+ `Could not resolve destination path '${destinationPath}'. Skipping moveFolder dispatch.`+ )+ return {}+ }++ const folderIndex = indexPaths.pop() as number++ const containingFolder = navigateToFolderWithIndexPath(newState, indexPaths)+ // We are moving a folder from the root+ if (containingFolder === null) {+ if (folderIndex < 0 || folderIndex >= newState.length) {+ console.error(`Folder index ${folderIndex} out of bounds in root. Skipping request.`)+ return {}+ }+ const theFolder = newState.splice(folderIndex, 1)++ target.folders.push(theFolder[0])+ } else {+ if (folderIndex < 0 || folderIndex >= containingFolder.folders.length) {+ console.error(`Folder index ${folderIndex} out of bounds. Skipping request.`)+ return {}+ }+ const theFolder = containingFolder.folders.splice(folderIndex, 1)++ target.folders.push(theFolder[0])+ }++ return { state: newState }+ },++ sortGraphqlCollection(+ { state }: GraphqlCollectionStoreType,+ {+ collectionPath,+ sortOrder,+ }: { collectionPath: number | null; sortOrder: "asc" | "desc" }+ ) {+ const newState = state++ if (collectionPath === null || isNaN(collectionPath)) {+ return {+ state: newState.sort(createComparator("name", sortOrder)),+ }+ }++ const collection = newState.find((_, index) => index === collectionPath)++ if (!collection) {+ console.error(`Collection not found.`)+ return {}+ }++ collection.requests.sort(createComparator("name", sortOrder))+ collection.folders.sort(createComparator("name", sortOrder))++ return {+ state: newState,+ }+ },++ sortGraphqlFolder(+ { state }: GraphqlCollectionStoreType,+ { path, sortOrder }: { path: string; sortOrder: "asc" | "desc" }+ ) {+ const newState = state++ const indexPaths = path.split("/").map((x) => parseInt(x))+ if (indexPaths.length === 0) {+ console.log("Given path too short. Skipping request.")+ return {}+ }++ const target = navigateToFolderWithIndexPath(newState, indexPaths)+ if (target === null) {+ console.log(+ `Could not resolve path '${path}'. Ignoring sortGraphqlFolder dispatch.`+ )+ return {}+ }++ target.requests.sort(createComparator("name", sortOrder))+ target.folders.sort(createComparator("name", sortOrder))++ return {+ state: newState,+ }+ },++ updateCollectionOrder(+ { state }: GraphqlCollectionStoreType,+ {+ collectionIndex,+ destinationCollectionIndex,+ }: {+ collectionIndex: string+ destinationCollectionIndex: string | null+ }+ ) {+ const newState = state++ const indexPaths = collectionIndex.split("/").map((x) => parseInt(x))++ if (indexPaths.length === 0) {+ console.log("Given path too short. Skipping request.")+ return {}+ }++ if (destinationCollectionIndex === null) {+ const folderIndex = indexPaths.pop() as number++ const containingFolder = navigateToFolderWithIndexPath(+ newState,+ indexPaths+ )++ if (containingFolder === null) {+ newState.push(newState.splice(folderIndex, 1)[0])+ return {+ state: newState,+ }+ }++ containingFolder.folders.push(+ containingFolder.folders.splice(folderIndex, 1)[0]+ )++ return {+ state: newState,+ }+ }++ const destinationIndexPaths = destinationCollectionIndex+ .split("/")+ .map((x) => parseInt(x))++ if (destinationIndexPaths.length === 0) {+ console.log("Given path too short. Skipping request.")+ return {}+ }++ const folderIndex = indexPaths.pop() as number+ const destinationFolderIndex = destinationIndexPaths.pop() as number++ const containingFolder = navigateToFolderWithIndexPath(+ newState,+ destinationIndexPaths+ )++ if (containingFolder === null) {+ reorderItems(newState, folderIndex, destinationFolderIndex)++ return {+ state: newState,+ }+ }++ reorderItems(containingFolder.folders, folderIndex, destinationFolderIndex)++ return {+ state: newState,+ }+ },+duplicateCollection({ state }: GraphqlCollectionStoreType,// `collectionSyncID` is used to sync the duplicated collection in `gqlCollections.sync.ts`@@ -1785,7 +2053,8 @@ export function removeGraphqlCollection(collectionID?: string) {if (!collectionID) {- collectionID = graphqlCollectionStore.value.state[collectionIndex]?._ref_id+ collectionID =+ graphqlCollectionStore.value.state[collectionIndex]?.id}graphqlCollectionStore.dispatch({dispatcher: "removeCollection",@@ -1838,7 +2107,7 @@ export function removeGraphqlFolder(path: string, folderID?: string) {graphqlCollectionStore.value.state,path.split("/").map((index) => parseInt(index)))- folderID = folder?._ref_id+ folderID = folder?.id}graphqlCollectionStore.dispatch({dispatcher: "removeFolder",@@ -1949,6 +2218,55 @@ export function moveGraphqlRequest(})}+export function moveGraphqlFolder(+ path: string,+ destinationPath: string | null+) {+ graphqlCollectionStore.dispatch({+ dispatcher: "moveFolder",+ payload: {+ path,+ destinationPath,+ },+ })+}++export function sortGraphqlCollection(+ collectionPath: number | null,+ sortOrder: "asc" | "desc"+) {+ graphqlCollectionStore.dispatch({+ dispatcher: "sortGraphqlCollection",+ payload: {+ collectionPath,+ sortOrder,+ },+ })+}++export function sortGraphqlFolder(path: string, sortOrder: "asc" | "desc") {+ graphqlCollectionStore.dispatch({+ dispatcher: "sortGraphqlFolder",+ payload: {+ path,+ sortOrder,+ },+ })+}++export function updateGraphqlCollectionOrder(+ collectionIndex: string,+ destinationCollectionIndex: string | null+) {+ graphqlCollectionStore.dispatch({+ dispatcher: "updateCollectionOrder",+ payload: {+ collectionIndex,+ destinationCollectionIndex,+ },+ })+}+function removeDuplicateCollectionsFromPath(idToRemove: string,collectionPath: string | null,diff --git a/packages/hoppscotch-common/src/platform/auth.ts b/packages/hoppscotch-common/src/platform/auth.tsindex 585afb76f..2fc997498 100644--- a/packages/hoppscotch-common/src/platform/auth.ts+++ b/packages/hoppscotch-common/src/platform/auth.ts@@ -125,6 +125,17 @@ export type AuthPlatformDef = {*/getBackendHeaders: () => Record<string, string>+ /**+ * Resolves once any org-scoped context required by `getBackendHeaders` (e.g.+ * the `x-organization-id` header) has settled. On org subdomains this waits+ * for the org info lookup to succeed or fail before letting backend calls+ * proceed, so requests don't go out with a missing org id on reload.+ *+ * Returns immediately when not in an org context or when the info is already+ * determined. May be absent on platforms that don't scope backend calls by org.+ */+ waitOrganizationInfoReady?: () => Promise<void>+/*** Called when the backend GQL API client encounters an auth error to check if with the* current state, if an auth error is possible. This lets the backend GQL client know thatdiff --git a/packages/hoppscotch-common/src/platform/history.ts b/packages/hoppscotch-common/src/platform/history.tsindex 7a3cceda2..08864b308 100644--- a/packages/hoppscotch-common/src/platform/history.ts+++ b/packages/hoppscotch-common/src/platform/history.ts@@ -2,7 +2,7 @@ import { Ref } from "vue"export type HistoryPlatformDef = {initHistorySync: () => void- requestHistoryStore?: {+ requestHistoryStore: {isHistoryStoreEnabled: Ref<boolean>isFetchingHistoryStoreStatus: Ref<boolean>hasErrorFetchingHistoryStoreStatus: Ref<boolean>diff --git a/packages/hoppscotch-common/src/platform/index.ts b/packages/hoppscotch-common/src/platform/index.tsindex 6e525b02e..d1ba84a72 100644--- a/packages/hoppscotch-common/src/platform/index.ts+++ b/packages/hoppscotch-common/src/platform/index.ts@@ -3,15 +3,11 @@ import { Ref } from "vue"import { HoppModule } from "~/modules"import { AnalyticsPlatformDef } from "./analytics"import { AuthPlatformDef } from "./auth"-import { CollectionsPlatformDef } from "./collections"-import { EnvironmentsPlatformDef } from "./environments"import { ExperimentsPlatformDef } from "./experiments"-import { HistoryPlatformDef } from "./history"import { InfraPlatformDef } from "./infra"import { InspectorsPlatformDef } from "./inspectors"import { KernelInterceptorsPlatformDef } from "./kernel-interceptors"import { LimitsPlatformDef } from "./limits"-import { SettingsPlatformDef } from "./settings"import { SpotlightPlatformDef } from "./spotlight"import { UIPlatformDef } from "./ui"import { BackendPlatformDef } from "./backend"@@ -19,6 +15,7 @@ import { OrganizationPlatformDef } from "./organization"import { KernelIO } from "./kernel-io"import { AdditionalLinksPlatformDef } from "./additionalLinks"import { InstancePlatformDef } from "./instance"+import { SyncPlatformDef } from "./sync"export type PlatformDef = {ui?: UIPlatformDef@@ -28,12 +25,6 @@ export type PlatformDef = {analytics?: AnalyticsPlatformDefkernelIO: KernelIOinstance: InstancePlatformDef- sync: {- environments: EnvironmentsPlatformDef- collections: CollectionsPlatformDef- settings: SettingsPlatformDef- history: HistoryPlatformDef- }kernelInterceptors: KernelInterceptorsPlatformDefadditionalInspectors?: InspectorsPlatformDefspotlight?: SpotlightPlatformDef@@ -75,6 +66,7 @@ export type PlatformDef = {backend: BackendPlatformDeforganization?: OrganizationPlatformDefadditionalLinks?: AdditionalLinksPlatformDef+ sync?: SyncPlatformDef}export let platform: PlatformDefdiff --git a/packages/hoppscotch-common/src/platform/sync.ts b/packages/hoppscotch-common/src/platform/sync.tsnew file mode 100644index 000000000..71b60cf56--- /dev/null+++ b/packages/hoppscotch-common/src/platform/sync.ts@@ -0,0 +1,41 @@+/**+ * Per-feature sync overrides. The default sync code in `lib/sync/*` talks+ * to the upstream Postgres backend directly; when a shell's backend+ * diverges (e.g. cloud has a dedicated `updateUserGlobalEnvironment`+ * mutation that legacy/selfhost backends don't), the shell can inject a+ * replacement here and the sync layer will feature-detect.+ *+ * Each field is optional — when omitted the sync layer falls back to its+ * legacy code path (currently: `updateUserEnvironment` with an empty+ * `name`, which the legacy backend treats as a global update).+ */+export type SyncPlatformDef = {+ environment?: {+ /**+ * Update the user's global environment. Receives the backend env id+ * and the pre-serialised JSON payload (the `{ v, variables }`+ * wrapper). Fire-and-forget — the sync layer doesn't await the+ * return.+ */+ updateUserGlobalEnvironment?: (id: string, variables: string) => unknown+ }+ history?: {+ /**+ * Resolve whether the backend currently has user-history storing+ * enabled. Self-host exposes this through the `isUserHistoryEnabled`+ * infra-config; backends without that admin toggle (e.g. cloud) omit+ * this hook and the sync layer treats history as always enabled.+ * Rejects on fetch failure so the sync layer can flag its error state.+ */+ getHistoryStoreStatus?: () => Promise<boolean>+ /**+ * Subscribe to backend-side history-enabled toggles (the self-host+ * infra-config `USER_HISTORY_STORE_ENABLED`). `onStatusChange` fires+ * with each new enabled state; returns an unsubscribe handle the sync+ * layer tears down alongside the other history subscriptions.+ */+ subscribeToHistoryStoreStatus?: (+ onStatusChange: (enabled: boolean) => void+ ) => { unsubscribe: () => void }+ }+}diff --git a/packages/hoppscotch-common/src/services/initialization.service.ts b/packages/hoppscotch-common/src/services/initialization.service.tsindex 5d5f855c2..d2ebf5edb 100644--- a/packages/hoppscotch-common/src/services/initialization.service.ts+++ b/packages/hoppscotch-common/src/services/initialization.service.ts@@ -14,6 +14,7 @@ import { performMigrations } from "~/helpers/migrations"import { initBackendGQLClient } from "~/helpers/backend/GQLClient"import { getKernelMode } from "@hoppscotch/kernel"import { diag } from "~/kernel/log"+import { sync } from "~/lib/sync/defs"type InitEvent =| { type: "STORE_READY" }@@ -136,10 +137,10 @@ export class InitializationService extends Service<InitEvent> {}await Promise.all([- platform.sync.settings.initSettingsSync(),- platform.sync.collections.initCollectionsSync(),- platform.sync.history.initHistorySync(),- platform.sync.environments.initEnvironmentsSync(),+ sync.settings.initSettingsSync(),+ sync.collections.initCollectionsSync(),+ sync.history.initHistorySync(),+ sync.environments.initEnvironmentsSync(),platform.analytics?.initAnalytics(),])diff --git a/packages/hoppscotch-common/src/services/spotlight/searchers/__tests__/history.searcher.spec.ts b/packages/hoppscotch-common/src/services/spotlight/searchers/__tests__/history.searcher.spec.tsindex 8c2e6873d..c46dea1e4 100644--- a/packages/hoppscotch-common/src/services/spotlight/searchers/__tests__/history.searcher.spec.ts+++ b/packages/hoppscotch-common/src/services/spotlight/searchers/__tests__/history.searcher.spec.ts@@ -1,14 +1,13 @@import { TestContainer } from "dioc/testing"import { beforeEach, describe, expect, it, vi } from "vitest"-import { HistorySpotlightSearcherService } from "../history.searcher"import { nextTick, ref } from "vue"-import { SpotlightService } from "../.."-import { GQLHistoryEntry, RESTHistoryEntry } from "~/newstore/history"-import { getDefaultRESTRequest } from "~/helpers/rest/default"import { HoppAction, HoppActionWithArgs } from "~/helpers/actions"import { getDefaultGQLRequest } from "~/helpers/graphql/default"+import { getDefaultRESTRequest } from "~/helpers/rest/default"+import { GQLHistoryEntry, RESTHistoryEntry } from "~/newstore/history"import { RESTTabService } from "~/services/tab/rest"-import { PlatformDef, setPlatformDef } from "~/platform"+import { SpotlightService } from "../.."+import { HistorySpotlightSearcherService } from "../history.searcher"async function flushPromises() {return await new Promise((r) => setTimeout(r))@@ -53,6 +52,18 @@ vi.mock("~/newstore/history", () => ({},}))+vi.mock("~/lib/sync/history", () => ({+ __esModule: true,+ def: {+ initHistorySync: vi.fn(),+ requestHistoryStore: {+ isHistoryStoreEnabled: { value: true },+ isFetchingHistoryStoreStatus: { value: false },+ hasErrorFetchingHistoryStoreStatus: { value: false },+ },+ },+}))+describe("HistorySpotlightSearcherService", () => {beforeEach(() => {let x = actionsMock.value.pop()@@ -75,14 +86,6 @@ describe("HistorySpotlightSearcherService", () => {actionsMock.invokeAction.mockReset()createNewTabFn.mockReset()-- const platform = {- sync: {- history: {},- },- }-- setPlatformDef(platform as PlatformDef)})it("registers with the spotlight service upon initialization", async () => {diff --git a/packages/hoppscotch-common/src/services/spotlight/searchers/history.searcher.ts b/packages/hoppscotch-common/src/services/spotlight/searchers/history.searcher.tsindex 91ed1ba93..d9717b880 100644--- a/packages/hoppscotch-common/src/services/spotlight/searchers/history.searcher.ts+++ b/packages/hoppscotch-common/src/services/spotlight/searchers/history.searcher.ts@@ -20,7 +20,7 @@ import { useStreamStatic } from "~/composables/stream"import { activeActions$, invokeAction } from "~/helpers/actions"import { map } from "rxjs/operators"import { HoppRequestDocument } from "~/helpers/rest/document"-import { platform } from "~/platform"+import { def as historySync } from "~/lib/sync/history"/*** This searcher is responsible for searching through the history.@@ -49,10 +49,10 @@ export class HistorySpotlightSearcherService})[0]- private hasHistoryPlatformDef = "requestHistoryStore" in platform.sync.history+ private hasHistoryPlatformDef = !!historySync.requestHistoryStoreprivate isHistoryEnabledPlatformRef =- platform.sync.history.requestHistoryStore?.isHistoryStoreEnabled+ historySync.requestHistoryStore?.isHistoryStoreEnabledprivate clearHistoryActionEnabledCombined = computed(() => {// if the platform has not defined the history store, by default we consider history is enableddiff --git a/packages/hoppscotch-common/vitest.config.mts b/packages/hoppscotch-common/vitest.config.mtsindex 95fa896b7..e9bf56b64 100644--- a/packages/hoppscotch-common/vitest.config.mts+++ b/packages/hoppscotch-common/vitest.config.mts@@ -16,6 +16,17 @@ export default defineConfig({__dirname,"../hoppscotch-common/src/composables"),+ "@components": path.resolve(+ __dirname,+ "../hoppscotch-common/src/components"+ ),+ "@helpers": path.resolve(__dirname, "../hoppscotch-common/src/helpers"),+ "@modules": path.resolve(__dirname, "../hoppscotch-common/src/modules"),+ "@workers": path.resolve(__dirname, "../hoppscotch-common/src/workers"),+ "@functional": path.resolve(+ __dirname,+ "../hoppscotch-common/src/helpers/functional"+ ),},},plugins: [diff --git a/packages/hoppscotch-data/src/global-environment/index.ts b/packages/hoppscotch-data/src/global-environment/index.tsindex d6817a3b7..4fd1dc6c3 100644--- a/packages/hoppscotch-data/src/global-environment/index.ts+++ b/packages/hoppscotch-data/src/global-environment/index.ts@@ -35,3 +35,5 @@ export type GlobalEnvironment = InferredEntity<typeof GlobalEnvironment>export type GlobalEnvironmentVariable = InferredEntity<typeof GlobalEnvironment>["variables"][number]++export const GlobalEnvironmentSchemaVersion = 2diff --git a/packages/hoppscotch-selfhost-web/src/main.ts b/packages/hoppscotch-selfhost-web/src/main.tsindex e52728eb3..27f3b4374 100644--- a/packages/hoppscotch-selfhost-web/src/main.ts+++ b/packages/hoppscotch-selfhost-web/src/main.ts@@ -10,16 +10,8 @@ import { getKernelMode } from "@hoppscotch/kernel"import { def as stdBackendDef } from "@hoppscotch/common/platform/std/backend"// Platform importsimport { def as webAuth } from "@app/platform/auth/web"-import { def as webEnvironments } from "@app/platform/environments/web"-import { def as webCollections } from "@app/platform/collections/web"-import { def as webSettings } from "@app/platform/settings/web"-import { def as webHistory } from "@app/platform/history/web"import { def as desktopAuth } from "@app/platform/auth/desktop"-import { def as desktopEnvironments } from "@app/platform/environments/desktop"-import { def as desktopCollections } from "@app/platform/collections/desktop"-import { def as desktopSettings } from "@app/platform/settings/desktop"-import { def as desktopHistory } from "@app/platform/history/desktop"// Std platformimport { def as webInstance } from "@app/platform/instance/web"@@ -27,6 +19,7 @@ import { def as desktopInstance } from "@app/platform/instance/desktop"import { stdFooterItems } from "@hoppscotch/common/platform/std/ui/footerItem"import { stdSupportOptionItems } from "@hoppscotch/common/platform/std/ui/supportOptionsItem"import { InfraPlatform } from "@app/platform/infra/infra.platform"+import { historySyncDef } from "@app/platform/history/sync"import { kernelIO } from "@hoppscotch/common/platform/std/kernel-io"import { HeaderDownloadableLinksService } from "@app/services/headerDownloadableLinks.service"@@ -43,10 +36,6 @@ import { BrowserKernelInterceptorService } from "@hoppscotch/common/platform/stdconst PLATFORM_CONFIG = {web: {auth: webAuth,- environments: webEnvironments,- collections: webCollections,- settings: webSettings,- history: webHistory,instance: webInstance,interceptors: [BrowserKernelInterceptorService,@@ -62,10 +51,6 @@ const PLATFORM_CONFIG = {desktop: {auth: desktopAuth,- environments: desktopEnvironments,- collections: desktopCollections,- settings: desktopSettings,- history: desktopHistory,instance: desktopInstance,interceptors: [NativeKernelInterceptorService,@@ -177,11 +162,12 @@ async function initApp() {auth: config.auth,kernelIO,instance: config.instance,++ // The history-enabled toggle is a self-host-only infra-config; inject the+ // documents the shared sync layer feature-detects rather than baking them+ // into common.sync: {- environments: config.environments,- collections: config.collections,- settings: config.settings,- history: config.history,+ history: historySyncDef,},kernelInterceptors: {diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/api.ts b/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/api.tsdeleted file mode 100644index 697722e68..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/api.ts+++ /dev/null@@ -1,371 +0,0 @@-import {- CreateGqlChildUserCollectionDocument,- CreateGqlChildUserCollectionMutation,- CreateGqlChildUserCollectionMutationVariables,- CreateGqlRootUserCollectionDocument,- CreateGqlRootUserCollectionMutation,- CreateGqlRootUserCollectionMutationVariables,- CreateGqlUserRequestDocument,- CreateGqlUserRequestMutation,- CreateGqlUserRequestMutationVariables,- CreateRestChildUserCollectionDocument,- CreateRestChildUserCollectionMutation,- CreateRestChildUserCollectionMutationVariables,- CreateRestRootUserCollectionDocument,- CreateRestRootUserCollectionMutation,- CreateRestRootUserCollectionMutationVariables,- CreateRestUserRequestDocument,- CreateRestUserRequestMutation,- CreateRestUserRequestMutationVariables,- DeleteUserCollectionDocument,- DeleteUserCollectionMutation,- DeleteUserCollectionMutationVariables,- DeleteUserRequestDocument,- DeleteUserRequestMutation,- DeleteUserRequestMutationVariables,- DuplicateUserCollectionDocument,- DuplicateUserCollectionMutation,- DuplicateUserCollectionMutationVariables,- ExportUserCollectionsToJsonDocument,- ExportUserCollectionsToJsonQuery,- ExportUserCollectionsToJsonQueryVariables,- ImportUserCollectionsFromJsonDocument,- ImportUserCollectionsFromJsonMutation,- ImportUserCollectionsFromJsonMutationVariables,- MoveUserCollectionDocument,- MoveUserCollectionMutation,- MoveUserCollectionMutationVariables,- MoveUserRequestDocument,- MoveUserRequestMutation,- MoveUserRequestMutationVariables,- RenameUserCollectionDocument,- RenameUserCollectionMutation,- RenameUserCollectionMutationVariables,- ReqType,- SortOptions,- SortUserCollectionsDocument,- SortUserCollectionsMutation,- SortUserCollectionsMutationVariables,- UpdateGqlUserRequestDocument,- UpdateGqlUserRequestMutation,- UpdateGqlUserRequestMutationVariables,- UpdateRestUserRequestDocument,- UpdateRestUserRequestMutation,- UpdateRestUserRequestMutationVariables,- UpdateUserCollectionDocument,- UpdateUserCollectionMutation,- UpdateUserCollectionMutationVariables,- UpdateUserCollectionOrderDocument,- UpdateUserCollectionOrderMutation,- UpdateUserCollectionOrderMutationVariables,- UserChildCollectionSortedDocument,- UserCollectionCreatedDocument,- UserCollectionDuplicatedDocument,- UserCollectionMovedDocument,- UserCollectionOrderUpdatedDocument,- UserCollectionRemovedDocument,- UserCollectionUpdatedDocument,- UserRequestCreatedDocument,- UserRequestDeletedDocument,- UserRequestMovedDocument,- UserRequestUpdatedDocument,- UserRootCollectionsSortedDocument,-} from "@app/api/generated/graphql"-import {- runGQLQuery,- runGQLSubscription,- runMutation,-} from "@hoppscotch/common/helpers/backend/GQLClient"--export const createRESTRootUserCollection = (title: string, data?: string) =>- runMutation<- CreateRestRootUserCollectionMutation,- CreateRestRootUserCollectionMutationVariables,- ""- >(CreateRestRootUserCollectionDocument, {- title,- data,- })()--export const createGQLRootUserCollection = (title: string, data?: string) =>- runMutation<- CreateGqlRootUserCollectionMutation,- CreateGqlRootUserCollectionMutationVariables,- ""- >(CreateGqlRootUserCollectionDocument, {- title,- data,- })()--export const createRESTUserRequest = (- title: string,- request: string,- collectionID: string-) =>- runMutation<- CreateRestUserRequestMutation,- CreateRestUserRequestMutationVariables,- ""- >(CreateRestUserRequestDocument, {- title,- request,- collectionID,- })()--export const createGQLUserRequest = (- title: string,- request: string,- collectionID: string-) =>- runMutation<- CreateGqlUserRequestMutation,- CreateGqlUserRequestMutationVariables,- ""- >(CreateGqlUserRequestDocument, {- title,- request,- collectionID,- })()--export const createRESTChildUserCollection = (- title: string,- parentUserCollectionID: string,- data?: string-) =>- runMutation<- CreateRestChildUserCollectionMutation,- CreateRestChildUserCollectionMutationVariables,- ""- >(CreateRestChildUserCollectionDocument, {- title,- parentUserCollectionID,- data,- })()--export const createGQLChildUserCollection = (- title: string,- parentUserCollectionID: string,- data?: string-) =>- runMutation<- CreateGqlChildUserCollectionMutation,- CreateGqlChildUserCollectionMutationVariables,- ""- >(CreateGqlChildUserCollectionDocument, {- title,- parentUserCollectionID,- data,- })()--export const deleteUserCollection = (userCollectionID: string) =>- runMutation<- DeleteUserCollectionMutation,- DeleteUserCollectionMutationVariables,- ""- >(DeleteUserCollectionDocument, {- userCollectionID,- })()--export const renameUserCollection = (- userCollectionID: string,- newTitle: string-) =>- runMutation<- RenameUserCollectionMutation,- RenameUserCollectionMutationVariables,- ""- >(RenameUserCollectionDocument, { userCollectionID, newTitle })()--export const updateUserCollection = (- userCollectionID: string,- newTitle?: string,- data?: string-) =>- runMutation<- UpdateUserCollectionMutation,- UpdateUserCollectionMutationVariables,- ""- >(UpdateUserCollectionDocument, { userCollectionID, newTitle, data })()--export const moveUserCollection = (- sourceCollectionID: string,- destinationCollectionID?: string-) =>- runMutation<- MoveUserCollectionMutation,- MoveUserCollectionMutationVariables,- ""- >(MoveUserCollectionDocument, {- userCollectionID: sourceCollectionID,- destCollectionID: destinationCollectionID,- })()--export const duplicateUserCollection = (- collectionID: string,- reqType: ReqType-) =>- runMutation<- DuplicateUserCollectionMutation,- DuplicateUserCollectionMutationVariables,- ""- >(DuplicateUserCollectionDocument, {- collectionID,- reqType,- })()--export const sortUserCollections = (- parentCollectionID: string | null,- sortOption: SortOptions-) =>- runMutation<- SortUserCollectionsMutation,- SortUserCollectionsMutationVariables,- ""- >(SortUserCollectionsDocument, {- parentCollectionID,- sortOption,- })()--export const editUserRequest = (- requestID: string,- title: string,- request: string-) =>- runMutation<- UpdateRestUserRequestMutation,- UpdateRestUserRequestMutationVariables,- ""- >(UpdateRestUserRequestDocument, {- id: requestID,- request,- title,- })()--export const editGQLUserRequest = (- requestID: string,- title: string,- request: string-) =>- runMutation<- UpdateGqlUserRequestMutation,- UpdateGqlUserRequestMutationVariables,- ""- >(UpdateGqlUserRequestDocument, {- id: requestID,- request,- title,- })()--export const deleteUserRequest = (requestID: string) =>- runMutation<- DeleteUserRequestMutation,- DeleteUserRequestMutationVariables,- ""- >(DeleteUserRequestDocument, {- requestID,- })()--export const moveUserRequest = (- sourceCollectionID: string,- destinationCollectionID: string,- requestID: string,- nextRequestID?: string-) =>- runMutation<MoveUserRequestMutation, MoveUserRequestMutationVariables, "">(- MoveUserRequestDocument,- {- sourceCollectionID,- destinationCollectionID,- requestID,- nextRequestID,- }- )()--export const updateUserCollectionOrder = (- collectionID: string,- nextCollectionID?: string-) =>- runMutation<- UpdateUserCollectionOrderMutation,- UpdateUserCollectionOrderMutationVariables,- ""- >(UpdateUserCollectionOrderDocument, {- collectionID,- nextCollectionID,- })()--export const exportUserCollectionsToJSON = (- collectionID?: string,- collectionType: ReqType.Rest | ReqType.Gql = ReqType.Rest-) =>- runGQLQuery<- ExportUserCollectionsToJsonQuery,- ExportUserCollectionsToJsonQueryVariables,- ""- >({- query: ExportUserCollectionsToJsonDocument,- variables: { collectionID, collectionType },- })--export const importUserCollectionsFromJSON = (- jsonString: string,- reqType: ReqType,- parentCollectionID?: string-) =>- runMutation<- ImportUserCollectionsFromJsonMutation,- ImportUserCollectionsFromJsonMutationVariables,- ""- >(ImportUserCollectionsFromJsonDocument, {- jsonString,- reqType,- parentCollectionID,- })()--export const runUserCollectionCreatedSubscription = () =>- runGQLSubscription({ query: UserCollectionCreatedDocument, variables: {} })--export const runUserCollectionUpdatedSubscription = () =>- runGQLSubscription({ query: UserCollectionUpdatedDocument, variables: {} })--export const runUserCollectionRemovedSubscription = () =>- runGQLSubscription({ query: UserCollectionRemovedDocument, variables: {} })--export const runUserCollectionMovedSubscription = () =>- runGQLSubscription({ query: UserCollectionMovedDocument, variables: {} })--export const runUserCollectionOrderUpdatedSubscription = () =>- runGQLSubscription({- query: UserCollectionOrderUpdatedDocument,- variables: {},- })--export const runUserCollectionDuplicatedSubscription = () =>- runGQLSubscription({- query: UserCollectionDuplicatedDocument,- variables: {},- })--export const runUserRootCollectionsSortedSubscription = () =>- runGQLSubscription({- query: UserRootCollectionsSortedDocument,- variables: {},- })--export const runUserChildCollectionSortedSubscription = () =>- runGQLSubscription({- query: UserChildCollectionSortedDocument,- variables: {},- })--export const runUserRequestCreatedSubscription = () =>- runGQLSubscription({ query: UserRequestCreatedDocument, variables: {} })--export const runUserRequestUpdatedSubscription = () =>- runGQLSubscription({ query: UserRequestUpdatedDocument, variables: {} })--export const runUserRequestMovedSubscription = () =>- runGQLSubscription({ query: UserRequestMovedDocument, variables: {} })--export const runUserRequestDeletedSubscription = () =>- runGQLSubscription({ query: UserRequestDeletedDocument, variables: {} })diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/gqlCollections.sync.ts b/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/gqlCollections.sync.tsdeleted file mode 100644index 1ef267968..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/gqlCollections.sync.ts+++ /dev/null@@ -1,422 +0,0 @@-import {- graphqlCollectionStore,- navigateToFolderWithIndexPath,- removeDuplicateGraphqlCollectionOrFolder,-} from "@hoppscotch/common/newstore/collections"-import {- getSettingSubject,- settingsStore,-} from "@hoppscotch/common/newstore/settings"--import {- generateUniqueRefId,- HoppCollection,- HoppRESTRequest,-} from "@hoppscotch/data"--import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"--import { getSyncInitFunction, type StoreSyncDefinitionOf } from "@app/lib/sync"--import { createMapper } from "@app/lib/sync/mapper"--import {- createGQLChildUserCollection,- createGQLRootUserCollection,- createGQLUserRequest,- deleteUserCollection,- deleteUserRequest,- duplicateUserCollection,- editGQLUserRequest,- importUserCollectionsFromJSON,- updateUserCollection,-} from "./api"--import * as E from "fp-ts/Either"-import { ReqType } from "@app/api/generated/graphql"-import { moveOrReorderRequests } from "./sync"--// gqlCollectionsMapper uses the collectionPath as the local identifier-// Helper function to transform HoppCollection to backend format-const transformCollectionForBackend = (collection: HoppCollection): any => {- const data = {- auth: collection.auth ?? {- authType: "inherit",- authActive: true,- },- headers: collection.headers ?? [],- variables: stripSecretVariableValuesForWire(collection.variables ?? []),- _ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",- }-- return {- name: collection.name,- data: JSON.stringify(data),- folders: collection.folders.map(transformCollectionForBackend),- requests: collection.requests,- }-}--export const gqlCollectionsMapper = createMapper<string, string>()--// gqlRequestsMapper uses the collectionPath/requestIndex as the local identifier-export const gqlRequestsMapper = createMapper<string, string>()--// Optimized implementation using importUserCollectionsFromJSON for bulk operations-// This replaces individual createGQLRootUserCollection/createGQLChildUserCollection/createGQLUserRequest calls-const recursivelySyncCollections = async (- collection: HoppCollection,- collectionPath: string,- parentUserCollectionID?: string-) => {- let parentCollectionID = parentUserCollectionID-- // if parentUserCollectionID does not exist, create the collection as a root collection- if (!parentUserCollectionID) {- const data = {- auth: collection.auth ?? {- authType: "inherit",- authActive: true,- },- headers: collection.headers ?? [],- variables: stripSecretVariableValuesForWire(collection.variables ?? []),- _ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",- }- const res = await createGQLRootUserCollection(- collection.name,- JSON.stringify(data)- )-- if (E.isRight(res)) {- parentCollectionID = res.right.createGQLRootUserCollection.id-- const returnedData = res.right.createGQLRootUserCollection.data- ? JSON.parse(res.right.createGQLRootUserCollection.data)- : {- auth: {- authType: "inherit",- authActive: true,- },- headers: [],- variables: [],- _ref_id: collection._ref_id ?? generateUniqueRefId("coll"),- description: null,- preRequestScript: "",- testScript: "",- }-- collection.id = parentCollectionID- collection.auth = returnedData.auth- collection.headers = returnedData.headers- collection.variables = returnedData.variables- collection._ref_id = returnedData._ref_id ?? generateUniqueRefId("coll")- collection.description = returnedData.description ?? null- collection.preRequestScript = returnedData.preRequestScript ?? ""- collection.testScript = returnedData.testScript ?? ""-- removeDuplicateGraphqlCollectionOrFolder(- parentCollectionID,- collectionPath- )- } else {- parentCollectionID = undefined- }- } else {- // if parentUserCollectionID exists, create the collection as a child collection-- const data = {- auth: collection.auth ?? {- authType: "inherit",- authActive: true,- },- headers: collection.headers ?? [],- variables: stripSecretVariableValuesForWire(collection.variables ?? []),- _ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",- }-- const res = await createGQLChildUserCollection(- collection.name,- parentUserCollectionID,- JSON.stringify(data)- )-- if (E.isRight(res)) {- const childCollectionId = res.right.createGQLChildUserCollection.id-- const returnedData = res.right.createGQLChildUserCollection.data- ? JSON.parse(res.right.createGQLChildUserCollection.data)- : {- auth: {- authType: "inherit",- authActive: true,- },- headers: [],- variables: [],- _ref_id: collection._ref_id ?? generateUniqueRefId("coll"),- description: null,- preRequestScript: "",- testScript: "",- }-- collection.id = childCollectionId- collection.auth = returnedData.auth- collection.headers = returnedData.headers- parentCollectionID = childCollectionId- collection.variables = returnedData.variables- collection._ref_id = returnedData._ref_id ?? generateUniqueRefId("coll")- collection.description = returnedData.description ?? null- collection.preRequestScript = returnedData.preRequestScript ?? ""- collection.testScript = returnedData.testScript ?? ""-- removeDuplicateGraphqlCollectionOrFolder(- childCollectionId,- `${collectionPath}`- )- }- }-- // create the requests- if (parentCollectionID) {- collection.requests.forEach(async (request) => {- const res = await createGQLUserRequest(- request.name,- JSON.stringify(request),- parentCollectionID- )-- if (res && E.isRight(res)) {- const requestId = res.right.createGQLUserRequest.id-- request.id = requestId- }- })- }-- // create the folders aka child collections- if (parentCollectionID)- collection.folders.forEach(async (folder, index) => {- recursivelySyncCollections(- folder,- `${collectionPath}/${index}`,- parentCollectionID- )- })-}--// TODO: generalize this-// TODO: ask backend to send enough info on the subscription to not need this-export const collectionReorderOrMovingOperations: {- sourceCollectionID: string- destinationCollectionID?: string- reorderOperation: {- fromPath: string- toPath?: string- }-}[] = []--type OperationStatus = "pending" | "completed"--type OperationCollectionRemoved = {- type: "COLLECTION_REMOVED"- collectionBackendID: string- status: OperationStatus-}--export const gqlCollectionsOperations: Array<OperationCollectionRemoved> = []--export const storeSyncDefinition: StoreSyncDefinitionOf<- typeof graphqlCollectionStore-> = {- async appendCollections({ entries }) {- if (entries.length === 0) return-- // Transform collections to backend format- const transformedCollections = entries.map(transformCollectionForBackend)-- // Use the bulk import API instead of individual calls- const jsonString = JSON.stringify(transformedCollections)-- const result = await importUserCollectionsFromJSON(- jsonString,- ReqType.Gql,- undefined // undefined for root collections- )-- // The backend handles creating all collections and requests in a single transaction- // The frontend collections will be updated through subscriptions-- if (E.isLeft(result)) {- // Fallback to individual calls if bulk import fails- let indexStart =- graphqlCollectionStore.value.state.length - entries.length-- entries.forEach((collection) => {- recursivelySyncCollections(collection, `${indexStart}`)- indexStart++- })- }- },- async addCollection({ collection }) {- // Use individual API for single collection creation (not import)- const lastCreatedCollectionIndex =- graphqlCollectionStore.value.state.length - 1-- await recursivelySyncCollections(- collection,- `${lastCreatedCollectionIndex}`- )- },- async removeCollection({ collectionID }) {- if (collectionID) {- await deleteUserCollection(collectionID)- }- },- editCollection({ collection, collectionIndex }) {- const collectionID = navigateToFolderWithIndexPath(- graphqlCollectionStore.value.state,- [collectionIndex]- )?.id-- const data = {- auth: collection.auth,- headers: collection.headers,- variables: stripSecretVariableValuesForWire(collection.variables ?? []),- _ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",- }-- if (collectionID) {- updateUserCollection(collectionID, collection.name, JSON.stringify(data))- }- },- async addFolder({ name, path }) {- const parentCollection = navigateToFolderWithIndexPath(- graphqlCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )-- const parentCollectionBackendID = parentCollection?.id-- if (parentCollectionBackendID) {- const foldersLength = parentCollection.folders.length-- const res = await createGQLChildUserCollection(- name,- parentCollectionBackendID- )-- 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 }) {- const folderBackendId = navigateToFolderWithIndexPath(- graphqlCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )?.id-- const data = {- auth: folder.auth,- headers: folder.headers,- variables: stripSecretVariableValuesForWire(folder.variables ?? []),- _ref_id: folder._ref_id,- description: folder.description ?? null,- preRequestScript: folder.preRequestScript ?? "",- testScript: folder.testScript ?? "",- }-- if (folderBackendId) {- updateUserCollection(folderBackendId, folder.name, JSON.stringify(data))- }- },- async removeFolder({ folderID }) {- if (folderID) {- await deleteUserCollection(folderID)- }- },- async duplicateCollection({ collectionSyncID }) {- if (collectionSyncID) {- await duplicateUserCollection(collectionSyncID, ReqType.Gql)- }- },- editRequest({ path, requestIndex, requestNew }) {- const request = navigateToFolderWithIndexPath(- graphqlCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )?.requests[requestIndex]-- const requestBackendID = request?.id-- if (requestBackendID) {- editGQLUserRequest(- requestBackendID,- (requestNew as HoppRESTRequest).name,- JSON.stringify(requestNew)- )- }- },- async saveRequestAs({ path, request }) {- const folder = navigateToFolderWithIndexPath(- graphqlCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )-- const parentCollectionBackendID = folder?.id-- if (parentCollectionBackendID) {- const newRequest = folder.requests[folder.requests.length - 1]-- const res = await createGQLUserRequest(- (request as HoppRESTRequest).name,- JSON.stringify(request),- parentCollectionBackendID- )-- if (E.isRight(res)) {- const { id } = res.right.createGQLUserRequest-- newRequest.id = id- removeDuplicateGraphqlCollectionOrFolder(- id,- `${path}/${folder.requests.length - 1}`,- "request"- )- }- }- },- async removeRequest({ requestID }) {- if (requestID) {- await deleteUserRequest(requestID)- }- },- moveRequest({ destinationPath, path, requestIndex }) {- moveOrReorderRequests(requestIndex, path, destinationPath, undefined, "GQL")- },-}--export const gqlCollectionsSyncer = getSyncInitFunction(- graphqlCollectionStore,- storeSyncDefinition,- () => settingsStore.value.syncCollections,- getSettingSubject("syncCollections")-)diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/import.ts b/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/import.tsdeleted file mode 100644index 269636ce7..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/import.ts+++ /dev/null@@ -1 +0,0 @@-export { importToPersonalWorkspace } from "../web/import"diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/sync.ts b/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/sync.tsdeleted file mode 100644index 7fb998600..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/sync.ts+++ /dev/null@@ -1,733 +0,0 @@-import {- graphqlCollectionStore,- navigateToFolderWithIndexPath,- removeDuplicateRESTCollectionOrFolder,- restCollectionStore,-} from "@hoppscotch/common/newstore/collections"-import {- getSettingSubject,- settingsStore,-} from "@hoppscotch/common/newstore/settings"--import {- generateUniqueRefId,- HoppCollection,- HoppRESTRequest,-} from "@hoppscotch/data"--import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"--import { getSyncInitFunction, StoreSyncDefinitionOf } from "@app/lib/sync"-import { createMapper } from "@app/lib/sync/mapper"-import {- createRESTChildUserCollection,- createRESTRootUserCollection,- createRESTUserRequest,- deleteUserCollection,- deleteUserRequest,- duplicateUserCollection,- editUserRequest,- importUserCollectionsFromJSON,- moveUserCollection,- moveUserRequest,- sortUserCollections,- updateUserCollection,- updateUserCollectionOrder,-} from "./api"--import * as E from "fp-ts/Either"-import { ReqType, SortOptions } from "@app/api/generated/graphql"--// restCollectionsMapper uses the collectionPath as the local identifier-// Helper function to transform HoppCollection to backend format-const transformCollectionForBackend = (collection: HoppCollection): any => {- const data = {- auth: collection.auth ?? {- authType: "inherit",- authActive: true,- },- headers: collection.headers ?? [],- variables: stripSecretVariableValuesForWire(collection.variables ?? []),- _ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",- }-- return {- name: collection.name,- data: JSON.stringify(data),- folders: collection.folders.map(transformCollectionForBackend),- requests: collection.requests,- }-}--export const restCollectionsMapper = createMapper<string, string>()--// restRequestsMapper uses the collectionPath/requestIndex as the local identifier-export const restRequestsMapper = createMapper<string, string>()--// Optimized implementation using importUserCollectionsFromJSON for bulk operations-// This replaces individual createRESTRootUserCollection/createRESTChildUserCollection/createRESTUserRequest calls-const recursivelySyncCollections = async (- collection: HoppCollection,- collectionPath: string,- parentUserCollectionID?: string-) => {- let parentCollectionID = parentUserCollectionID-- // if parentUserCollectionID does not exist, create the collection as a root collection- if (!parentUserCollectionID) {- const data = {- auth: collection.auth ?? {- authType: "inherit",- authActive: true,- },- headers: collection.headers ?? [],- variables: stripSecretVariableValuesForWire(collection.variables ?? []),- _ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",- }- const res = await createRESTRootUserCollection(- collection.name,- JSON.stringify(data)- )- if (E.isRight(res)) {- parentCollectionID = res.right.createRESTRootUserCollection.id-- const returnedData = res.right.createRESTRootUserCollection.data- ? JSON.parse(res.right.createRESTRootUserCollection.data)- : {- auth: {- authType: "inherit",- authActive: true,- },- headers: [],- variables: [],- _ref_id: generateUniqueRefId("coll"),- description: null,- preRequestScript: "",- testScript: "",- }-- collection.id = parentCollectionID- collection._ref_id = returnedData._ref_id ?? generateUniqueRefId("coll")- collection.auth = returnedData.auth- collection.headers = returnedData.headers- collection.variables = returnedData.variables- collection.description = returnedData.description ?? null- collection.preRequestScript = returnedData.preRequestScript ?? ""- collection.testScript = returnedData.testScript ?? ""-- removeDuplicateRESTCollectionOrFolder(parentCollectionID, collectionPath)- } else {- parentCollectionID = undefined- }- } else {- // if parentUserCollectionID exists, create the collection as a child collection- const data = {- auth: collection.auth ?? {- authType: "inherit",- authActive: true,- },- headers: collection.headers ?? [],- variables: stripSecretVariableValuesForWire(collection.variables ?? []),- _ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",- }-- const res = await createRESTChildUserCollection(- collection.name,- parentUserCollectionID,- JSON.stringify(data)- )-- if (E.isRight(res)) {- const childCollectionId = res.right.createRESTChildUserCollection.id-- const returnedData = res.right.createRESTChildUserCollection.data- ? JSON.parse(res.right.createRESTChildUserCollection.data)- : {- auth: {- authType: "inherit",- authActive: true,- },- headers: [],- variables: [],- _ref_id: generateUniqueRefId("coll"),- description: null,- preRequestScript: "",- testScript: "",- }-- collection.id = childCollectionId- collection._ref_id = returnedData._ref_id ?? generateUniqueRefId("coll")- collection.auth = returnedData.auth- collection.headers = returnedData.headers- parentCollectionID = childCollectionId- collection.variables = returnedData.variables- collection.description = returnedData.description ?? null- collection.preRequestScript = returnedData.preRequestScript ?? ""- collection.testScript = returnedData.testScript ?? ""-- removeDuplicateRESTCollectionOrFolder(- childCollectionId,- `${collectionPath}`- )- }- }-- // create the requests- if (parentCollectionID) {- collection.requests.forEach(async (request) => {- const res = await createRESTUserRequest(- request.name,- JSON.stringify(request),- parentCollectionID- )-- if (res && E.isRight(res)) {- const requestId = res.right.createRESTUserRequest.id-- request.id = requestId- }- })- }-- // create the folders aka child collections- if (parentCollectionID)- collection.folders.forEach(async (folder, index) => {- recursivelySyncCollections(- folder,- `${collectionPath}/${index}`,- parentCollectionID- )- })-}--// TODO: generalize this-// TODO: ask backend to send enough info on the subscription to not need this-export const collectionReorderOrMovingOperations: {- sourceCollectionID: string- destinationCollectionID?: string- reorderOperation: {- fromPath: string- toPath?: string- }-}[] = []--type OperationStatus = "pending" | "completed"--type OperationCollectionRemoved = {- type: "COLLECTION_REMOVED"- collectionBackendID: string- status: OperationStatus-}--export const restCollectionsOperations: Array<OperationCollectionRemoved> = []--export const storeSyncDefinition: StoreSyncDefinitionOf<- typeof restCollectionStore-> = {- async appendCollections({ entries }) {- if (entries.length === 0) return-- // Transform collections to backend format- const transformedCollections = entries.map(transformCollectionForBackend)-- // Use the bulk import API instead of individual calls- const jsonString = JSON.stringify(transformedCollections)-- const result = await importUserCollectionsFromJSON(- jsonString,- ReqType.Rest,- undefined // undefined for root collections- )-- // The backend handles creating all collections and requests in a single transaction- // The frontend collections will be updated through subscriptions-- if (E.isLeft(result)) {- // Fallback to individual calls if bulk import fails- let indexStart = restCollectionStore.value.state.length - entries.length-- entries.forEach((collection) => {- recursivelySyncCollections(collection, `${indexStart}`)- indexStart++- })- }- },- async addCollection({ collection }) {- // Use individual API for single collection creation (not import)- const lastCreatedCollectionIndex =- restCollectionStore.value.state.length - 1-- recursivelySyncCollections(collection, `${lastCreatedCollectionIndex}`)- },- async removeCollection({ collectionID }) {- if (collectionID) {- await deleteUserCollection(collectionID)- }- },- editCollection({ partialCollection: collection, collectionIndex }) {- const collectionID = navigateToFolderWithIndexPath(- restCollectionStore.value.state,- [collectionIndex]- )?.id-- const data = {- auth: collection.auth,- headers: collection.headers,- variables: stripSecretVariableValuesForWire(collection.variables ?? []),- _ref_id: collection._ref_id,- description: collection.description ?? null,- preRequestScript: collection.preRequestScript ?? "",- testScript: collection.testScript ?? "",- }-- if (collectionID) {- updateUserCollection(collectionID, collection.name, JSON.stringify(data))- }- },-- sortRESTCollection({ collectionPath, sortOrder }) {- // If collectionPath is empty, it means we're sorting the whole root collections else we're sorting a specific collection- const collectionID =- collectionPath !== null && collectionPath !== undefined- ? navigateToFolderWithIndexPath(restCollectionStore.value.state, [- collectionPath,- ])?.id- : null-- const order =- sortOrder === "asc" ? SortOptions.TitleAsc : SortOptions.TitleDesc-- sortUserCollections(collectionID ?? null, order)- },-- sortRESTFolder({ path, sortOrder }) {- const collectionID = navigateToFolderWithIndexPath(- restCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )?.id-- if (collectionID) {- const order =- sortOrder === "asc" ? SortOptions.TitleAsc : SortOptions.TitleDesc-- sortUserCollections(collectionID, order)- }- },- async addFolder({ name, path }) {- const parentCollection = navigateToFolderWithIndexPath(- restCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )-- const parentCollectionBackendID = parentCollection?.id-- if (parentCollectionBackendID) {- const res = await createRESTChildUserCollection(- name,- parentCollectionBackendID- )-- if (E.isRight(res)) {- const { id } = res.right.createRESTChildUserCollection-- // Always try to assign the ID to the last created folder- const foldersLength = parentCollection.folders.length- if (foldersLength > 0) {- const lastFolderIndex = foldersLength - 1- const lastFolder = parentCollection.folders[lastFolderIndex]-- // Only assign ID if the folder doesn't already have one (avoid overwriting)- if (!lastFolder.id) {- lastFolder.id = id- removeDuplicateRESTCollectionOrFolder(- id,- `${path}/${lastFolderIndex}`- )- }- }- }- }- },- editFolder({ folder, path }) {- const folderID = navigateToFolderWithIndexPath(- restCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )?.id-- const folderName = folder.name- const data = {- auth: folder.auth,- headers: folder.headers,- variables: stripSecretVariableValuesForWire(folder.variables ?? []),- _ref_id: folder._ref_id,- description: folder.description ?? null,- preRequestScript: folder.preRequestScript ?? "",- testScript: folder.testScript ?? "",- }- if (folderID) {- updateUserCollection(folderID, folderName, JSON.stringify(data))- }- },- async removeFolder({ folderID }) {- if (folderID) {- await deleteUserCollection(folderID)- }- },- async moveFolder({ destinationPath, path }) {- const { newSourcePath, newDestinationPath } = getPathsAfterMoving(- path,- destinationPath ?? undefined- )-- if (newSourcePath) {- const sourceCollectionID = navigateToFolderWithIndexPath(- restCollectionStore.value.state,- newSourcePath.split("/").map((index) => parseInt(index))- )?.id-- const destinationCollectionID = destinationPath- ? newDestinationPath &&- navigateToFolderWithIndexPath(- restCollectionStore.value.state,- newDestinationPath.split("/").map((index) => parseInt(index))- )?.id- : undefined-- if (sourceCollectionID) {- await moveUserCollection(sourceCollectionID, destinationCollectionID)- }- }- },- async duplicateCollection({ collectionSyncID }) {- if (collectionSyncID) {- await duplicateUserCollection(collectionSyncID, ReqType.Rest)- }- },- editRequest({ path, requestIndex, requestNew }) {- const request = navigateToFolderWithIndexPath(- restCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )?.requests[requestIndex]-- const requestBackendID = request?.id-- if (requestBackendID) {- editUserRequest(- requestBackendID,- (requestNew as HoppRESTRequest).name,- JSON.stringify(requestNew)- )- }- },- async saveRequestAs({ path, request }) {- const folder = navigateToFolderWithIndexPath(- restCollectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )-- const parentCollectionBackendID = folder?.id-- if (parentCollectionBackendID) {- const res = await createRESTUserRequest(- (request as HoppRESTRequest).name,- JSON.stringify(request),- parentCollectionBackendID- )-- if (E.isRight(res)) {- const { id } = res.right.createRESTUserRequest-- // Find the last request that doesn't have an ID (the newly added one)- const requestsLength = folder.requests.length- if (requestsLength > 0) {- const lastRequestIndex = requestsLength - 1- const lastRequest = folder.requests[lastRequestIndex]-- // Only assign ID if the request doesn't already have one- if (!lastRequest.id) {- lastRequest.id = id- removeDuplicateRESTCollectionOrFolder(- id,- `${path}/${lastRequestIndex}`,- "request"- )- }- }- }- }- },- async removeRequest({ requestID }) {- if (requestID) {- await deleteUserRequest(requestID)- }- },- moveRequest({ destinationPath, path, requestIndex }) {- moveOrReorderRequests(requestIndex, path, destinationPath)- },- updateRequestOrder({- destinationCollectionPath,- destinationRequestIndex,- requestIndex,- }) {- /**- * currently the FE implementation only supports reordering requests between the same collection,- * so destinationCollectionPath and sourceCollectionPath will be same- */- moveOrReorderRequests(- requestIndex,- destinationCollectionPath,- destinationCollectionPath,- destinationRequestIndex ?? undefined- )- },- async updateCollectionOrder({- collectionIndex: collectionPath,- destinationCollectionIndex: destinationCollectionPath,- }) {- const collections = restCollectionStore.value.state-- const sourcePathIndexes = getParentPathIndexesFromPath(collectionPath)- const sourceCollectionIndex = getCollectionIndexFromPath(collectionPath)-- const destinationCollectionIndex = !!destinationCollectionPath- ? getCollectionIndexFromPath(destinationCollectionPath)- : undefined-- let updatedCollectionIndexs:- | [newSourceIndex: number, newDestinationIndex: number | undefined]- | undefined-- if (- (sourceCollectionIndex || sourceCollectionIndex == 0) &&- (destinationCollectionIndex || destinationCollectionIndex == 0)- ) {- updatedCollectionIndexs = getIndexesAfterReorder(- sourceCollectionIndex,- destinationCollectionIndex- )- } else if (sourceCollectionIndex || sourceCollectionIndex == 0) {- if (sourcePathIndexes.length == 0) {- // we're reordering root collections- updatedCollectionIndexs = [collections.length - 1, undefined]- } else {- const sourceCollection = navigateToFolderWithIndexPath(collections, [- ...sourcePathIndexes,- ])-- if (sourceCollection && sourceCollection.folders.length > 0) {- updatedCollectionIndexs = [- sourceCollection.folders.length - 1,- undefined,- ]- }- }- }-- const sourceCollectionID =- updatedCollectionIndexs &&- navigateToFolderWithIndexPath(collections, [- ...sourcePathIndexes,- updatedCollectionIndexs[0],- ])?.id-- const destinationCollectionID =- updatedCollectionIndexs &&- (updatedCollectionIndexs[1] || updatedCollectionIndexs[1] == 0)- ? navigateToFolderWithIndexPath(collections, [- ...sourcePathIndexes,- updatedCollectionIndexs[1],- ])?.id- : undefined-- if (sourceCollectionID) {- await updateUserCollectionOrder(- sourceCollectionID,- destinationCollectionID- )- }- },-}--export const collectionsSyncer = getSyncInitFunction(- restCollectionStore,- storeSyncDefinition,- () => settingsStore.value.syncCollections,- getSettingSubject("syncCollections")-)--export async function moveOrReorderRequests(- requestIndex: number,- path: string,- destinationPath: string,- nextRequestIndex?: number,- requestType: "REST" | "GQL" = "REST"-) {- const { collectionStore } = getStoreByCollectionType(requestType)-- const sourceCollectionBackendID = navigateToFolderWithIndexPath(- collectionStore.value.state,- path.split("/").map((index) => parseInt(index))- )?.id-- const destinationCollection = navigateToFolderWithIndexPath(- collectionStore.value.state,- destinationPath.split("/").map((index) => parseInt(index))- )-- const destinationCollectionBackendID = destinationCollection?.id-- let requestBackendID: string | undefined-- let nextRequestBackendID: string | undefined-- // we only need this for reordering requests, not for moving requests- if (nextRequestIndex) {- // reordering- const [newRequestIndex, newDestinationIndex] = getIndexesAfterReorder(- requestIndex,- nextRequestIndex- )-- requestBackendID =- destinationCollection?.requests[newRequestIndex]?.id ?? undefined-- nextRequestBackendID =- destinationCollection?.requests[newDestinationIndex]?.id ?? undefined- } else {- // moving- const requests = destinationCollection?.requests- requestBackendID =- requests && requests.length > 0- ? requests[requests.length - 1]?.id- : undefined- }-- if (- sourceCollectionBackendID &&- destinationCollectionBackendID &&- requestBackendID- ) {- await moveUserRequest(- sourceCollectionBackendID,- destinationCollectionBackendID,- requestBackendID,- nextRequestBackendID- )- }-}--function getParentPathIndexesFromPath(path: string) {- const indexes = path.split("/")- indexes.pop()- return indexes.map((index) => parseInt(index))-}--export function getCollectionIndexFromPath(collectionPath: string) {- const sourceCollectionIndexString = collectionPath.split("/").pop()- const sourceCollectionIndex = sourceCollectionIndexString- ? parseInt(sourceCollectionIndexString)- : undefined-- return sourceCollectionIndex-}--/**- * the sync function is called after the reordering has happened on the store- * because of this we need to find the new source and destination indexes after the reordering- */-function getIndexesAfterReorder(- oldSourceIndex: number,- oldDestinationIndex: number-): [newSourceIndex: number, newDestinationIndex: number] {- // Source Becomes Destination -1- // Destination Remains Same- if (oldSourceIndex < oldDestinationIndex) {- return [oldDestinationIndex - 1, oldDestinationIndex]- }-- // Source Becomes The Destination- // Destintion Becomes Source + 1- if (oldSourceIndex > oldDestinationIndex) {- return [oldDestinationIndex, oldDestinationIndex + 1]- }-- throw new Error("Source and Destination are the same")-}--/**- * the sync function is called after moving a folder has happened on the store,- * because of this the source index given to the sync function is not the live one- * we need to find the new source index after the moving- */-function getPathsAfterMoving(sourcePath: string, destinationPath?: string) {- if (!destinationPath) {- return {- newSourcePath: `${restCollectionStore.value.state.length - 1}`,- newDestinationPath: destinationPath,- }- }-- const sourceParentPath = getParentPathFromPath(sourcePath)- const destinationParentPath = getParentPathFromPath(destinationPath)-- const isSameParentPath = sourceParentPath === destinationParentPath-- let newDestinationPath: string-- if (isSameParentPath) {- const sourceIndex = getCollectionIndexFromPath(sourcePath)- const destinationIndex = getCollectionIndexFromPath(destinationPath)-- if (- (sourceIndex || sourceIndex == 0) &&- (destinationIndex || destinationIndex == 0) &&- sourceIndex < destinationIndex- ) {- newDestinationPath = destinationParentPath- ? `${destinationParentPath}/${destinationIndex - 1}`- : `${destinationIndex - 1}`- } else {- newDestinationPath = destinationPath- }- } else {- newDestinationPath = destinationPath- }-- const destinationFolder = navigateToFolderWithIndexPath(- restCollectionStore.value.state,- newDestinationPath.split("/").map((index) => parseInt(index))- )-- const newSourcePath = destinationFolder- ? `${newDestinationPath}/${destinationFolder?.folders.length - 1}`- : undefined-- return {- newSourcePath,- newDestinationPath,- }-}--function getParentPathFromPath(path: string | undefined) {- const indexes = path ? path.split("/") : []- indexes.pop()-- return indexes.join("/")-}--export function getStoreByCollectionType(type: "GQL" | "REST") {- const isGQL = type == "GQL"-- const collectionStore = isGQL ? graphqlCollectionStore : restCollectionStore-- return { collectionStore }-}diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/web/index.ts b/packages/hoppscotch-selfhost-web/src/platform/collections/web/index.tsdeleted file mode 100644index 631fb3e9a..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/collections/web/index.ts+++ /dev/null@@ -1,1202 +0,0 @@-import { CollectionsPlatformDef } from "@hoppscotch/common/platform/collections"-import { authEvents$, def as platformAuth } from "@app/platform/auth/web"-import { runDispatchWithOutSyncing } from "@app/lib/sync"--import {- exportUserCollectionsToJSON,- runUserChildCollectionSortedSubscription,- runUserCollectionCreatedSubscription,- runUserCollectionDuplicatedSubscription,- runUserCollectionMovedSubscription,- runUserCollectionOrderUpdatedSubscription,- runUserCollectionRemovedSubscription,- runUserCollectionUpdatedSubscription,- runUserRequestCreatedSubscription,- runUserRequestDeletedSubscription,- runUserRequestMovedSubscription,- runUserRequestUpdatedSubscription,- runUserRootCollectionsSortedSubscription,-} from "./api"-import { collectionsSyncer, getStoreByCollectionType } from "./sync"--import {- ReqType,- UserCollectionDuplicatedData,- UserRequest,-} from "@app/api/generated/graphql"-import { runGQLSubscription } from "@hoppscotch/common/helpers/backend/GQLClient"-import {- addGraphqlCollection,- addGraphqlFolder,- addRESTCollection,- addRESTFolder,- editGraphqlCollection,- editGraphqlFolder,- editGraphqlRequest,- editRESTCollection,- editRESTFolder,- editRESTRequest,- moveGraphqlRequest,- moveRESTFolder,- moveRESTRequest,- navigateToFolderWithIndexPath,- removeGraphqlCollection,- removeGraphqlFolder,- removeGraphqlRequest,- removeRESTCollection,- removeRESTFolder,- removeRESTRequest,- restCollectionStore,- saveGraphqlRequestAs,- saveRESTRequestAs,- setGraphqlCollections,- setRESTCollections,- sortRESTCollection,- sortRESTFolder,- updateRESTCollectionOrder,- updateRESTRequestOrder,-} from "@hoppscotch/common/newstore/collections"-import {- generateUniqueRefId,- GQLHeader,- HoppCollection,- HoppGQLRequest,- HoppRESTHeaders,- HoppRESTParam,- HoppRESTRequest,-} from "@hoppscotch/data"-import * as E from "fp-ts/Either"-import { gqlCollectionsSyncer } from "./gqlCollections.sync"-import { importToPersonalWorkspace } from "./import"--function initCollectionsSync() {- const currentUser$ = platformAuth.getCurrentUserStream()- collectionsSyncer.startStoreSync()- collectionsSyncer.setupSubscriptions(setupSubscriptions)-- gqlCollectionsSyncer.startStoreSync()-- // TODO: fix collection schema transformation on backend maybe?- loadUserCollections("REST")- loadUserCollections("GQL")-- // TODO: test & make sure the auth thing is working properly- currentUser$.subscribe(async (user) => {- if (user) {- loadUserCollections("REST")- loadUserCollections("GQL")- }- })-- authEvents$.subscribe((event) => {- if (event.event == "login" || event.event == "token_refresh") {- collectionsSyncer.startListeningToSubscriptions()- }-- if (event.event == "logout") {- collectionsSyncer.stopListeningToSubscriptions()- }- })-}--export type ExportedUserCollectionREST = {- id?: string- _ref_id?: string- folders: ExportedUserCollectionREST[]- requests: Array<HoppRESTRequest & { id: string }>- name: string- data: string-}--export type ExportedUserCollectionGQL = {- id?: string- _ref_id?: string- folders: ExportedUserCollectionGQL[]- requests: Array<HoppGQLRequest & { id: string }>- name: string- data: string-}--function addDescriptionField(- candidate: HoppRESTHeaders | GQLHeader[] | HoppRESTParam[]-) {- return candidate.map((item) => ({- ...item,- description: "description" in item ? item.description : "",- }))-}--export function exportedCollectionToHoppCollection(- collection: ExportedUserCollectionREST | ExportedUserCollectionGQL,- collectionType: "REST" | "GQL"-): HoppCollection {- if (collectionType == "REST") {- const restCollection = collection as ExportedUserCollectionREST-- const data =- restCollection.data && restCollection.data !== "null"- ? JSON.parse(restCollection.data)- : {- auth: { authType: "inherit", authActive: true },- headers: [],- _ref_id: generateUniqueRefId("coll"),- variables: [],- description: null,- preRequestScript: "",- testScript: "",- }-- return {- id: restCollection.id,- _ref_id: data._ref_id ?? generateUniqueRefId("coll"),- v: 12,- name: restCollection.name,- folders: restCollection.folders.map((folder) =>- exportedCollectionToHoppCollection(folder, collectionType)- ),- requests: restCollection.requests.map((request) => {- const requestParsedResult = HoppRESTRequest.safeParse(request)- if (requestParsedResult.type === "ok") {- return requestParsedResult.value- }-- const {- v,- id,- auth,- body,- endpoint,- headers,- method,- name,- params,- preRequestScript,- testScript,- requestVariables,- responses,- description,- _ref_id,- } = request-- const resolvedParams = addDescriptionField(params)- const resolvedHeaders = addDescriptionField(headers)-- return {- v,- id,- name,- endpoint,- method,- params: resolvedParams,- requestVariables,- auth,- headers: resolvedHeaders,- body,- preRequestScript,- testScript,- responses,- description: description ?? null,- _ref_id: _ref_id ?? generateUniqueRefId("req"),- }- }),- description: data.description ?? null,- auth: data.auth,- headers: addDescriptionField(data.headers),- variables: data.variables ?? [],- preRequestScript: data.preRequestScript ?? "",- testScript: data.testScript ?? "",- }- } else {- const gqlCollection = collection as ExportedUserCollectionGQL-- const data =- gqlCollection.data && gqlCollection.data !== "null"- ? JSON.parse(gqlCollection.data)- : {- auth: { authType: "inherit", authActive: true },- headers: [],- _ref_id: generateUniqueRefId("coll"),- variables: [],- description: null,- }-- return {- id: gqlCollection.id,- _ref_id: data._ref_id ?? generateUniqueRefId("coll"),- v: 12,- name: gqlCollection.name,- folders: gqlCollection.folders.map((folder) =>- exportedCollectionToHoppCollection(folder, collectionType)- ),- requests: gqlCollection.requests.map((request) => {- const requestParsedResult = HoppGQLRequest.safeParse(request)- if (requestParsedResult.type === "ok") {- return requestParsedResult.value- }-- const { v, auth, headers, name, id, query, url, variables } = request-- const resolvedHeaders = addDescriptionField(headers)-- return {- id,- v,- auth,- headers: resolvedHeaders,- name,- query,- url,- variables,- }- }),- auth: data.auth,- headers: addDescriptionField(data.headers),- variables: data.variables ?? [],- description: data.description ?? null,- preRequestScript: data.preRequestScript ?? "",- testScript: data.testScript ?? "",- }- }-}--async function loadUserCollections(collectionType: "REST" | "GQL") {- const res = await exportUserCollectionsToJSON(- undefined,- collectionType == "REST" ? ReqType.Rest : ReqType.Gql- )- if (E.isRight(res)) {- const collectionsJSONString =- res.right.exportUserCollectionsToJSON.exportedCollection- const exportedCollections = (- JSON.parse(collectionsJSONString) as Array<- ExportedUserCollectionGQL | ExportedUserCollectionREST- >- ).map((collection) => ({ v: 1, ...collection }))- runDispatchWithOutSyncing(() => {- collectionType == "REST"- ? setRESTCollections(- exportedCollections.map(- (collection) =>- exportedCollectionToHoppCollection(- collection,- "REST"- ) as HoppCollection- )- )- : setGraphqlCollections(- exportedCollections.map(- (collection) =>- exportedCollectionToHoppCollection(- collection,- "GQL"- ) as HoppCollection- )- )- })- }-}--function setupSubscriptions() {- let subs: ReturnType<typeof runGQLSubscription>[1][] = []-- const userCollectionCreatedSub = setupUserCollectionCreatedSubscription()- const userCollectionUpdatedSub = setupUserCollectionUpdatedSubscription()- const userCollectionRemovedSub = setupUserCollectionRemovedSubscription()- const userCollectionMovedSub = setupUserCollectionMovedSubscription()- const userCollectionOrderUpdatedSub =- setupUserCollectionOrderUpdatedSubscription()- const userCollectionDuplicatedSub =- setupUserCollectionDuplicatedSubscription()- const userRootCollectionsSortedSub =- setupUserRootCollectionsSortedSubscription()- const userChildCollectionSortedSub =- setupUserChildCollectionSortedSubscription()-- const userRequestCreatedSub = setupUserRequestCreatedSubscription()- const userRequestUpdatedSub = setupUserRequestUpdatedSubscription()- const userRequestDeletedSub = setupUserRequestDeletedSubscription()- const userRequestMovedSub = setupUserRequestMovedSubscription()-- subs = [- userCollectionCreatedSub,- userCollectionUpdatedSub,- userCollectionRemovedSub,- userCollectionMovedSub,- userCollectionOrderUpdatedSub,- userCollectionDuplicatedSub,- userRootCollectionsSortedSub,- userChildCollectionSortedSub,- userRequestCreatedSub,- userRequestUpdatedSub,- userRequestDeletedSub,- userRequestMovedSub,- ]-- return () => {- subs.forEach((sub) => sub.unsubscribe())- }-}--function setupUserCollectionCreatedSubscription() {- const [userCollectionCreated$, userCollectionCreatedSub] =- runUserCollectionCreatedSubscription()-- userCollectionCreated$.subscribe((res) => {- if (E.isRight(res)) {- const collectionType = res.right.userCollectionCreated.type-- const { collectionStore } = getStoreByCollectionType(collectionType)-- const userCollectionBackendID = res.right.userCollectionCreated.id- const parentCollectionID = res.right.userCollectionCreated.parent?.id-- const userCollectionLocalID = getCollectionPathFromCollectionID(- userCollectionBackendID,- collectionStore.value.state- )-- // collection already exists in store ( this instance created it )- if (userCollectionLocalID) {- return- }-- const parentCollectionPath =- parentCollectionID &&- getCollectionPathFromCollectionID(- parentCollectionID,- collectionStore.value.state- )-- // only folders will have parent collection id- if (parentCollectionID && parentCollectionPath) {- runDispatchWithOutSyncing(() => {- collectionType == "GQL"- ? addGraphqlFolder(- res.right.userCollectionCreated.title,- parentCollectionPath- )- : addRESTFolder(- res.right.userCollectionCreated.title,- parentCollectionPath- )-- const parentCollection = navigateToFolderWithIndexPath(- collectionStore.value.state,- parentCollectionPath- .split("/")- .map((pathIndex) => parseInt(pathIndex))- )-- if (parentCollection) {- const folderIndex = parentCollection.folders.length - 1-- const addedFolder = parentCollection.folders[folderIndex]- addedFolder.id = userCollectionBackendID- }- })- } else {- // root collections won't have parentCollectionID- const data =- res.right.userCollectionCreated.data &&- res.right.userCollectionCreated.data != "null"- ? JSON.parse(res.right.userCollectionCreated.data)- : {- auth: { authType: "inherit", authActive: true },- headers: [],- _ref_id: generateUniqueRefId("coll"),- variables: [],- description: null,- preRequestScript: "",- testScript: "",- }-- runDispatchWithOutSyncing(() => {- collectionType == "GQL"- ? addGraphqlCollection({- name: res.right.userCollectionCreated.title,- folders: [],- requests: [],- v: 12,- _ref_id: data._ref_id,- auth: data.auth,- headers: addDescriptionField(data.headers),- variables: data.variables ?? [],- description: data.description ?? null,- preRequestScript: data.preRequestScript ?? "",- testScript: data.testScript ?? "",- })- : addRESTCollection({- name: res.right.userCollectionCreated.title,- folders: [],- requests: [],- v: 12,- _ref_id: data._ref_id,- auth: data.auth,- headers: addDescriptionField(data.headers),- variables: data.variables ?? [],- description: data.description ?? null,- preRequestScript: data.preRequestScript ?? "",- testScript: data.testScript ?? "",- })-- const localIndex = collectionStore.value.state.length - 1-- const addedCollection = collectionStore.value.state[localIndex]- addedCollection.id = userCollectionBackendID- })- }- }- })-- return userCollectionCreatedSub-}--function setupUserCollectionUpdatedSubscription() {- const [userCollectionUpdated$, userCollectionUpdatedSub] =- runUserCollectionUpdatedSubscription()-- userCollectionUpdated$.subscribe((res) => {- if (E.isRight(res)) {- const collectionType = res.right.userCollectionUpdated.type-- const { collectionStore } = getStoreByCollectionType(collectionType)-- const updatedCollectionBackendID = res.right.userCollectionUpdated.id- const updatedCollectionLocalPath = getCollectionPathFromCollectionID(- updatedCollectionBackendID,- collectionStore.value.state- )-- const isFolder =- updatedCollectionLocalPath &&- updatedCollectionLocalPath.split("/").length > 1-- // updated collection is a folder- if (isFolder) {- runDispatchWithOutSyncing(() => {- collectionType == "REST"- ? editRESTFolder(updatedCollectionLocalPath, {- name: res.right.userCollectionUpdated.title,- })- : editGraphqlFolder(updatedCollectionLocalPath, {- name: res.right.userCollectionUpdated.title,- })- })- }-- // updated collection is a root collection- if (updatedCollectionLocalPath && !isFolder) {- runDispatchWithOutSyncing(() => {- collectionType == "REST"- ? editRESTCollection(parseInt(updatedCollectionLocalPath), {- name: res.right.userCollectionUpdated.title,- })- : editGraphqlCollection(parseInt(updatedCollectionLocalPath), {- name: res.right.userCollectionUpdated.title,- })- })- }- }- })-- return userCollectionUpdatedSub-}--function setupUserCollectionMovedSubscription() {- const [userCollectionMoved$, userCollectionMovedSub] =- runUserCollectionMovedSubscription()-- userCollectionMoved$.subscribe((res) => {- if (E.isRight(res)) {- const movedMetadata = res.right.userCollectionMoved-- const sourcePath = getCollectionPathFromCollectionID(- movedMetadata.id,- restCollectionStore.value.state- )-- let destinationPath: string | undefined-- if (movedMetadata.parent?.id) {- destinationPath =- getCollectionPathFromCollectionID(- movedMetadata.parent?.id,- restCollectionStore.value.state- ) ?? undefined- }-- sourcePath &&- runDispatchWithOutSyncing(() => {- moveRESTFolder(sourcePath, destinationPath ?? null)- })- }- })-- return userCollectionMovedSub-}--function setupUserCollectionRemovedSubscription() {- const [userCollectionRemoved$, userCollectionRemovedSub] =- runUserCollectionRemovedSubscription()-- userCollectionRemoved$.subscribe((res) => {- if (E.isRight(res)) {- const removedCollectionBackendID = res.right.userCollectionRemoved.id- const collectionType = res.right.userCollectionRemoved.type-- const { collectionStore } = getStoreByCollectionType(collectionType)-- const removedCollectionLocalPath = getCollectionPathFromCollectionID(- removedCollectionBackendID,- collectionStore.value.state- )-- const isFolder =- removedCollectionLocalPath &&- removedCollectionLocalPath.split("/").length > 1-- if (removedCollectionLocalPath && isFolder) {- runDispatchWithOutSyncing(() => {- collectionType == "REST"- ? removeRESTFolder(removedCollectionLocalPath)- : removeGraphqlFolder(removedCollectionLocalPath)- })- }-- if (removedCollectionLocalPath && !isFolder) {- runDispatchWithOutSyncing(() => {- collectionType == "REST"- ? removeRESTCollection(parseInt(removedCollectionLocalPath))- : removeGraphqlCollection(parseInt(removedCollectionLocalPath))- })- }- }- })-- return userCollectionRemovedSub-}--function setupUserCollectionOrderUpdatedSubscription() {- const [userCollectionOrderUpdated$, userCollectionOrderUpdatedSub] =- runUserCollectionOrderUpdatedSubscription()-- userCollectionOrderUpdated$.subscribe((res) => {- if (E.isRight(res)) {- const { userCollection, nextUserCollection } =- res.right.userCollectionOrderUpdated-- const sourceCollectionID = userCollection.id- const destinationCollectionID = nextUserCollection?.id-- const sourcePath = getCollectionPathFromCollectionID(- sourceCollectionID,- restCollectionStore.value.state- )-- let destinationPath: string | null | undefined-- if (destinationCollectionID) {- destinationPath = getCollectionPathFromCollectionID(- destinationCollectionID,- restCollectionStore.value.state- )- }-- runDispatchWithOutSyncing(() => {- if (sourcePath) {- updateRESTCollectionOrder(sourcePath, destinationPath ?? null)- }- })- }- })-- return userCollectionOrderUpdatedSub-}--function setupUserCollectionDuplicatedSubscription() {- const [userCollectionDuplicated$, userCollectionDuplicatedSub] =- runUserCollectionDuplicatedSubscription()-- userCollectionDuplicated$.subscribe((res) => {- if (E.isRight(res)) {- const {- childCollections: childCollectionsJSONStr,- data,- id,- parentID: parentCollectionID,- requests: userRequests,- title: name,- type: collectionType,- } = res.right.userCollectionDuplicated-- const { collectionStore } = getStoreByCollectionType(collectionType)-- const parentCollectionPath =- parentCollectionID &&- getCollectionPathFromCollectionID(- parentCollectionID,- collectionStore.value.state- )-- // Incoming data transformed to the respective internal representations- const {- auth,- headers,- variables,- description,- preRequestScript,- testScript,- } =- data && data != "null"- ? JSON.parse(data)- : {- auth: { authType: "inherit", authActive: true },- headers: [],- variables: [],- description: null,- preRequestScript: "",- testScript: "",- }- // Duplicated collection will have a unique ref id- const _ref_id = generateUniqueRefId("coll")-- const folders = transformDuplicatedCollections(childCollectionsJSONStr)-- const requests = transformDuplicatedCollectionRequests(- userRequests as UserRequest[]- )-- // New collection to be added to store with the transformed data- const effectiveDuplicatedCollection: HoppCollection = {- id,- name,- folders,- requests,- v: 12,- _ref_id,- auth,- headers: addDescriptionField(headers),- variables: variables ?? [],- description: description ?? null,- preRequestScript: preRequestScript ?? "",- testScript: testScript ?? "",- }-- // only folders will have parent collection id- if (parentCollectionID && parentCollectionPath) {- const collectionCreatedFromStoreIDSuffix = "-duplicate-collection"-- const parentCollection = navigateToFolderWithIndexPath(- collectionStore.value.state,- parentCollectionPath- .split("/")- .map((pathIndex) => parseInt(pathIndex))- )-- if (!parentCollection) {- return- }-- // Grab the child collection inserted via store update with the ID suffix- const collectionInsertedViaStoreUpdateIdx =- parentCollection.folders.findIndex(({ id }) =>- id?.endsWith(collectionCreatedFromStoreIDSuffix)- )-- if (collectionInsertedViaStoreUpdateIdx === -1) {- return- }-- const collectionInsertedViaStoreUpdateIndexPath = `${parentCollectionPath}/${collectionInsertedViaStoreUpdateIdx}`-- runDispatchWithOutSyncing(() => {- /**- * Step 1. Remove the collection inserted via store update with the ID suffix- * Step 2. Add the duplicated collection received from the GQL subscription- * Step 3. Update the duplicated collection with the relevant data- */-- if (collectionType === "GQL") {- removeGraphqlFolder(collectionInsertedViaStoreUpdateIndexPath)-- addGraphqlFolder(name, parentCollectionPath)-- editGraphqlFolder(- collectionInsertedViaStoreUpdateIndexPath,- effectiveDuplicatedCollection- )- } else {- removeRESTFolder(collectionInsertedViaStoreUpdateIndexPath)-- addRESTFolder(name, parentCollectionPath)-- editRESTFolder(- collectionInsertedViaStoreUpdateIndexPath,- effectiveDuplicatedCollection- )- }- })- } else {- // root collections won't have `parentCollectionID`- const collectionCreatedFromStoreIDSuffix = "-duplicate-collection"-- // Grab the child collection inserted via store update with the ID suffix- const collectionInsertedViaStoreUpdateIdx =- collectionStore.value.state.findIndex(({ id }) =>- id?.endsWith(collectionCreatedFromStoreIDSuffix)- )-- if (collectionInsertedViaStoreUpdateIdx === -1) {- return- }-- runDispatchWithOutSyncing(() => {- /**- * Step 1. Remove the collection inserted via store update with the ID suffix- * Step 2. Add the duplicated collection received from the GQL subscription- */- if (collectionType === "GQL") {- removeGraphqlCollection(collectionInsertedViaStoreUpdateIdx)-- addGraphqlCollection(effectiveDuplicatedCollection)- } else {- removeRESTCollection(collectionInsertedViaStoreUpdateIdx)-- addRESTCollection(effectiveDuplicatedCollection)- }- })- }- }- })-- return userCollectionDuplicatedSub-}--const setupUserRootCollectionsSortedSubscription = () => {- const [userRootCollectionsSorted$, userRootCollectionsSortedSub] =- runUserRootCollectionsSortedSubscription()-- userRootCollectionsSorted$.subscribe((res) => {- if (E.isRight(res)) {- runDispatchWithOutSyncing(() => {- if (res.right.userRootCollectionsSorted) {- const { sortOption } = res.right.userRootCollectionsSorted-- const sortOrder = sortOption === "TITLE_ASC" ? "asc" : "desc"-- sortRESTCollection(null, sortOrder)- }- })- }- })- return userRootCollectionsSortedSub-}--const setupUserChildCollectionSortedSubscription = () => {- const [userChildCollectionSorted$, userChildCollectionSortedSub] =- runUserChildCollectionSortedSubscription()-- userChildCollectionSorted$.subscribe((res) => {- if (E.isRight(res)) {- runDispatchWithOutSyncing(() => {- if (res.right.userChildCollectionsSorted) {- const { parentCollectionID, sortOption } =- res.right.userChildCollectionsSorted-- if (!parentCollectionID) return-- const sortOrder = sortOption === "TITLE_ASC" ? "asc" : "desc"-- const sourcePath = getCollectionPathFromCollectionID(- parentCollectionID,- restCollectionStore.value.state- )-- if (!sourcePath) return-- sortRESTFolder(sourcePath, sortOrder)- }- })- }- })- return userChildCollectionSortedSub-}--function setupUserRequestCreatedSubscription() {- const [userRequestCreated$, userRequestCreatedSub] =- runUserRequestCreatedSubscription()-- userRequestCreated$.subscribe((res) => {- if (E.isRight(res)) {- const collectionID = res.right.userRequestCreated.collectionID- const request = JSON.parse(res.right.userRequestCreated.request)- const requestID = res.right.userRequestCreated.id-- const requestType = res.right.userRequestCreated.type-- const { collectionStore } = getStoreByCollectionType(requestType)-- const hasAlreadyHappened = getRequestPathFromRequestID(- requestID,- collectionStore.value.state- )-- if (!!hasAlreadyHappened) {- return- }-- const collectionPath = getCollectionPathFromCollectionID(- collectionID,- collectionStore.value.state- )-- if (collectionID && collectionPath) {- runDispatchWithOutSyncing(() => {- requestType == "REST"- ? saveRESTRequestAs(collectionPath, request)- : saveGraphqlRequestAs(collectionPath, request)-- const target = navigateToFolderWithIndexPath(- collectionStore.value.state,- collectionPath.split("/").map((index) => parseInt(index))- )-- const targetRequest = target?.requests[target?.requests.length - 1]-- if (targetRequest) {- targetRequest.id = requestID- }- })- }- }- })-- return userRequestCreatedSub-}--function setupUserRequestUpdatedSubscription() {- const [userRequestUpdated$, userRequestUpdatedSub] =- runUserRequestUpdatedSubscription()-- userRequestUpdated$.subscribe((res) => {- if (E.isRight(res)) {- const requestType = res.right.userRequestUpdated.type-- const { collectionStore } = getStoreByCollectionType(requestType)-- const requestPath = getRequestPathFromRequestID(- res.right.userRequestUpdated.id,- collectionStore.value.state- )-- const collectionPath = requestPath?.collectionPath- const requestIndex = requestPath?.requestIndex-- ;(requestIndex || requestIndex == 0) &&- collectionPath &&- runDispatchWithOutSyncing(() => {- requestType == "REST"- ? editRESTRequest(- collectionPath,- requestIndex,- JSON.parse(res.right.userRequestUpdated.request)- )- : editGraphqlRequest(- collectionPath,- requestIndex,- JSON.parse(res.right.userRequestUpdated.request)- )- })- }- })-- return userRequestUpdatedSub-}--function setupUserRequestMovedSubscription() {- const [userRequestMoved$, userRequestMovedSub] =- runUserRequestMovedSubscription()-- userRequestMoved$.subscribe((res) => {- if (E.isRight(res)) {- const { request, nextRequest } = res.right.userRequestMoved-- const {- collectionID: destinationCollectionID,- id: sourceRequestID,- type: requestType,- } = request-- const { collectionStore } = getStoreByCollectionType(requestType)-- const sourceRequestPath = getRequestPathFromRequestID(- sourceRequestID,- collectionStore.value.state- )-- const destinationCollectionPath = getCollectionPathFromCollectionID(- destinationCollectionID,- collectionStore.value.state- )-- const destinationRequestIndex = destinationCollectionPath- ? (() => {- const requestsLength = navigateToFolderWithIndexPath(- collectionStore.value.state,- destinationCollectionPath- .split("/")- .map((index) => parseInt(index))- )?.requests.length-- return requestsLength || requestsLength == 0- ? requestsLength - 1- : undefined- })()- : undefined-- // there is no nextRequest, so request is moved- if (- (destinationRequestIndex || destinationRequestIndex == 0) &&- destinationCollectionPath &&- sourceRequestPath &&- !nextRequest- ) {- runDispatchWithOutSyncing(() => {- requestType == "REST"- ? moveRESTRequest(- sourceRequestPath.collectionPath,- sourceRequestPath.requestIndex,- destinationCollectionPath- )- : moveGraphqlRequest(- sourceRequestPath.collectionPath,- sourceRequestPath.requestIndex,- destinationCollectionPath- )- })- }-- // there is nextRequest, so request is reordered- if (- (destinationRequestIndex || destinationRequestIndex == 0) &&- destinationCollectionPath &&- nextRequest &&- // we don't have request reordering for graphql yet- requestType == "REST"- ) {- const { collectionID: nextCollectionID, id: nextRequestID } =- nextRequest-- const nextCollectionPath =- getCollectionPathFromCollectionID(- nextCollectionID,- collectionStore.value.state- ) ?? undefined-- const nextRequestIndex = nextCollectionPath- ? getRequestIndex(- nextRequestID,- nextCollectionPath,- collectionStore.value.state- )- : undefined-- nextRequestIndex &&- nextCollectionPath &&- sourceRequestPath &&- runDispatchWithOutSyncing(() => {- updateRESTRequestOrder(- sourceRequestPath?.requestIndex,- nextRequestIndex,- nextCollectionPath- )- })- }- }- })-- return userRequestMovedSub-}--function setupUserRequestDeletedSubscription() {- const [userRequestDeleted$, userRequestDeletedSub] =- runUserRequestDeletedSubscription()-- userRequestDeleted$.subscribe((res) => {- if (E.isRight(res)) {- const requestType = res.right.userRequestDeleted.type-- const { collectionStore } = getStoreByCollectionType(requestType)-- const deletedRequestPath = getRequestPathFromRequestID(- res.right.userRequestDeleted.id,- collectionStore.value.state- )-- ;(deletedRequestPath?.requestIndex ||- deletedRequestPath?.requestIndex == 0) &&- deletedRequestPath.collectionPath &&- runDispatchWithOutSyncing(() => {- requestType == "REST"- ? removeRESTRequest(- deletedRequestPath.collectionPath,- deletedRequestPath.requestIndex- )- : removeGraphqlRequest(- deletedRequestPath.collectionPath,- deletedRequestPath.requestIndex- )- })- }- })-- return userRequestDeletedSub-}--export const def: CollectionsPlatformDef = {- initCollectionsSync,- loadUserCollections,- importToPersonalWorkspace,-}--function getCollectionPathFromCollectionID(- collectionID: string,- collections: HoppCollection[],- parentPath?: string-): string | null {- for (const collectionIndex in collections) {- if (collections[collectionIndex].id == collectionID) {- return parentPath- ? `${parentPath}/${collectionIndex}`- : `${collectionIndex}`- } else {- const collectionPath = getCollectionPathFromCollectionID(- collectionID,- collections[collectionIndex].folders,- parentPath ? `${parentPath}/${collectionIndex}` : `${collectionIndex}`- )-- if (collectionPath) return collectionPath- }- }-- return null-}--function getRequestPathFromRequestID(- requestID: string,- collections: HoppCollection[],- parentPath?: string-): { collectionPath: string; requestIndex: number } | null {- for (const collectionIndex in collections) {- const requestIndex = collections[collectionIndex].requests.findIndex(- (request) => request.id == requestID- )-- if (requestIndex != -1) {- return {- collectionPath: parentPath- ? `${parentPath}/${collectionIndex}`- : `${collectionIndex}`,- requestIndex,- }- } else {- const requestPath = getRequestPathFromRequestID(- requestID,- collections[collectionIndex].folders,- parentPath ? `${parentPath}/${collectionIndex}` : `${collectionIndex}`- )-- if (requestPath) return requestPath- }- }-- return null-}--function getRequestIndex(- requestID: string,- parentCollectionPath: string,- collections: HoppCollection[]-) {- const collection = navigateToFolderWithIndexPath(- collections,- parentCollectionPath?.split("/").map((index) => parseInt(index))- )-- const requestIndex = collection?.requests.findIndex(- (request) => request.id == requestID- )-- return requestIndex-}--function transformDuplicatedCollections(- collectionsJSONStr: string-): HoppCollection[] {- const parsedCollections: UserCollectionDuplicatedData[] =- JSON.parse(collectionsJSONStr)-- return parsedCollections.map(- ({- childCollections: childCollectionsJSONStr,- data,- id,- requests: userRequests,- title: name,- }) => {- const {- auth,- headers,- variables,- description,- preRequestScript,- testScript,- } =- data && data !== "null"- ? JSON.parse(data)- : {- auth: { authType: "inherit", authActive: true },- headers: [],- variables: [],- description: null,- preRequestScript: "",- testScript: "",- }-- const _ref_id = generateUniqueRefId("coll")-- const folders = transformDuplicatedCollections(childCollectionsJSONStr)-- const requests = transformDuplicatedCollectionRequests(userRequests)-- return {- id,- name,- folders,- requests,- _ref_id,- v: 12,- auth,- headers: addDescriptionField(headers),- variables: variables ?? [],- description: description ?? null,- preRequestScript: preRequestScript ?? "",- testScript: testScript ?? "",- }- }- )-}--function transformDuplicatedCollectionRequests(- requests: UserRequest[]-): HoppRESTRequest[] | HoppGQLRequest[] {- return requests.map(({ id, request }) => {- const parsedRequest = JSON.parse(request)-- return {- ...parsedRequest,- id,- }- })-}diff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/api.ts b/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/api.tsdeleted file mode 100644index 31ddd9921..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/api.ts+++ /dev/null@@ -1,121 +0,0 @@-import {- runMutation,- runGQLQuery,- runGQLSubscription,-} from "@helpers/backend/GQLClient"--import {- CreateUserEnvironmentDocument,- CreateUserEnvironmentMutation,- CreateUserEnvironmentMutationVariables,- UpdateUserEnvironmentMutation,- UpdateUserEnvironmentMutationVariables,- UpdateUserEnvironmentDocument,- DeleteUserEnvironmentMutation,- DeleteUserEnvironmentMutationVariables,- DeleteUserEnvironmentDocument,- ClearGlobalEnvironmentsMutation,- ClearGlobalEnvironmentsMutationVariables,- ClearGlobalEnvironmentsDocument,- CreateUserGlobalEnvironmentMutation,- CreateUserGlobalEnvironmentMutationVariables,- CreateUserGlobalEnvironmentDocument,- GetGlobalEnvironmentsDocument,- GetGlobalEnvironmentsQueryVariables,- GetGlobalEnvironmentsQuery,- GetUserEnvironmentsDocument,- UserEnvironmentCreatedDocument,- UserEnvironmentUpdatedDocument,- UserEnvironmentDeletedDocument,-} from "@app/api/generated/graphql"--export const createUserEnvironment = (name: string, variables: string) =>- runMutation<- CreateUserEnvironmentMutation,- CreateUserEnvironmentMutationVariables,- ""- >(CreateUserEnvironmentDocument, {- name,- variables,- })()--// `variables` is the pre-stringified JSON payload — callers decide which-// shape to serialise (a bare `Environment.variables` array for regular-// envs, a `GlobalEnvironment` wrapper `{ v, variables }` for the global-// env). Mirrors `createUserEnvironment` and lets the global-env caller-// preserve the wrapper shape on the wire without a union type / cast.-export const updateUserEnvironment = (- id: string,- name: string,- variables: string-) =>- runMutation<- UpdateUserEnvironmentMutation,- UpdateUserEnvironmentMutationVariables,- ""- >(UpdateUserEnvironmentDocument, {- id,- name,- variables,- })--export const deleteUserEnvironment = (id: string) =>- runMutation<- DeleteUserEnvironmentMutation,- DeleteUserEnvironmentMutationVariables,- ""- >(DeleteUserEnvironmentDocument, {- id,- })--export const clearGlobalEnvironmentVariables = (id: string) =>- runMutation<- ClearGlobalEnvironmentsMutation,- ClearGlobalEnvironmentsMutationVariables,- ""- >(ClearGlobalEnvironmentsDocument, {- id,- })()--export const getUserEnvironments = () =>- runGQLQuery({- query: GetUserEnvironmentsDocument,- variables: {},- })--export const getGlobalEnvironments = () =>- runGQLQuery<- GetGlobalEnvironmentsQuery,- GetGlobalEnvironmentsQueryVariables,- "user_environment/user_env_does_not_exists"- >({- query: GetGlobalEnvironmentsDocument,- variables: {},- })--export const createUserGlobalEnvironment = (variables: string) =>- runMutation<- CreateUserGlobalEnvironmentMutation,- CreateUserGlobalEnvironmentMutationVariables,- ""- >(CreateUserGlobalEnvironmentDocument, {- variables,- })()--export const runUserEnvironmentCreatedSubscription = () =>- runGQLSubscription({- query: UserEnvironmentCreatedDocument,- variables: {},- })--export const runUserEnvironmentUpdatedSubscription = () =>- runGQLSubscription({- query: UserEnvironmentUpdatedDocument,- variables: {},- })--export const runUserEnvironmentDeletedSubscription = () =>- runGQLSubscription({- query: UserEnvironmentDeletedDocument,- variables: {},- })diff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/index.ts b/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/index.tsdeleted file mode 100644index 251f9650a..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/index.ts+++ /dev/null@@ -1,251 +0,0 @@-import { authEvents$, def as platformAuth } from "@app/platform/auth/desktop"-import { entityReference } from "verzod"--import {- createEnvironment,- deleteEnvironment,- environmentsStore,- getLocalIndexByEnvironmentID,- replaceEnvironments,- setGlobalEnvID,- setGlobalEnvVariables,- updateEnvironment,-} from "@hoppscotch/common/newstore/environments"--import { EnvironmentsPlatformDef } from "@hoppscotch/common/src/platform/environments"-import { runGQLSubscription } from "@hoppscotch/common/helpers/backend/GQLClient"--import { environnmentsSyncer } from "@app/platform/environments/desktop/sync"--import * as E from "fp-ts/Either"-import {- Environment,- EnvironmentSchemaVersion,- GlobalEnvironment,-} from "@hoppscotch/data"-import { runDispatchWithOutSyncing } from "@app/lib/sync"-import {- createUserGlobalEnvironment,- getGlobalEnvironments,- getUserEnvironments,- runUserEnvironmentCreatedSubscription,- runUserEnvironmentDeletedSubscription,- runUserEnvironmentUpdatedSubscription,-} from "./api"--export function initEnvironmentsSync() {- const currentUser$ = platformAuth.getCurrentUserStream()-- environnmentsSyncer.startStoreSync()- environnmentsSyncer.setupSubscriptions(setupSubscriptions)-- currentUser$.subscribe(async (user) => {- if (user) {- await loadAllEnvironments()- }- })-- authEvents$.subscribe((event) => {- if (event.event == "login" || event.event == "token_refresh") {- environnmentsSyncer.startListeningToSubscriptions()- }-- if (event.event == "logout") {- environnmentsSyncer.stopListeningToSubscriptions()- }- })-}--export const def: EnvironmentsPlatformDef = {- initEnvironmentsSync,-}--function setupSubscriptions() {- let subs: ReturnType<typeof runGQLSubscription>[1][] = []-- const userEnvironmentCreatedSub = setupUserEnvironmentCreatedSubscription()- const userEnvironmentUpdatedSub = setupUserEnvironmentUpdatedSubscription()- const userEnvironmentDeletedSub = setupUserEnvironmentDeletedSubscription()-- subs = [- userEnvironmentCreatedSub,- userEnvironmentUpdatedSub,- userEnvironmentDeletedSub,- ]-- return () => {- subs.forEach((sub) => sub.unsubscribe())- }-}--async function loadUserEnvironments() {- const res = await getUserEnvironments()-- if (E.isRight(res)) {- const environments = res.right.me.environments-- if (environments.length > 0) {- runDispatchWithOutSyncing(() => {- const formatedEnvironments = environments.map(- (env) =>- <Environment>{- id: env.id,- name: env.name,- variables: JSON.parse(env.variables),- }- )-- replaceEnvironments(- formatedEnvironments.map((environment) => {- const parsedEnv = Environment.safeParse(environment)-- return parsedEnv.type === "ok"- ? parsedEnv.value- : {- ...environment,- v: EnvironmentSchemaVersion,- }- })- )- })- }- }-}--async function loadGlobalEnvironments() {- const res = await getGlobalEnvironments()-- if (E.isRight(res)) {- const globalEnv = res.right.me.globalEnvironments-- if (globalEnv) {- const parsed = JSON.parse(globalEnv.variables)-- // Parse ladder: wrapper → wrap-bare-array → empty wrapper.- let result = entityReference(GlobalEnvironment).safeParse(parsed)-- if (!result.success && Array.isArray(parsed)) {- result = entityReference(GlobalEnvironment).safeParse({- v: 2,- variables: parsed,- })- }-- runDispatchWithOutSyncing(() => {- setGlobalEnvVariables(- result.success ? result.data : { v: 2, variables: [] }- )- setGlobalEnvID(globalEnv.id)- })- }- } else if (res.left.error == "user_environment/user_env_does_not_exists") {- const res = await createUserGlobalEnvironment(JSON.stringify([]))-- if (E.isRight(res)) {- const backendId = res.right.createUserGlobalEnvironment.id- setGlobalEnvID(backendId)- }- }-}--async function loadAllEnvironments() {- await loadUserEnvironments()- await loadGlobalEnvironments()-}--function setupUserEnvironmentCreatedSubscription() {- const [userEnvironmentCreated$, userEnvironmentCreatedSub] =- runUserEnvironmentCreatedSubscription()-- userEnvironmentCreated$.subscribe((res) => {- if (E.isRight(res)) {- const { name, variables, id } = res.right.userEnvironmentCreated-- const isAlreadyExisting = environmentsStore.value.environments.some(- (env) => env.id == id- )-- if (name && !isAlreadyExisting) {- runDispatchWithOutSyncing(() => {- createEnvironment(name, JSON.parse(variables), id)- })- }- }- })-- return userEnvironmentCreatedSub-}--function setupUserEnvironmentUpdatedSubscription() {- const [userEnvironmentUpdated$, userEnvironmentUpdatedSub] =- runUserEnvironmentUpdatedSubscription()-- userEnvironmentUpdated$.subscribe((res) => {- if (E.isRight(res)) {- const { name, variables, id, isGlobal } = res.right.userEnvironmentUpdated-- // handle the case for global environments- if (isGlobal) {- runDispatchWithOutSyncing(() => {- const parsed = JSON.parse(variables)-- // Mirror the load path: try as-is first (so v0 bare arrays still- // migrate via verzod), only wrap a bare array as a v2 envelope- // when the as-is parse fails (the broken-intermediate-state case).- let result = entityReference(GlobalEnvironment).safeParse(parsed)- if (!result.success && Array.isArray(parsed)) {- result = entityReference(GlobalEnvironment).safeParse({- v: 2,- variables: parsed,- })- }-- setGlobalEnvVariables(- result.success ? result.data : { v: 2, variables: [] }- )- })- } else {- // handle the case for normal environments-- const localIndex = environmentsStore.value.environments.findIndex(- (env) => env.id == id- )-- if ((localIndex || localIndex == 0) && name) {- runDispatchWithOutSyncing(() => {- updateEnvironment(localIndex, {- v: 2,- id,- name,- variables: JSON.parse(variables),- })- })- }- }- }- })-- return userEnvironmentUpdatedSub-}--function setupUserEnvironmentDeletedSubscription() {- const [userEnvironmentDeleted$, userEnvironmentDeletedSub] =- runUserEnvironmentDeletedSubscription()-- userEnvironmentDeleted$.subscribe((res) => {- if (E.isRight(res)) {- const { id } = res.right.userEnvironmentDeleted-- // TODO: move getLocalIndexByID to a getter in the environmentsStore- const localIndex = getLocalIndexByEnvironmentID(id)-- if (localIndex || localIndex === 0) {- runDispatchWithOutSyncing(() => {- deleteEnvironment(localIndex)- })- }- }- })-- return userEnvironmentDeletedSub-}diff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/web/sync.ts b/packages/hoppscotch-selfhost-web/src/platform/environments/web/sync.tsdeleted file mode 100644index b28d65887..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/environments/web/sync.ts+++ /dev/null@@ -1,221 +0,0 @@-import {- environmentsStore,- getGlobalVariableID,- removeDuplicateEntry,-} from "@hoppscotch/common/newstore/environments"-import {- getSettingSubject,- settingsStore,-} from "@hoppscotch/common/newstore/settings"--import { getSyncInitFunction, type StoreSyncDefinitionOf } from "@app/lib/sync"--import * as E from "fp-ts/Either"--import { createMapper } from "@app/lib/sync/mapper"--import {- clearGlobalEnvironmentVariables,- createUserEnvironment,- deleteUserEnvironment,- updateUserEnvironment,-} from "./api"-import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"-import { SecretEnvironmentService } from "@hoppscotch/common/services/secret-environment.service"-import { getService } from "@hoppscotch/common/modules/dioc"-import { CurrentValueService } from "@hoppscotch/common/services/current-environment-value.service"--export const environmentsMapper = createMapper<number, string>()-export const globalEnvironmentMapper = createMapper<number, string>()--const secretEnvironmentService = getService(SecretEnvironmentService)-const currentEnvironmentValueService = getService(CurrentValueService)--// Tracks env ids that are still client-side temporary (`uniqueID()`) while-// the backend create is in flight. `deleteEnvironment` skips the backend-// call when the id is in this set — preventing a spurious 404 during the-// create-then-delete race window. Real backend ids are never added here,-// so deleting an already-synced env always fires the backend mutation.-const pendingTempEnvIds = new Set<string>()--export const storeSyncDefinition: StoreSyncDefinitionOf<- typeof environmentsStore-> = {- async createEnvironment({ name, variables }) {- const lastCreatedEnvIndex = environmentsStore.value.environments.length - 1- const tempId = environmentsStore.value.environments[lastCreatedEnvIndex]?.id- if (!tempId) return- pendingTempEnvIds.add(tempId)-- try {- const res = await createUserEnvironment(- name,- JSON.stringify(stripSecretVariableValuesForWire(variables))- )-- if (E.isRight(res)) {- const id = res.right.createUserEnvironment.id-- // Use the captured `tempId` (not a re-read of the array) so the- // migration still works if the env list shifted during the await.- // Matches the pattern in `appendEnvironments` below.- secretEnvironmentService.updateSecretEnvironmentID(tempId, id)- currentEnvironmentValueService.updateEnvironmentID(tempId, id)-- environmentsStore.value.environments[lastCreatedEnvIndex].id = id- removeDuplicateEntry(id)- }- } finally {- pendingTempEnvIds.delete(tempId)- }- },- async appendEnvironments({ envs }) {- const appendListLength = envs.length- let appendStart =- environmentsStore.value.environments.length - appendListLength - 1-- envs.forEach((env) => {- const envId = ++appendStart-- ;(async function () {- // Capture temp id before backend overwrites it — local stores were- // populated under this id at import time; we remap, not re-populate.- const tempId = environmentsStore.value.environments[envId]?.id- if (!tempId) return- pendingTempEnvIds.add(tempId)-- try {- // Strip at the wire-write boundary even though the import caller- // pre-strips — `appendEnvironments` is a public store API; the- // invariant can't rely on callers.- const res = await createUserEnvironment(- env.name,- JSON.stringify(- stripSecretVariableValuesForWire(env.variables ?? [])- )- )-- if (E.isRight(res)) {- const id = res.right.createUserEnvironment.id-- secretEnvironmentService.updateSecretEnvironmentID(tempId, id)- currentEnvironmentValueService.updateEnvironmentID(tempId, id)-- environmentsStore.value.environments[envId].id = id- removeDuplicateEntry(id)- } else {- // Backend rejected — leave local-store entries intact under- // `tempId` so the env in newstore (which still references- // `tempId`) continues to render secrets for this session.- // Reload will drop the env from newstore; the orphaned- // entries persist but are bounded (one per failed import).- console.error("[appendEnvironments] backend rejected create")- }- } catch (e) {- // Caught here so the fire-and-forget IIFE doesn't surface an- // "unhandled promise rejection." Same in-session preservation- // as the `E.isLeft` branch.- console.error("[appendEnvironments] backend create threw", e)- } finally {- pendingTempEnvIds.delete(tempId)- }- })()- })- },- async duplicateEnvironment({ envIndex }) {- const environmentToDuplicate = environmentsStore.value.environments.find(- (_, index) => index === envIndex- )- if (!environmentToDuplicate) return-- const lastCreatedEnvIndex = environmentsStore.value.environments.length - 1- const tempId = environmentsStore.value.environments[lastCreatedEnvIndex]?.id- if (!tempId) return- pendingTempEnvIds.add(tempId)-- try {- const res = await createUserEnvironment(- `${environmentToDuplicate.name} - Duplicate`,- JSON.stringify(- stripSecretVariableValuesForWire(- environmentToDuplicate.variables ?? []- )- )- )-- if (E.isRight(res)) {- const id = res.right.createUserEnvironment.id- environmentsStore.value.environments[lastCreatedEnvIndex].id = id-- // Duplicates start fresh on secrets per the per-entity model.- removeDuplicateEntry(id)- }- } finally {- pendingTempEnvIds.delete(tempId)- }- },- updateEnvironment({ envIndex, updatedEnv }) {- const backendId = environmentsStore.value.environments[envIndex].id- if (backendId) {- updateUserEnvironment(- backendId,- updatedEnv.name,- JSON.stringify(- stripSecretVariableValuesForWire(updatedEnv.variables ?? [])- )- )()- }- },- async deleteEnvironment({ envID }) {- // Skip when the id belongs to an env whose backend create is still in- // flight — sending the temp `uniqueID()` would 404 and the backend- // create would still complete, orphaning a row. Already-synced envs- // are never in `pendingTempEnvIds`, so this only filters the race- // window; normal deletes fire the backend mutation.- if (envID && !pendingTempEnvIds.has(envID)) {- await deleteUserEnvironment(envID)()- }- },- setGlobalVariables({ entries }) {- const backendId = getGlobalVariableID()- if (backendId) {- // Bail on malformed input — syncing the dispatcher-coerced `[]`- // would clear backend globals irreversibly. Leaving FE/BE desynced- // is recoverable (reload re-hydrates from backend), data loss is- // not. The dispatcher's coerce only protects FE state.- const variables = entries?.variables- if (!Array.isArray(variables)) {- console.error(- "[setGlobalVariables] unexpected variables shape, skipping sync"- )- return- }- updateUserEnvironment(- backendId,- "",- JSON.stringify({- v: 2,- variables: stripSecretVariableValuesForWire(variables),- })- )()- }- },- clearGlobalVariables() {- const backendId = getGlobalVariableID()-- if (backendId) {- clearGlobalEnvironmentVariables(backendId)- }-- // Flush "Global" entries so a later add doesn't alias stale `varIndex`.- secretEnvironmentService.addSecretEnvironment("Global", [])- currentEnvironmentValueService.addEnvironment("Global", [])- },-}--export const environnmentsSyncer = getSyncInitFunction(- environmentsStore,- storeSyncDefinition,- () => settingsStore.value.syncEnvironments,- getSettingSubject("syncEnvironments")-)diff --git a/packages/hoppscotch-selfhost-web/src/platform/history/desktop/api.ts b/packages/hoppscotch-selfhost-web/src/platform/history/desktop/api.tsdeleted file mode 100644index 9e49017a6..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/history/desktop/api.ts+++ /dev/null@@ -1,127 +0,0 @@-import {- runMutation,- runGQLQuery,- runGQLSubscription,-} from "@helpers/backend/GQLClient"--import {- CreateUserHistoryDocument,- CreateUserHistoryMutation,- CreateUserHistoryMutationVariables,- DeleteAllUserHistoryDocument,- DeleteAllUserHistoryMutation,- DeleteAllUserHistoryMutationVariables,- GetRestUserHistoryDocument,- GetRestUserHistoryQuery,- GetRestUserHistoryQueryVariables,- RemoveRequestFromHistoryDocument,- RemoveRequestFromHistoryMutation,- RemoveRequestFromHistoryMutationVariables,- ReqType,- ToggleHistoryStarStatusDocument,- ToggleHistoryStarStatusMutation,- ToggleHistoryStarStatusMutationVariables,- UserHistoryCreatedDocument,- UserHistoryDeletedDocument,- UserHistoryDeletedManyDocument,- UserHistoryUpdatedDocument,- IsUserHistoryEnabledQuery,- IsUserHistoryEnabledQueryVariables,- IsUserHistoryEnabledDocument,- UserHistoryStoreStatusChangedDocument,- UserHistoryAllDeletedDocument,-} from "@app/api/generated/graphql"--export const getUserHistoryEntries = () =>- runGQLQuery<GetRestUserHistoryQuery, GetRestUserHistoryQueryVariables, "">({- query: GetRestUserHistoryDocument,- variables: {},- })--export const getUserHistoryStore = () =>- runGQLQuery<- IsUserHistoryEnabledQuery,- IsUserHistoryEnabledQueryVariables,- ""- >({- query: IsUserHistoryEnabledDocument,- variables: {},- })--export const createUserHistory = (- reqData: string,- resMetadata: string,- reqType: ReqType-) =>- runMutation<- CreateUserHistoryMutation,- CreateUserHistoryMutationVariables,- ""- >(CreateUserHistoryDocument, {- reqData,- resMetadata,- reqType,- })()--export const toggleHistoryStarStatus = (id: string) =>- runMutation<- ToggleHistoryStarStatusMutation,- ToggleHistoryStarStatusMutationVariables,- ""- >(ToggleHistoryStarStatusDocument, {- id,- })()--export const removeRequestFromHistory = (id: string) =>- runMutation<- RemoveRequestFromHistoryMutation,- RemoveRequestFromHistoryMutationVariables,- ""- >(RemoveRequestFromHistoryDocument, {- id,- })()--export const deleteAllUserHistory = (reqType: ReqType) =>- runMutation<- DeleteAllUserHistoryMutation,- DeleteAllUserHistoryMutationVariables,- ""- >(DeleteAllUserHistoryDocument, {- reqType,- })()--export const runUserHistoryCreatedSubscription = () =>- runGQLSubscription({- query: UserHistoryCreatedDocument,- variables: {},- })--export const runUserHistoryUpdatedSubscription = () =>- runGQLSubscription({- query: UserHistoryUpdatedDocument,- variables: {},- })--export const runUserHistoryDeletedSubscription = () =>- runGQLSubscription({- query: UserHistoryDeletedDocument,- variables: {},- })--export const runUserHistoryDeletedManySubscription = () =>- runGQLSubscription({- query: UserHistoryDeletedManyDocument,- variables: {},- })--export const runUserHistoryStoreStatusChangedSubscription = () =>- runGQLSubscription({- query: UserHistoryStoreStatusChangedDocument,- variables: {},- })--export const runUserHistoryAllDeletedSubscription = () =>- runGQLSubscription({- query: UserHistoryAllDeletedDocument,- variables: {},- })diff --git a/packages/hoppscotch-selfhost-web/src/platform/history/desktop/sync.ts b/packages/hoppscotch-selfhost-web/src/platform/history/desktop/sync.tsdeleted file mode 100644index cc2661ffb..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/history/desktop/sync.ts+++ /dev/null@@ -1,110 +0,0 @@-import {- graphqlHistoryStore,- removeDuplicateRestHistoryEntry,- removeDuplicateGraphqlHistoryEntry,- restHistoryStore,-} from "@hoppscotch/common/newstore/history"-import {- getSettingSubject,- settingsStore,-} from "@hoppscotch/common/newstore/settings"--import { getSyncInitFunction, type StoreSyncDefinitionOf } from "@app/lib/sync"--import * as E from "fp-ts/Either"--import {- createUserHistory,- deleteAllUserHistory,- removeRequestFromHistory,- toggleHistoryStarStatus,-} from "@app/platform/history/desktop/api"-import { ReqType } from "@app/api/generated/graphql"--import { isHistoryStoreEnabled } from "."--export const restHistoryStoreSyncDefinition: StoreSyncDefinitionOf<- typeof restHistoryStore-> = {- async addEntry({ entry }) {- if (!isHistoryStoreEnabled.value) {- return- }-- const res = await createUserHistory(- JSON.stringify(entry.request),- JSON.stringify(entry.responseMeta),- ReqType.Rest- )-- if (E.isRight(res)) {- entry.id = res.right.createUserHistory.id-- // preventing double insertion from here and subscription- removeDuplicateRestHistoryEntry(entry.id)- }- },- deleteEntry({ entry }) {- if (entry.id) {- removeRequestFromHistory(entry.id)- }- },- toggleStar({ entry }) {- if (entry.id) {- toggleHistoryStarStatus(entry.id)- }- },- clearHistory() {- deleteAllUserHistory(ReqType.Rest)- },-}--export const gqlHistoryStoreSyncDefinition: StoreSyncDefinitionOf<- typeof graphqlHistoryStore-> = {- async addEntry({ entry }) {- if (!isHistoryStoreEnabled.value) {- return- }-- const res = await createUserHistory(- JSON.stringify(entry.request),- JSON.stringify(entry.response),- ReqType.Gql- )-- if (E.isRight(res)) {- entry.id = res.right.createUserHistory.id-- // preventing double insertion from here and subscription- removeDuplicateGraphqlHistoryEntry(entry.id)- }- },- deleteEntry({ entry }) {- if (entry.id) {- removeRequestFromHistory(entry.id)- }- },- toggleStar({ entry }) {- if (entry.id) {- toggleHistoryStarStatus(entry.id)- }- },- clearHistory() {- deleteAllUserHistory(ReqType.Gql)- },-}--export const restHistorySyncer = getSyncInitFunction(- restHistoryStore,- restHistoryStoreSyncDefinition,- () => settingsStore.value.syncHistory,- getSettingSubject("syncHistory")-)--export const gqlHistorySyncer = getSyncInitFunction(- graphqlHistoryStore,- gqlHistoryStoreSyncDefinition,- () => settingsStore.value.syncHistory,- getSettingSubject("syncHistory")-)diff --git a/packages/hoppscotch-selfhost-web/src/platform/history/sync.ts b/packages/hoppscotch-selfhost-web/src/platform/history/sync.tsnew file mode 100644index 000000000..b19e467bc--- /dev/null+++ b/packages/hoppscotch-selfhost-web/src/platform/history/sync.ts@@ -0,0 +1,56 @@+import {+ runGQLQuery,+ runGQLSubscription,+} from "@hoppscotch/common/helpers/backend/GQLClient"+import { SyncPlatformDef } from "@hoppscotch/common/platform/sync"+import * as E from "fp-ts/Either"++import {+ IsUserHistoryEnabledDocument,+ IsUserHistoryEnabledQuery,+ IsUserHistoryEnabledQueryVariables,+ ServiceStatus,+ UserHistoryStoreStatusChangedDocument,+} from "@app/api/generated/graphql"++const getUserHistoryStore = () =>+ runGQLQuery<+ IsUserHistoryEnabledQuery,+ IsUserHistoryEnabledQueryVariables,+ ""+ >({+ query: IsUserHistoryEnabledDocument,+ variables: {},+ })++/**+ * Self-host history sync overrides. The `isUserHistoryEnabled` infra-config+ * (and its change subscription) only exist on the self-hosted backend, so the+ * shared sync layer in `~/lib/sync/history` feature-detects these hooks rather+ * than depending on the self-host-only documents directly.+ */+export const historySyncDef: NonNullable<SyncPlatformDef["history"]> = {+ async getHistoryStoreStatus() {+ const res = await getUserHistoryStore()++ if (E.isLeft(res)) {+ throw res.left+ }++ return res.right.isUserHistoryEnabled.value === ServiceStatus.Enable+ },+ subscribeToHistoryStoreStatus(onStatusChange) {+ const [statusChanged$, sub] = runGQLSubscription({+ query: UserHistoryStoreStatusChangedDocument,+ variables: {},+ })++ statusChanged$.subscribe((res) => {+ if (E.isRight(res)) {+ onStatusChange(res.right.infraConfigUpdate === ServiceStatus.Enable)+ }+ })++ return sub+ },+}diff --git a/packages/hoppscotch-selfhost-web/src/platform/history/web/index.ts b/packages/hoppscotch-selfhost-web/src/platform/history/web/index.tsdeleted file mode 100644index 9a274161a..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/history/web/index.ts+++ /dev/null@@ -1,329 +0,0 @@-import { authEvents$, def as platformAuth } from "@app/platform/auth/web"-import {- restHistoryStore,- RESTHistoryEntry,- setRESTHistoryEntries,- addRESTHistoryEntry,- toggleRESTHistoryEntryStar,- deleteRESTHistoryEntry,- clearRESTHistory,- setGraphqlHistoryEntries,- GQLHistoryEntry,- addGraphqlHistoryEntry,- toggleGraphqlHistoryEntryStar,- graphqlHistoryStore,- deleteGraphqlHistoryEntry,- clearGraphqlHistory,- decodeGQLHistoryResponse,-} from "@hoppscotch/common/newstore/history"-import { translateToNewRequest, translateToGQLRequest } from "@hoppscotch/data"-import { HistoryPlatformDef } from "@hoppscotch/common/platform/history"-import {- getUserHistoryEntries,- getUserHistoryStore,- runUserHistoryAllDeletedSubscription,- runUserHistoryCreatedSubscription,- runUserHistoryDeletedManySubscription,- runUserHistoryDeletedSubscription,- runUserHistoryStoreStatusChangedSubscription,- runUserHistoryUpdatedSubscription,-} from "@app/platform/history/web/api"--import * as E from "fp-ts/Either"-import {- restHistorySyncer,- gqlHistorySyncer,-} from "@app/platform/history/web/sync"-import { runGQLSubscription } from "@hoppscotch/common/helpers/backend/GQLClient"-import { runDispatchWithOutSyncing } from "@app/lib/sync"-import { ReqType, ServiceStatus } from "@app/api/generated/graphql"-import { ref } from "vue"--function initHistorySync() {- const currentUser$ = platformAuth.getCurrentUserStream()-- restHistorySyncer.startStoreSync()- restHistorySyncer.setupSubscriptions(setupSubscriptions)-- gqlHistorySyncer.startStoreSync()-- getUserHistoryStatus()- loadHistoryEntries()-- currentUser$.subscribe(async (user) => {- getUserHistoryStatus()-- if (user) {- await loadHistoryEntries()- }- })-- authEvents$.subscribe((event) => {- if (event.event == "login" || event.event == "token_refresh") {- restHistorySyncer.startListeningToSubscriptions()- }-- if (event.event == "logout") {- restHistorySyncer.stopListeningToSubscriptions()- }- })-}--function setupSubscriptions() {- let subs: ReturnType<typeof runGQLSubscription>[1][] = []-- const userHistoryCreatedSub = setupUserHistoryCreatedSubscription()- const userHistoryUpdatedSub = setupUserHistoryUpdatedSubscription()- const userHistoryDeletedSub = setupUserHistoryDeletedSubscription()- const userHistoryDeletedManySub = setupUserHistoryDeletedManySubscription()- const userHistoryStoreStatusChangedSub =- setupUserHistoryStoreStatusChangedSubscription()- const userHistoryAllDeletedSub = setupUserHistoryAllDeletedSubscription()-- subs = [- userHistoryCreatedSub,- userHistoryUpdatedSub,- userHistoryDeletedSub,- userHistoryDeletedManySub,- userHistoryStoreStatusChangedSub,- userHistoryAllDeletedSub,- ]-- return () => {- subs.forEach((sub) => sub.unsubscribe())- }-}--async function loadHistoryEntries() {- const res = await getUserHistoryEntries()-- if (E.isRight(res)) {- const restEntries = res.right.me.RESTHistory- const gqlEntries = res.right.me.GQLHistory-- const restHistoryEntries: RESTHistoryEntry[] = restEntries.map((entry) => ({- v: 1,- request: translateToNewRequest(JSON.parse(entry.request)),- responseMeta: JSON.parse(entry.responseMetadata),- star: entry.isStarred,- updatedOn: new Date(entry.executedOn),- id: entry.id,- }))-- const gqlHistoryEntries: GQLHistoryEntry[] = gqlEntries.map((entry) => ({- v: 1,- request: translateToGQLRequest(JSON.parse(entry.request)),- response: decodeGQLHistoryResponse(entry.responseMetadata),- star: entry.isStarred,- updatedOn: new Date(entry.executedOn),- id: entry.id,- }))-- runDispatchWithOutSyncing(() => {- setRESTHistoryEntries(restHistoryEntries)- setGraphqlHistoryEntries(gqlHistoryEntries)- })- }-}--async function getUserHistoryStatus() {- const currentUser = platformAuth.getCurrentUser()-- if (!currentUser) {- isHistoryStoreEnabled.value = true- return- }-- isFetchingHistoryStoreStatus.value = true-- const res = await getUserHistoryStore()-- if (E.isLeft(res)) {- hasErrorFetchingHistoryStoreStatus.value = true- isFetchingHistoryStoreStatus.value = false- return- }-- isHistoryStoreEnabled.value =- res.right.isUserHistoryEnabled.value === ServiceStatus.Enable-- isFetchingHistoryStoreStatus.value = false-}--function setupUserHistoryCreatedSubscription() {- const [userHistoryCreated$, userHistoryCreatedSub] =- runUserHistoryCreatedSubscription()-- userHistoryCreated$.subscribe((res) => {- if (E.isRight(res)) {- const { id, reqType, request, responseMetadata, isStarred, executedOn } =- res.right.userHistoryCreated-- const hasAlreadyBeenAdded =- reqType == ReqType.Rest- ? restHistoryStore.value.state.some((entry) => entry.id == id)- : graphqlHistoryStore.value.state.some((entry) => entry.id == id)-- !hasAlreadyBeenAdded &&- runDispatchWithOutSyncing(() => {- reqType == ReqType.Rest- ? addRESTHistoryEntry({- v: 1,- id,- request: translateToNewRequest(JSON.parse(request)),- responseMeta: JSON.parse(responseMetadata),- star: isStarred,- updatedOn: new Date(executedOn),- })- : addGraphqlHistoryEntry({- v: 1,- id,- request: translateToGQLRequest(JSON.parse(request)),- response: decodeGQLHistoryResponse(responseMetadata),- star: isStarred,- updatedOn: new Date(executedOn),- })- })- }- })-- return userHistoryCreatedSub-}--// currently the updates are only for toggling the star-function setupUserHistoryUpdatedSubscription() {- const [userHistoryUpdated$, userHistoryUpdatedSub] =- runUserHistoryUpdatedSubscription()-- userHistoryUpdated$.subscribe((res) => {- if (E.isRight(res)) {- const { id, reqType, isStarred } = res.right.userHistoryUpdated-- if (reqType == ReqType.Rest) {- const existingEntry = restHistoryStore.value.state.find(- (entry) => entry.id == id- )-- // Only toggle if the store entry's star doesn't match the server state.- // Without this guard, the subscription echo from the same client's own- // toggle would cause a second toggle and revert the star.- if (existingEntry && existingEntry.star !== isStarred) {- runDispatchWithOutSyncing(() => {- toggleRESTHistoryEntryStar(existingEntry)- })- }- }-- if (reqType == ReqType.Gql) {- const existingEntry = graphqlHistoryStore.value.state.find(- (entry) => entry.id == id- )-- if (existingEntry && existingEntry.star !== isStarred) {- runDispatchWithOutSyncing(() => {- toggleGraphqlHistoryEntryStar(existingEntry)- })- }- }- }- })-- return userHistoryUpdatedSub-}--function setupUserHistoryDeletedSubscription() {- const [userHistoryDeleted$, userHistoryDeletedSub] =- runUserHistoryDeletedSubscription()-- userHistoryDeleted$.subscribe((res) => {- if (E.isRight(res)) {- const { id, reqType } = res.right.userHistoryDeleted-- if (reqType == ReqType.Gql) {- const deletedEntry = graphqlHistoryStore.value.state.find(- (entry) => entry.id == id- )-- deletedEntry &&- runDispatchWithOutSyncing(() => {- deleteGraphqlHistoryEntry(deletedEntry)- })- }-- if (reqType == ReqType.Rest) {- const deletedEntry = restHistoryStore.value.state.find(- (entry) => entry.id == id- )-- deletedEntry &&- runDispatchWithOutSyncing(() => {- deleteRESTHistoryEntry(deletedEntry)- })- }- }- })-- return userHistoryDeletedSub-}--function setupUserHistoryDeletedManySubscription() {- const [userHistoryDeletedMany$, userHistoryDeletedManySub] =- runUserHistoryDeletedManySubscription()-- userHistoryDeletedMany$.subscribe((res) => {- if (E.isRight(res)) {- const { reqType } = res.right.userHistoryDeletedMany-- runDispatchWithOutSyncing(() => {- reqType == ReqType.Rest ? clearRESTHistory() : clearGraphqlHistory()- })- }- })-- return userHistoryDeletedManySub-}--function setupUserHistoryStoreStatusChangedSubscription() {- const [userHistoryStoreStatusChanged$, userHistoryStoreStatusChangedSub] =- runUserHistoryStoreStatusChangedSubscription()-- userHistoryStoreStatusChanged$.subscribe((res) => {- if (E.isRight(res)) {- const status =- res.right.infraConfigUpdate == ServiceStatus.Enable ? true : false-- isHistoryStoreEnabled.value = status- }- })-- return userHistoryStoreStatusChangedSub-}--function setupUserHistoryAllDeletedSubscription() {- const [userHistoryAllDeleted$, userHistoryAllDeletedSub] =- runUserHistoryAllDeletedSubscription()-- userHistoryAllDeleted$.subscribe((res) => {- if (E.isRight(res)) {- runDispatchWithOutSyncing(() => {- clearRESTHistory()- clearGraphqlHistory()- })- }- })-- return userHistoryAllDeletedSub-}--export const isHistoryStoreEnabled = ref(false)-const isFetchingHistoryStoreStatus = ref(false)-const hasErrorFetchingHistoryStoreStatus = ref(false)--export const def: HistoryPlatformDef = {- initHistorySync,- requestHistoryStore: {- isHistoryStoreEnabled,- isFetchingHistoryStoreStatus,- hasErrorFetchingHistoryStoreStatus,- },-}diff --git a/packages/hoppscotch-selfhost-web/src/platform/settings/desktop/index.ts b/packages/hoppscotch-selfhost-web/src/platform/settings/desktop/index.tsdeleted file mode 100644index 2e3c46a1d..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/settings/desktop/index.ts+++ /dev/null@@ -1,88 +0,0 @@-import { SettingsPlatformDef } from "@hoppscotch/common/platform/settings"-import { settingsSyncer } from "./sync"-import { authEvents$, def as platformAuth } from "@app/platform/auth/desktop"-import {- createUserSettings,- getUserSettings,- runUserSettingsUpdatedSubscription,-} from "./api"-import * as E from "fp-ts/Either"-import { runGQLSubscription } from "@hoppscotch/common/helpers/backend/GQLClient"-import {- bulkApplySettings,- getDefaultSettings,-} from "@hoppscotch/common/newstore/settings"-import { runDispatchWithOutSyncing } from "@app/lib/sync"--function initSettingsSync() {- const currentUser$ = platformAuth.getCurrentUserStream()- settingsSyncer.startStoreSync()- settingsSyncer.setupSubscriptions(setupSubscriptions)-- // load the settings-- loadUserSettings()-- currentUser$.subscribe(async (user) => {- if (user) {- // load the settings- loadUserSettings()- }- })-- authEvents$.subscribe((event) => {- if (event.event == "login" || event.event == "token_refresh") {- settingsSyncer.startListeningToSubscriptions()- }-- if (event.event == "logout") {- settingsSyncer.stopListeningToSubscriptions()- }- })-}--async function loadUserSettings() {- const res = await getUserSettings()-- // create user settings if it doesn't exist- E.isLeft(res) &&- res.left.error == "user_settings/not_found" &&- (await createUserSettings(JSON.stringify(getDefaultSettings())))-- if (E.isRight(res)) {- runDispatchWithOutSyncing(() => {- bulkApplySettings(JSON.parse(res.right.me.settings.properties))- })- }-}--function setupSubscriptions() {- let subs: ReturnType<typeof runGQLSubscription>[1][] = []-- const userSettingsUpdatedSub = setupUserSettingsUpdatedSubscription()-- subs = [userSettingsUpdatedSub]-- return () => {- subs.forEach((sub) => sub.unsubscribe())- }-}--function setupUserSettingsUpdatedSubscription() {- const [userSettingsUpdated$, userSettingsUpdatedSub] =- runUserSettingsUpdatedSubscription()-- userSettingsUpdated$.subscribe((res) => {- if (E.isRight(res)) {- runDispatchWithOutSyncing(() => {- bulkApplySettings(JSON.parse(res.right.userSettingsUpdated.properties))- })- }- })-- return userSettingsUpdatedSub-}--export const def: SettingsPlatformDef = {- initSettingsSync,-}diff --git a/packages/hoppscotch-selfhost-web/src/platform/settings/desktop/sync.ts b/packages/hoppscotch-selfhost-web/src/platform/settings/desktop/sync.tsdeleted file mode 100644index 17d9011c1..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/settings/desktop/sync.ts+++ /dev/null@@ -1,28 +0,0 @@-import { settingsStore } from "@hoppscotch/common/newstore/settings"--import { getSyncInitFunction, type StoreSyncDefinitionOf } from "@app/lib/sync"--import { updateUserSettings } from "./api"--export const settingsSyncDefinition: StoreSyncDefinitionOf<- typeof settingsStore-> = {- toggleSetting() {- updateUserSettings(JSON.stringify(settingsStore.value))- },- toggleNestedSetting() {- updateUserSettings(JSON.stringify(settingsStore.value))- },- applySetting() {- updateUserSettings(JSON.stringify(settingsStore.value))- },- applyNestedSetting() {- updateUserSettings(JSON.stringify(settingsStore.value))- },-}--export const settingsSyncer = getSyncInitFunction(- settingsStore,- settingsSyncDefinition,- () => true-)diff --git a/packages/hoppscotch-selfhost-web/src/platform/settings/web/api.ts b/packages/hoppscotch-selfhost-web/src/platform/settings/web/api.tsdeleted file mode 100644index dd726fe9a..000000000--- a/packages/hoppscotch-selfhost-web/src/platform/settings/web/api.ts+++ /dev/null@@ -1,51 +0,0 @@-import {- runGQLQuery,- runGQLSubscription,- runMutation,-} from "@helpers/backend/GQLClient"-import {- CreateUserSettingsDocument,- CreateUserSettingsMutation,- CreateUserSettingsMutationVariables,- GetUserSettingsDocument,- GetUserSettingsQuery,- GetUserSettingsQueryVariables,- UpdateUserSettingsDocument,- UpdateUserSettingsMutation,- UpdateUserSettingsMutationVariables,- UserSettingsUpdatedDocument,-} from "@app/api/generated/graphql"--export const getUserSettings = () =>- runGQLQuery<- GetUserSettingsQuery,- GetUserSettingsQueryVariables,- "user_settings/not_found"- >({- query: GetUserSettingsDocument,- variables: {},- })--export const createUserSettings = (properties: string) =>- runMutation<- CreateUserSettingsMutation,- CreateUserSettingsMutationVariables,- ""- >(CreateUserSettingsDocument, {- properties,- })()--export const updateUserSettings = (properties: string) =>- runMutation<- UpdateUserSettingsMutation,- UpdateUserSettingsMutationVariables,- ""- >(UpdateUserSettingsDocument, {- properties,- })()--export const runUserSettingsUpdatedSubscription = () =>- runGQLSubscription({- query: UserSettingsUpdatedDocument,- variables: {},- })diff --git a/packages/hoppscotch-selfhost-web/tsconfig.json b/packages/hoppscotch-selfhost-web/tsconfig.jsonindex d50b6fcbb..75c49f743 100644--- a/packages/hoppscotch-selfhost-web/tsconfig.json+++ b/packages/hoppscotch-selfhost-web/tsconfig.json@@ -21,7 +21,6 @@"@app/composables/*": ["./src/composables/*"],"@app/helpers/*": ["./src/helpers/*"],"@app/api/*": ["./src/api/*"],- "@app/lib/*": ["./src/lib/*"],"@app/kernel/*": ["./src/kernel/*"]},"types": ["vite/client", "unplugin-icons/types/vue"]diff --git a/packages/hoppscotch-selfhost-web/vite.config.ts b/packages/hoppscotch-selfhost-web/vite.config.tsindex 96fbceba1..21df33085 100644--- a/packages/hoppscotch-selfhost-web/vite.config.ts+++ b/packages/hoppscotch-selfhost-web/vite.config.ts@@ -89,7 +89,6 @@ export default defineConfig({"@app/composables": path.resolve(__dirname, "./src/composables"),"@app/helpers": path.resolve(__dirname, "./src/helpers"),"@app/api": path.resolve(__dirname, "./src/api"),- "@app/lib": path.resolve(__dirname, "./src/lib"),"@app/kernel": path.resolve(__dirname, "./src/kernel"),// Node.js polyfills