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
feat: REST-GQL Unified workspace (#6545)
Nivedin4789a0f2fae4
diff --git a/packages/hoppscotch-backend/prisma/migrations/20260713090000_mock_server_gql_examples/migration.sql b/packages/hoppscotch-backend/prisma/migrations/20260713090000_mock_server_gql_examples/migration.sqlnew file mode 100644index 000000000..75f2893f0--- /dev/null+++ b/packages/hoppscotch-backend/prisma/migrations/20260713090000_mock_server_gql_examples/migration.sql@@ -0,0 +1,55 @@+-- Extend sync_mock_examples() to project the GraphQL operation identity of+-- saved example responses (operationName / operationType, stamped by the app+-- when a GraphQL run is saved as an example). The mock server's GraphQL+-- matcher selects examples by these, the way REST examples match by+-- method + path. REST examples project both fields as NULL.+CREATE OR REPLACE FUNCTION sync_mock_examples()+RETURNS TRIGGER AS $$+BEGIN+ NEW."mockExamples" := jsonb_build_object(+ 'examples',+ COALESCE(+ (+ SELECT jsonb_agg(+ jsonb_build_object(+ 'key', key,+ 'name', value->>'name',+ 'endpoint', value->'originalRequest'->>'endpoint',+ 'method', value->'originalRequest'->>'method',+ 'headers', COALESCE(value->'originalRequest'->'headers', '[]'::jsonb),+ 'statusCode', (value->>'code')::int,+ 'statusText', value->>'status',+ 'responseBody', value->>'body',+ 'responseHeaders', COALESCE(value->'headers', '[]'::jsonb),+ 'operationName', value->>'operationName',+ 'operationType', value->>'operationType'+ )+ )+ FROM jsonb_each(NEW.request->'responses') AS responses(key, value)+ WHERE jsonb_typeof(NEW.request->'responses') = 'object'+ ),+ '[]'::jsonb+ )+ );++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++-- Backfill: re-fire the trigger so existing rows pick up the new projection.+--+-- Scoped to rows that actually carry saved example responses. `request` is+-- NOT NULL on both tables, so an `IS NOT NULL` guard would filter nothing and+-- rewrite every request row in the database — a full-table rewrite (plus bloat+-- and a long lock hold on large self-hosted instances) to recompute a value+-- that is unchanged for those rows: with no `responses` object the projection+-- COALESCEs to the same `{"examples": []}` the previous trigger produced.+UPDATE "UserRequest"+SET request = request+WHERE jsonb_typeof(request -> 'responses') = 'object'+ AND request -> 'responses' <> '{}'::jsonb;++UPDATE "TeamRequest"+SET request = request+WHERE jsonb_typeof(request -> 'responses') = 'object'+ AND request -> 'responses' <> '{}'::jsonb;diff --git a/packages/hoppscotch-backend/prisma/schema.prisma b/packages/hoppscotch-backend/prisma/schema.prismaindex 26a3b2630..54d8f25c4 100644--- a/packages/hoppscotch-backend/prisma/schema.prisma+++ b/packages/hoppscotch-backend/prisma/schema.prisma@@ -7,14 +7,46 @@ datasource db {provider = "postgresql"}+// ============================================================+// ENUMS+// ============================================================++enum WorkspaceType {+ USER+ TEAM+}++enum ReqType {+ REST+ GQL+}++enum TeamAccessRole {+ OWNER+ VIEWER+ EDITOR+}++enum MockServerAction {+ CREATED+ DELETED+ ACTIVATED+ DEACTIVATED+}++// ============================================================+// TEAM+// ============================================================+model Team {- id String @id @default(cuid())- name String- TeamCollection TeamCollection[]- TeamEnvironment TeamEnvironment[]- TeamInvitation TeamInvitation[]- members TeamMember[]- TeamRequest TeamRequest[]+ id String @id @default(cuid())+ name String++ collections TeamCollection[]+ environments TeamEnvironment[]+ invitations TeamInvitation[]+ members TeamMember[]+ requests TeamRequest[]}model TeamMember {@@ -22,7 +54,8 @@ model TeamMember {role TeamAccessRoleuserUid StringteamID String- team Team @relation(fields: [teamID], references: [id], onDelete: Cascade)++ team Team @relation(fields: [teamID], references: [id], onDelete: Cascade)@@unique([teamID, userUid])}@@ -33,55 +66,46 @@ model TeamInvitation {creatorUid StringinviteeEmail StringinviteeRole TeamAccessRole- team Team @relation(fields: [teamID], references: [id], onDelete: Cascade)++ team Team @relation(fields: [teamID], references: [id], onDelete: Cascade)@@unique([teamID, inviteeEmail])@@index([teamID])}model TeamCollection {- id String @id @default(cuid())+ id String @id @default(cuid())parentID String?teamID Stringtitle StringorderIndex Int- createdOn DateTime @default(now()) @db.Timestamptz(3)- updatedOn DateTime @updatedAt @db.Timestamptz(3)data Json?- parent TeamCollection? @relation("TeamCollectionChildParent", fields: [parentID], references: [id], onDelete: Cascade)- children TeamCollection[] @relation("TeamCollectionChildParent")- team Team @relation(fields: [teamID], references: [id], onDelete: Cascade)- requests TeamRequest[]+ createdOn DateTime @default(now()) @db.Timestamptz(3)+ updatedOn DateTime @updatedAt @db.Timestamptz(3)++ parent TeamCollection? @relation("TeamCollectionChildParent", fields: [parentID], references: [id], onDelete: Cascade)+ children TeamCollection[] @relation("TeamCollectionChildParent")+ team Team @relation(fields: [teamID], references: [id], onDelete: Cascade)+ requests TeamRequest[]@@unique([teamID, parentID, orderIndex])}model TeamRequest {- id String @id @default(cuid())+ id String @id @default(cuid())collectionID StringteamID Stringtitle Stringrequest JsonmockExamples Json?orderIndex Int- createdOn DateTime @default(now()) @db.Timestamptz(3)- updatedOn DateTime @updatedAt @db.Timestamptz(3)- collection TeamCollection @relation(fields: [collectionID], references: [id], onDelete: Cascade)- team Team @relation(fields: [teamID], references: [id], onDelete: Cascade)+ createdOn DateTime @default(now()) @db.Timestamptz(3)+ updatedOn DateTime @updatedAt @db.Timestamptz(3)- @@unique([teamID, collectionID, orderIndex])-}--model Shortcode {- id String @id @unique- request Json- creatorUid String?- createdOn DateTime @default(now()) @db.Timestamptz(3)- embedProperties Json?- updatedOn DateTime @default(now()) @updatedAt @db.Timestamptz(3)- User User? @relation(fields: [creatorUid], references: [uid])+ collection TeamCollection @relation(fields: [collectionID], references: [id], onDelete: Cascade)+ team Team @relation(fields: [teamID], references: [id], onDelete: Cascade)- @@unique([id, creatorUid], name: "creator_uid_shortcode_unique")+ @@unique([teamID, collectionID, orderIndex])}model TeamEnvironment {@@ -89,32 +113,38 @@ model TeamEnvironment {teamID Stringname Stringvariables Json- team Team @relation(fields: [teamID], references: [id], onDelete: Cascade)++ team Team @relation(fields: [teamID], references: [id], onDelete: Cascade)}+// ============================================================+// USER+// ============================================================+model User {- uid String @id @default(cuid())- displayName String?- email String? @unique- photoURL String?- isAdmin Boolean @default(false)- refreshToken String?- currentRESTSession Json?- currentGQLSession Json?- createdOn DateTime @default(now()) @db.Timestamptz(3)- lastLoggedOn DateTime? @db.Timestamptz(3)- lastActiveOn DateTime? @db.Timestamptz(3)+ uid String @id @default(cuid())+ displayName String?+ email String? @unique+ photoURL String?+ isAdmin Boolean @default(false)+ refreshToken String?+ currentRESTSession Json?+ currentGQLSession Json?+ createdOn DateTime @default(now()) @db.Timestamptz(3)+ lastLoggedOn DateTime? @db.Timestamptz(3)+ lastActiveOn DateTime? @db.Timestamptz(3)+providerAccounts Account[]invitedUsers InvitedUsers[]mockServers MockServer[]personalAccessTokens PersonalAccessToken[]shortcodes Shortcode[]userCollections UserCollection[]- UserEnvironments UserEnvironment[]- UserHistory UserHistory[]+ environments UserEnvironment[]+ history UserHistory[]userRequests UserRequest[]settings UserSettings?- VerificationToken VerificationToken[]+ verificationTokens VerificationToken[]}model Account {@@ -126,7 +156,8 @@ model Account {providerAccessToken String?providerScope String?loggedIn DateTime @default(now()) @db.Timestamptz(3)- user User @relation(fields: [userId], references: [uid], onDelete: Cascade)++ user User @relation(fields: [userId], references: [uid], onDelete: Cascade)@@unique([provider, providerAccountId], name: "verifyProviderAccount")}@@ -136,7 +167,8 @@ model VerificationToken {token String @unique @default(cuid())userUid StringexpiresOn DateTime @db.Timestamptz(3)- user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)++ user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)@@unique([deviceIdentifier, token], name: "passwordless_deviceIdentifier_tokens")}@@ -146,7 +178,8 @@ model UserSettings {userUid String @uniqueproperties JsonupdatedOn DateTime @updatedAt @db.Timestamptz(3)- user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)++ user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)}model UserHistory {@@ -157,7 +190,8 @@ model UserHistory {responseMetadata JsonisStarred BooleanexecutedOn DateTime @default(now()) @db.Timestamptz(3)- user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)++ user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)}model UserEnvironment {@@ -166,7 +200,8 @@ model UserEnvironment {name String?variables JsonisGlobal Boolean- user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)++ user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)}model InvitedUsers {@@ -174,20 +209,22 @@ model InvitedUsers {adminEmail StringinviteeEmail String @uniqueinvitedOn DateTime @default(now()) @db.Timestamptz(3)- user User @relation(fields: [adminUid], references: [uid], onDelete: Cascade)++ user User @relation(fields: [adminUid], references: [uid], onDelete: Cascade)}model UserRequest {- id String @id @default(cuid())- collectionID String- userUid String- title String- request Json- mockExamples Json?- type ReqType- orderIndex Int- createdOn DateTime @default(now()) @db.Timestamptz(3)- updatedOn DateTime @updatedAt @db.Timestamptz(3)+ id String @id @default(cuid())+ collectionID String+ userUid String+ title String+ request Json+ type ReqType+ mockExamples Json?+ orderIndex Int+ createdOn DateTime @default(now()) @db.Timestamptz(3)+ updatedOn DateTime @updatedAt @db.Timestamptz(3)+userCollection UserCollection @relation(fields: [collectionID], references: [id], onDelete: Cascade)user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)@@ -195,77 +232,52 @@ model UserRequest {}model UserCollection {- id String @id @default(cuid())+ id String @id @default(cuid())parentID String?userUid Stringtitle String- orderIndex Inttype ReqType- createdOn DateTime @default(now()) @db.Timestamptz(3)- updatedOn DateTime @updatedAt @db.Timestamptz(3)+ orderIndex Intdata Json?- parent UserCollection? @relation("ParentUserCollection", fields: [parentID], references: [id], onDelete: Cascade)- children UserCollection[] @relation("ParentUserCollection")- user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)- requests UserRequest[]-- @@unique([userUid, parentID, orderIndex])-}+ createdOn DateTime @default(now()) @db.Timestamptz(3)+ updatedOn DateTime @updatedAt @db.Timestamptz(3)-model InfraConfig {- id String @id @default(cuid())- name String @unique- value String?- createdOn DateTime @default(now()) @db.Timestamptz(3)- updatedOn DateTime @updatedAt @db.Timestamptz(3)- isEncrypted Boolean @default(false)- lastSyncedEnvFileValue String?-}+ parent UserCollection? @relation("ParentUserCollection", fields: [parentID], references: [id], onDelete: Cascade)+ children UserCollection[] @relation("ParentUserCollection")+ user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)+ requests UserRequest[]-model PersonalAccessToken {- id String @id @default(cuid())- userUid String- label String- token String @unique @default(uuid())- expiresOn DateTime? @db.Timestamptz(3)- createdOn DateTime @default(now()) @db.Timestamptz(3)- updatedOn DateTime @updatedAt @db.Timestamptz(3)- user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)+ @@unique([userUid, parentID, orderIndex])}-model InfraToken {- id String @id @default(cuid())- creatorUid String- label String- token String @unique @default(uuid())- expiresOn DateTime? @db.Timestamptz(3)- createdOn DateTime @default(now()) @db.Timestamptz(3)- updatedOn DateTime @default(now()) @db.Timestamptz(3)-}+// ============================================================+// MOCK SERVER+// ============================================================model MockServer {- id String @id @default(cuid())- name String- subdomain String @unique- creatorUid String?- collectionID String- workspaceType WorkspaceType- workspaceID String- delayInMs Int @default(0)- isPublic Boolean @default(true)- isActive Boolean @default(true)- hitCount Int @default(0)- lastHitAt DateTime? @db.Timestamptz(3)- createdOn DateTime @default(now()) @db.Timestamptz(3)- updatedOn DateTime @updatedAt @db.Timestamptz(3)- deletedAt DateTime? @db.Timestamptz(3)+ id String @id @default(cuid())+ name String+ subdomain String @unique+ creatorUid String?+ collectionID String+ workspaceType WorkspaceType+ workspaceID String+ delayInMs Int @default(0)+ isPublic Boolean @default(true)+ isActive Boolean @default(true)+ hitCount Int @default(0)+ lastHitAt DateTime? @db.Timestamptz(3)+ createdOn DateTime @default(now()) @db.Timestamptz(3)+ updatedOn DateTime @updatedAt @db.Timestamptz(3)+ deletedAt DateTime? @db.Timestamptz(3)+user User? @relation(fields: [creatorUid], references: [uid], onDelete: SetNull)requestLogs MockServerLog[]activityHistory MockServerActivity[]}model MockServerLog {- id String @id @default(cuid())+ id String @id @default(cuid())mockServerID StringrequestMethod StringrequestPath String@@ -278,8 +290,9 @@ model MockServerLog {responseTime IntipAddress String?userAgent String?- executedAt DateTime @default(now()) @db.Timestamptz(3)- mockServer MockServer @relation(fields: [mockServerID], references: [id], onDelete: Cascade)+ executedAt DateTime @default(now()) @db.Timestamptz(3)++ mockServer MockServer @relation(fields: [mockServerID], references: [id], onDelete: Cascade)@@index([mockServerID])@@index([mockServerID, executedAt])@@ -291,11 +304,61 @@ model MockServerActivity {action MockServerActionperformedBy String?performedAt DateTime @default(now()) @db.Timestamptz(3)- mockServer MockServer @relation(fields: [mockServerID], references: [id], onDelete: Cascade)++ mockServer MockServer @relation(fields: [mockServerID], references: [id], onDelete: Cascade)@@index([mockServerID])}+// ============================================================+// OTHERS+// ============================================================++model Shortcode {+ id String @id @unique+ request Json+ creatorUid String?+ embedProperties Json?+ createdOn DateTime @default(now()) @db.Timestamptz(3)+ updatedOn DateTime @default(now()) @updatedAt @db.Timestamptz(3)++ user User? @relation(fields: [creatorUid], references: [uid])++ @@unique([id, creatorUid], name: "creator_uid_shortcode_unique")+}++model InfraConfig {+ id String @id @default(cuid())+ name String @unique+ value String?+ isEncrypted Boolean @default(false)+ lastSyncedEnvFileValue String?+ createdOn DateTime @default(now()) @db.Timestamptz(3)+ updatedOn DateTime @updatedAt @db.Timestamptz(3)+}++model PersonalAccessToken {+ id String @id @default(cuid())+ userUid String+ label String+ token String @unique @default(uuid())+ expiresOn DateTime? @db.Timestamptz(3)+ createdOn DateTime @default(now()) @db.Timestamptz(3)+ updatedOn DateTime @updatedAt @db.Timestamptz(3)++ user User @relation(fields: [userUid], references: [uid], onDelete: Cascade)+}++model InfraToken {+ id String @id @default(cuid())+ creatorUid String+ label String+ token String @unique @default(uuid())+ expiresOn DateTime? @db.Timestamptz(3)+ createdOn DateTime @default(now()) @db.Timestamptz(3)+ updatedOn DateTime @default(now()) @db.Timestamptz(3)+}+model PublishedDocs {id String @id @default(cuid())slug String@@ -317,26 +380,3 @@ model PublishedDocs {@@unique([slug, version])@@index([collectionID])}--enum WorkspaceType {- USER- TEAM-}--enum ReqType {- REST- GQL-}--enum TeamAccessRole {- OWNER- VIEWER- EDITOR-}--enum MockServerAction {- CREATED- DELETED- ACTIVATED- DEACTIVATED-}diff --git a/packages/hoppscotch-backend/src/errors.ts b/packages/hoppscotch-backend/src/errors.tsindex fac347388..98c749f91 100644--- a/packages/hoppscotch-backend/src/errors.ts+++ b/packages/hoppscotch-backend/src/errors.ts@@ -189,6 +189,12 @@ export const TEAM_FB_COLL_PATH_RESOLVE_FAIL = 'team/fb_coll_path_resolve_fail';*/export const TEAM_COLL_NOT_FOUND = 'team_coll/collection_not_found';+/**+ * The collection does not have the same parent as the expected parent+ * (TeamCollectionService)+ */+export const TEAM_COLL_NOT_SAME_PARENT = 'team_coll/not_same_parent';+/*** Could not find the team in the database* (TeamCollectionService)@@ -221,13 +227,6 @@ export const TEAM_COLL_DEST_SAME =export const TEAM_COL_ALREADY_ROOT ='team_coll/target_collection_is_already_root_collection';-/**- * Collections have different parents- * (TeamCollectionService)- */-export const TEAM_COL_NOT_SAME_PARENT =- 'team_coll/team_collections_have_different_parents';-/*** Collection and next Collection are the same* (TeamCollectionService)diff --git a/packages/hoppscotch-backend/src/infra-config/infra-config.model.ts b/packages/hoppscotch-backend/src/infra-config/infra-config.model.tsindex 7962c6965..48051eb7c 100644--- a/packages/hoppscotch-backend/src/infra-config/infra-config.model.ts+++ b/packages/hoppscotch-backend/src/infra-config/infra-config.model.ts@@ -5,7 +5,7 @@ import { ServiceStatus } from './helper';@ObjectType()export class InfraConfig {- @Field({+ @Field(() => InfraConfigEnum, {description: 'Infra Config Name',})name: InfraConfigEnum;diff --git a/packages/hoppscotch-backend/src/mock-server/mock-server.controller.ts b/packages/hoppscotch-backend/src/mock-server/mock-server.controller.tsindex 8872bba98..dcf431431 100644--- a/packages/hoppscotch-backend/src/mock-server/mock-server.controller.ts+++ b/packages/hoppscotch-backend/src/mock-server/mock-server.controller.ts@@ -93,6 +93,9 @@ export class MockServerController {method,queryParams,requestHeaders,+ // Parsed by the global express.json() middleware — needed for+ // GraphQL operation-based matching ({query, operationName, variables})+ req.body,);if (E.isLeft(result)) {diff --git a/packages/hoppscotch-backend/src/mock-server/mock-server.service.spec.ts b/packages/hoppscotch-backend/src/mock-server/mock-server.service.spec.tsindex 4f6ba1a77..0e84b6190 100644--- a/packages/hoppscotch-backend/src/mock-server/mock-server.service.spec.ts+++ b/packages/hoppscotch-backend/src/mock-server/mock-server.service.spec.ts@@ -2070,4 +2070,446 @@ describe('MockServerService', () => {expect(result.queryParams).toEqual({});});});++ describe('handleMockRequest — GraphQL', () => {+ const gqlExample = {+ key: 'gql1',+ name: 'Get User Example',+ endpoint: null,+ method: null,+ operationName: 'GetUser',+ operationType: 'query',+ statusCode: 200,+ statusText: 'OK',+ responseBody: '{"data":{"user":{"id":"1"}}}',+ responseHeaders: [{ key: 'content-type', value: 'application/json' }],+ headers: [],+ };++ const gqlUserRequest = {+ id: 'gqlreq1',+ collectionID: userCollection.id,+ teamID: null,+ title: 'Get User',+ request: {},+ mockExamples: {+ examples: [gqlExample],+ },+ orderIndex: 1,+ createdOn: currentTime,+ updatedOn: currentTime,+ } as any;++ const setupMocks = (requests: any[]) => {+ mockPrisma.userCollection.findUnique.mockResolvedValue(userCollection);+ mockPrisma.userCollection.findMany.mockResolvedValue([]);+ mockPrisma.userRequest.findMany.mockResolvedValue(requests as any);+ };++ test('matches a GraphQL example by operation name and type', async () => {+ setupMocks([gqlUserRequest]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ { query: 'query GetUser { user { id } }' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).statusCode).toBe(200);+ expect((result.right as any).body).toBe('{"data":{"user":{"id":"1"}}}');+ }+ });++ test('exact operation-name match beats a wildcard example', async () => {+ const wildcardExample = {+ ...gqlExample,+ key: 'gql-wild',+ name: 'Any Query',+ operationName: null,+ responseBody: '{"data":{"wildcard":true}}',+ };+ setupMocks([+ {+ ...gqlUserRequest,+ mockExamples: { examples: [wildcardExample, gqlExample] },+ },+ ]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ { query: 'query GetUser { user { id } }' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).body).toBe('{"data":{"user":{"id":"1"}}}');+ }+ });++ test('wildcard example matches an unnamed operation of the same type', async () => {+ const wildcardExample = {+ ...gqlExample,+ key: 'gql-wild',+ name: 'Any Query',+ operationName: null,+ responseBody: '{"data":{"wildcard":true}}',+ };+ setupMocks([+ {+ ...gqlUserRequest,+ mockExamples: { examples: [wildcardExample] },+ },+ ]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ { query: '{ user { id } }' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).body).toBe('{"data":{"wildcard":true}}');+ }+ });++ test('operation type mismatch returns Left', async () => {+ setupMocks([gqlUserRequest]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ { query: 'mutation GetUser { updateUser { id } }' },+ );++ expect(E.isLeft(result)).toBe(true);+ });++ test('matches a large query', async () => {+ setupMocks([gqlUserRequest]);++ const large = `query GetUser { user { id ${'alias: id '.repeat(+ 5_000,+ )} } }`;++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ { query: large },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).body).toBe('{"data":{"user":{"id":"1"}}}');+ }+ });++ test('anonymous multi-operation document without operationName returns 400 errors body', async () => {+ setupMocks([gqlUserRequest]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ {+ query: 'query GetUser { user { id } } query Other { other { id } }',+ },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).statusCode).toBe(400);+ expect((result.right as any).body).toContain('operationName');+ }+ });++ test('multi-operation document with operationName selects the named operation', async () => {+ setupMocks([gqlUserRequest]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ {+ query: 'query GetUser { user { id } } query Other { other { id } }',+ operationName: 'GetUser',+ },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).statusCode).toBe(200);+ }+ });++ test('unparseable query falls through to REST matching', async () => {+ const restExample = {+ key: 'rest1',+ name: 'REST Example',+ method: 'POST',+ endpoint: 'http://api.example.com/search',+ statusCode: 200,+ statusText: 'OK',+ responseBody: '{"rest":true}',+ responseHeaders: [],+ headers: [],+ };+ setupMocks([+ {+ ...gqlUserRequest,+ mockExamples: { examples: [restExample] },+ },+ ]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/search',+ 'POST',+ {},+ {},+ { query: 'SELECT * FROM users' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).body).toBe('{"rest":true}');+ }+ });++ // Regression: operation stamping only exists in clients shipping the+ // unified playground, so every example in an already-deployed database is+ // unstamped. A parseable GraphQL body must not divert into operation+ // matching when the mock owns no GraphQL examples — doing so 404s every+ // pre-existing REST mock of a GraphQL-over-HTTP endpoint.+ const unstampedGraphqlRestExample = {+ key: 'rest-gql',+ name: 'Legacy GraphQL Mock',+ method: 'POST',+ endpoint: 'http://api.example.com/graphql',+ statusCode: 200,+ statusText: 'OK',+ responseBody: '{"data":{"legacy":true}}',+ responseHeaders: [],+ headers: [],+ };++ test('parseable GraphQL body falls through to REST when no example is operation-stamped', async () => {+ setupMocks([+ {+ ...gqlUserRequest,+ mockExamples: { examples: [unstampedGraphqlRestExample] },+ },+ ]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ { query: 'query GetUser { user { id } }' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).body).toBe('{"data":{"legacy":true}}');+ }+ });++ test('x-mock-response-name still resolves when no example is operation-stamped', async () => {+ setupMocks([+ {+ ...gqlUserRequest,+ mockExamples: { examples: [unstampedGraphqlRestExample] },+ },+ ]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ { 'x-mock-response-name': 'Legacy GraphQL Mock' },+ { query: 'query GetUser { user { id } }' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).body).toBe('{"data":{"legacy":true}}');+ }+ });++ test('GraphQL operation with no matching stamped example falls back to REST scoring', async () => {+ setupMocks([+ {+ ...gqlUserRequest,+ mockExamples: {+ // A stamped mutation example plus a plain REST example on the same+ // path — an unmatched *query* must reach the REST example, not 404+ examples: [+ { ...gqlExample, operationType: 'mutation', operationName: 'Nope' },+ unstampedGraphqlRestExample,+ ],+ },+ },+ ]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ { query: 'query GetUser { user { id } }' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).body).toBe('{"data":{"legacy":true}}');+ }+ });++ test('x-mock-response-name override picks the named GraphQL example', async () => {+ const otherExample = {+ ...gqlExample,+ key: 'gql2',+ name: 'Error Case',+ statusCode: 500,+ responseBody: '{"errors":[{"message":"boom"}]}',+ };+ setupMocks([+ {+ ...gqlUserRequest,+ mockExamples: { examples: [gqlExample, otherExample] },+ },+ ]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ { 'x-mock-response-name': 'Error Case' },+ { query: 'query GetUser { user { id } }' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).statusCode).toBe(500);+ }+ });++ test('x-mock-response-name override does not cross operation types', async () => {+ // A query example and a mutation example share the name 'Shared Name'.+ // A mutation request naming it must not resolve to the query example.+ const queryNamed = {+ ...gqlExample,+ key: 'gql-q',+ name: 'Shared Name',+ operationType: 'query',+ responseBody: '{"data":{"fromQuery":true}}',+ };+ const mutationNamed = {+ ...gqlExample,+ key: 'gql-m',+ name: 'Shared Name',+ operationName: 'UpdateUser',+ operationType: 'mutation',+ responseBody: '{"data":{"fromMutation":true}}',+ };+ setupMocks([+ {+ ...gqlUserRequest,+ mockExamples: { examples: [queryNamed, mutationNamed] },+ },+ ]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ { 'x-mock-response-name': 'Shared Name' },+ { query: 'mutation UpdateUser { updateUser { id } }' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).body).toBe(+ '{"data":{"fromMutation":true}}',+ );+ }+ });++ test('treats an empty-string operationName as unspecified', async () => {+ setupMocks([gqlUserRequest]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ { query: 'query GetUser { user { id } }', operationName: '' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).statusCode).toBe(200);+ expect((result.right as any).body).toBe('{"data":{"user":{"id":"1"}}}');+ }+ });++ test('prefers a 200 example among equal-score matches', async () => {+ const error500 = {+ ...gqlExample,+ key: 'gql-a-500',+ name: 'Failure',+ statusCode: 500,+ responseBody: '{"errors":[{"message":"boom"}]}',+ };+ setupMocks([+ {+ ...gqlUserRequest,+ mockExamples: { examples: [error500, gqlExample] },+ },+ ]);++ const result = await mockServerService.handleMockRequest(+ dbMockServer,+ '/graphql',+ 'POST',+ {},+ {},+ { query: 'query GetUser { user { id } }' },+ );++ expect(E.isRight(result)).toBe(true);+ if (E.isRight(result)) {+ expect((result.right as any).statusCode).toBe(200);+ }+ });+ });});diff --git a/packages/hoppscotch-backend/src/mock-server/mock-server.service.ts b/packages/hoppscotch-backend/src/mock-server/mock-server.service.tsindex 6efbb8a4e..7578cfd56 100644--- a/packages/hoppscotch-backend/src/mock-server/mock-server.service.ts+++ b/packages/hoppscotch-backend/src/mock-server/mock-server.service.ts@@ -21,6 +21,7 @@ import {MOCK_SERVER_COLLECTION_CREATION_FAILED,} from 'src/errors';import { randomBytes } from 'crypto';+import { parse, getOperationAST } from 'graphql';import { WorkspaceType } from 'src/types/WorkspaceTypes';import {MockServerAction,@@ -37,6 +38,23 @@ import { ReqType } from 'src/types/RequestTypes';import { AuthUser } from 'src/types/AuthUser';import { mockServerCollRequestExample } from './constants/mock-server-coll-request-example';+/**+ * A saved example carrying GraphQL operation identity, projected by the+ * `sync_mock_examples` trigger. Examples saved before operation stamping+ * existed (i.e. every example in an already-deployed database) have no+ * `operationType` and are not GraphQL examples.+ */+interface GqlExample {+ id: string;+ name: string;+ operationName: string | null;+ operationType: string;+ statusCode: number;+ statusText: string;+ responseBody: string;+ responseHeaders: Array<{ key: string; value: string }>;+}+@Injectable()export class MockServerService {constructor(@@ -714,6 +732,7 @@ export class MockServerService {method: string,queryParams?: Record<string, string>,requestHeaders?: Record<string, string>,+ requestBody?: unknown,): Promise<E.Either<string, MockServerResponse>> {try {// OPTIMIZATION: Fetch collection IDs once (recursive DB query)@@ -733,6 +752,56 @@ export class MockServerService {collectionIds,);+ // GraphQL branch: a body that parses as a GraphQL document routes to+ // operation-based matching instead of path scoring. A body that merely+ // LOOKS GraphQL-ish but fails to parse falls through to REST matching,+ // so REST payloads that happen to carry a `query` field keep working.+ //+ // The branch is gated on this mock actually owning GraphQL-stamped+ // examples. Operation stamping only exists in clients that ship the+ // unified playground, so every example in an already-deployed database+ // is unstamped — without the gate, a mock that has always served+ // `POST /graphql` from a REST example would start returning 404 on+ // upgrade, with no way back (the divert precedes the+ // `x-mock-response-id`/`-name` override below).+ //+ // The example gate is evaluated FIRST, and deliberately so: collecting+ // examples is an in-memory pass over rows already fetched above, whereas+ // parsing allocates an AST several times the size of its input. This+ // endpoint is public (throttled only), so a mock that could not use the+ // result should never reach the parser.+ const gqlExamples = this.collectGraphQLExamples(requests);+ if (gqlExamples.length > 0) {+ const gqlOperation = this.resolveGraphQLOperation(requestBody);++ if (gqlOperation) {+ if (E.isLeft(gqlOperation)) {+ // Genuinely GraphQL (parsed) but unresolvable operation —+ // respond per GraphQL-over-HTTP instead of a REST-style 404+ return E.right({+ statusCode: 400,+ body: JSON.stringify({+ errors: [{ message: gqlOperation.left }],+ }),+ headers: JSON.stringify({ 'content-type': 'application/json' }),+ delay: mockServer.delayInMs || 0,+ });+ }++ const gqlResult = this.handleGraphQLMockRequest(+ gqlOperation.right,+ gqlExamples,+ requestHeaders,+ mockServer.delayInMs,+ );++ // A mixed collection can hold GraphQL examples that don't cover this+ // operation while still holding a REST example for the same path, so+ // a miss falls through to REST scoring rather than terminating in 404.+ if (E.isRight(gqlResult)) return gqlResult;+ }+ }+// OPTIMIZATION: Check for custom headers first (fastest path)// If user specified exact example, return it immediately without scoringif (requestHeaders) {@@ -1175,6 +1244,153 @@ export class MockServerService {/*** Format example response for return*/+ /**+ * Resolve the executed GraphQL operation from a request body.+ *+ * Returns `null` when the body is not a GraphQL payload (missing/non-string+ * `query`, or a `query` that fails GraphQL parsing — the latter deliberately+ * falls through to REST matching so REST payloads carrying a `query` field+ * are never misclassified). Returns `Left` only for genuinely-GraphQL+ * documents whose operation can't be resolved (anonymous multi-operation+ * documents without an `operationName`).+ */+ private resolveGraphQLOperation(+ body: unknown,+ ): null | E.Either<string, { name: string | null; type: string }> {+ if (!body || typeof body !== 'object' || Array.isArray(body)) return null;++ const query = (body as Record<string, unknown>).query;+ if (typeof query !== 'string' || query.trim().length === 0) return null;++ let doc;+ try {+ doc = parse(query);+ } catch (_e) {+ return null;+ }++ const rawOpName = (body as Record<string, unknown>).operationName;+ const node = getOperationAST(+ doc,+ typeof rawOpName === 'string' && rawOpName.length > 0+ ? rawOpName+ : undefined,+ );+ if (!node) {+ return E.left(+ 'Must provide operationName if query contains multiple operations.',+ );+ }++ return E.right({ name: node.name?.value ?? null, type: node.operation });+ }++ /**+ * Operation-based matching for GraphQL mock requests — the GraphQL+ * counterpart of the path/query scoring pipeline. GraphQL examples are+ * discriminated by SHAPE (presence of `operationType`, stamped by the app+ * and projected by the `sync_mock_examples` trigger). Team requests carry+ * no REST/GQL discriminator of their own, so shape is the only signal:+ * GraphQL requests live alongside REST ones in the same rows by design.+ */+ private collectGraphQLExamples(+ requests: Array<{ id: string; mockExamples: any }>,+ ): GqlExample[] {+ const examples: GqlExample[] = [];+ for (const request of requests) {+ const mockExamples = request.mockExamples as any;+ if (!Array.isArray(mockExamples?.examples)) continue;+ for (const exampleData of mockExamples.examples) {+ if (typeof exampleData?.operationType !== 'string') continue;+ examples.push({+ id: exampleData.key || `${request.id}-${exampleData.name}`,+ name: exampleData.name || '',+ operationName: exampleData.operationName || null,+ operationType: exampleData.operationType,+ statusCode: exampleData.statusCode || 200,+ statusText: exampleData.statusText || 'OK',+ responseBody: exampleData.responseBody || '',+ responseHeaders: Array.isArray(exampleData.responseHeaders)+ ? exampleData.responseHeaders+ : [],+ });+ }+ }+ return examples;+ }++ private handleGraphQLMockRequest(+ operation: { name: string | null; type: string },+ examples: GqlExample[],+ requestHeaders: Record<string, string> | undefined,+ delayInMs: number,+ ): E.Either<string, MockServerResponse> {+ if (examples.length === 0) {+ return E.left(+ `No GraphQL mock examples found for ${operation.type} ${operation.name ?? '(anonymous)'}`,+ );+ }++ // x-mock-response-id / x-mock-response-name: exact-example override,+ // bypassing scoring. The REST fast path gates its override on the HTTP+ // method; over GraphQL the method carries no meaning, so the operation+ // type is the equivalent discriminator — a mutation request must never+ // resolve to a query example just because the names collide.+ const overrideId = requestHeaders?.['x-mock-response-id'];+ const overrideName = requestHeaders?.['x-mock-response-name'];+ if (overrideId || overrideName) {+ const exact = examples.find(+ (ex) =>+ ex.operationType === operation.type &&+ ((overrideId && ex.id === overrideId) ||+ (overrideName && ex.name === overrideName)),+ );+ if (exact) return this.formatExampleResponse(exact, delayInMs);+ }++ // x-mock-response-code: status pre-filter with silent fallback (REST parity)+ let filtered = examples;+ const overrideCode = requestHeaders?.['x-mock-response-code'];+ if (overrideCode) {+ const statusCode = parseInt(overrideCode, 10);+ const codeFiltered = examples.filter(+ (ex) => ex.statusCode === statusCode,+ );+ if (codeFiltered.length > 0) filtered = codeFiltered;+ }++ // Scoring: operation type must match; exact operation-name match beats a+ // wildcard example (one saved without an operation name); anything else+ // is a non-match. Anonymous request operations match only wildcards.+ const scored = filtered+ .map((example) => {+ if (example.operationType !== operation.type)+ return { example, score: 0 };+ if (example.operationName === operation.name)+ return { example, score: 100 };+ if (!example.operationName) return { example, score: 95 };+ return { example, score: 0 };+ })+ .filter((s) => s.score > 0)+ .sort((a, b) => b.score - a.score);++ if (scored.length === 0) {+ return E.left(+ `No matching GraphQL mock example for ${operation.type} ${operation.name ?? '(anonymous)'}`,+ );+ }++ // Deterministic selection among ties: prefer 200s (REST parity), then+ // lexicographic example id — unlike REST, never DB row order+ const highest = scored[0].score;+ const top = scored+ .filter((s) => s.score === highest)+ .sort((a, b) => a.example.id.localeCompare(b.example.id));+ const selected = top.find((s) => s.example.statusCode === 200) ?? top[0];++ return this.formatExampleResponse(selected.example, delayInMs);+ }+private formatExampleResponse(example: any,delayInMs: number,diff --git a/packages/hoppscotch-backend/src/shortcode/shortcode.model.ts b/packages/hoppscotch-backend/src/shortcode/shortcode.model.tsindex 635312a8e..f8295c553 100644--- a/packages/hoppscotch-backend/src/shortcode/shortcode.model.ts+++ b/packages/hoppscotch-backend/src/shortcode/shortcode.model.ts@@ -60,7 +60,7 @@ export class ShortcodeWithUserEmail {})createdOn: Date;- @Field({+ @Field(() => ShortcodeCreator, {description: 'Details of user who created the shortcode',nullable: true,})diff --git a/packages/hoppscotch-backend/src/shortcode/shortcode.service.spec.ts b/packages/hoppscotch-backend/src/shortcode/shortcode.service.spec.tsindex 672dfd86c..b76dc9b03 100644--- a/packages/hoppscotch-backend/src/shortcode/shortcode.service.spec.ts+++ b/packages/hoppscotch-backend/src/shortcode/shortcode.service.spec.ts@@ -99,7 +99,7 @@ const shortcodesWithUserEmail = [creatorUid: user.uid,createdOn: new Date(),updatedOn: createdOn,- User: user,+ user: user,},{id: 'blablabla1',@@ -112,7 +112,7 @@ const shortcodesWithUserEmail = [creatorUid: user.uid,createdOn: new Date(),updatedOn: createdOn,- User: user,+ user: user,},];diff --git a/packages/hoppscotch-backend/src/shortcode/shortcode.service.ts b/packages/hoppscotch-backend/src/shortcode/shortcode.service.tsindex 70a59c5e9..f230f7d51 100644--- a/packages/hoppscotch-backend/src/shortcode/shortcode.service.ts+++ b/packages/hoppscotch-backend/src/shortcode/shortcode.service.ts@@ -298,7 +298,7 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {const shortCodes = await this.prisma.shortcode.findMany({where: userEmail? {- User: {+ user: {email: {equals: userEmail,mode: 'insensitive',@@ -313,7 +313,7 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {take: args.take,cursor: args.cursor ? { id: args.cursor } : undefined,include: {- User: true,+ user: true,},});@@ -327,10 +327,10 @@ export class ShortcodeService implements UserDataHandler, OnModuleInit {? JSON.stringify(code.embedProperties): null,createdOn: code.createdOn,- creator: code.User+ creator: code.user? {- uid: code.User.uid,- email: code.User.email,+ uid: code.user.uid,+ email: code.user.email,}: null,};diff --git a/packages/hoppscotch-backend/src/team-collection/team-collection.model.ts b/packages/hoppscotch-backend/src/team-collection/team-collection.model.tsindex d34a290f8..1c4975235 100644--- a/packages/hoppscotch-backend/src/team-collection/team-collection.model.ts+++ b/packages/hoppscotch-backend/src/team-collection/team-collection.model.ts@@ -27,12 +27,12 @@ export class TeamCollection {@ObjectType()export class CollectionReorderData {- @Field({+ @Field(() => TeamCollection, {description: 'Team Collection being moved',})collection: TeamCollection;- @Field({+ @Field(() => TeamCollection, {description:'Team Collection succeeding the collection being moved in its new position',nullable: true,diff --git a/packages/hoppscotch-backend/src/team-collection/team-collection.resolver.ts b/packages/hoppscotch-backend/src/team-collection/team-collection.resolver.tsindex 25e89dcaa..7a559d8b0 100644--- a/packages/hoppscotch-backend/src/team-collection/team-collection.resolver.ts+++ b/packages/hoppscotch-backend/src/team-collection/team-collection.resolver.ts@@ -164,12 +164,12 @@ export class TeamCollectionResolver {type: () => ID,})collectionID: string,- ) {+ ): Promise<TeamCollection> {const teamCollections =await this.teamCollectionService.getCollection(collectionID);if (E.isLeft(teamCollections)) throwErr(teamCollections.left);- return <TeamCollection>{+ return {id: teamCollections.right.id,title: teamCollections.right.title,parentID: teamCollections.right.parentID,diff --git a/packages/hoppscotch-backend/src/team-collection/team-collection.service.spec.ts b/packages/hoppscotch-backend/src/team-collection/team-collection.service.spec.tsindex 8488da37b..e109a4f87 100644--- a/packages/hoppscotch-backend/src/team-collection/team-collection.service.spec.ts+++ b/packages/hoppscotch-backend/src/team-collection/team-collection.service.spec.ts@@ -9,6 +9,7 @@ import {TEAM_COLL_INVALID_JSON,TEAM_COLL_IS_PARENT_COLL,TEAM_COLL_NOT_FOUND,+ TEAM_COLL_NOT_SAME_PARENT,TEAM_COLL_NOT_SAME_TEAM,TEAM_COLL_SHORT_TITLE,TEAM_COL_ALREADY_ROOT,@@ -675,9 +676,7 @@ describe('createCollection', () => {});test('should throw TEAM_NOT_OWNER when parent TeamCollection does not belong to the team', async () => {- jest- .spyOn(teamCollectionService as any, 'isOwnerCheck')- .mockResolvedValueOnce(O.none);+ mockPrisma.teamCollection.findFirst.mockResolvedValueOnce(null);const result = await teamCollectionService.createCollection(rootTeamCollection.teamID,@@ -688,10 +687,10 @@ describe('createCollection', () => {expect(result).toEqualLeft(TEAM_NOT_OWNER);});- test('should throw TEAM_COLL_DATA_INVALID when parent TeamCollection does not belong to the team', async () => {- jest- .spyOn(teamCollectionService as any, 'isOwnerCheck')- .mockResolvedValueOnce(O.some(true));+ test('should throw TEAM_COLL_DATA_INVALID when the data is invalid JSON', async () => {+ mockPrisma.teamCollection.findFirst.mockResolvedValueOnce({+ ...rootTeamCollection,+ });const result = await teamCollectionService.createCollection(rootTeamCollection.teamID,@@ -720,9 +719,10 @@ describe('createCollection', () => {});test('should successfully create a new child TeamCollection with valid inputs', async () => {- jest- .spyOn(teamCollectionService as any, 'isOwnerCheck')- .mockResolvedValueOnce(O.some(true));+ // parent ownership check+ mockPrisma.teamCollection.findFirst.mockResolvedValueOnce({+ ...rootTeamCollection,+ });mockPrisma.$transaction.mockImplementationOnce(async (fn) =>fn(mockPrisma),);@@ -740,9 +740,10 @@ describe('createCollection', () => {});test('should send pubsub message to "team_coll/<teamID>/coll_added" if child TeamCollection is created successfully', async () => {- jest- .spyOn(teamCollectionService as any, 'isOwnerCheck')- .mockResolvedValueOnce(O.some(true));+ // parent ownership check+ mockPrisma.teamCollection.findFirst.mockResolvedValueOnce({+ ...rootTeamCollection,+ });mockPrisma.$transaction.mockImplementationOnce(async (fn) =>fn(mockPrisma),);@@ -1338,6 +1339,33 @@ describe('updateCollectionOrder', () => {expect(result).toEqualLeft(TEAM_COLL_NOT_SAME_TEAM);});+ test('should throw TEAM_COLL_NOT_SAME_PARENT if collection and nextCollection have different parents', async () => {+ // getCollection; both collections belong to the same team but sit under+ // different parents, so reordering between them is not a valid operation+ mockPrisma.teamCollection.findUniqueOrThrow+ .mockResolvedValueOnce(childTeamCollectionList[4])+ .mockResolvedValueOnce(childTeamCollection_2);++ const result = await teamCollectionService.updateCollectionOrder(+ childTeamCollectionList[4].id,+ childTeamCollection_2.id,+ );+ expect(result).toEqualLeft(TEAM_COLL_NOT_SAME_PARENT);+ });++ test('should not reorder when collection and nextCollection have different parents', async () => {+ mockPrisma.teamCollection.findUniqueOrThrow+ .mockResolvedValueOnce(childTeamCollectionList[4])+ .mockResolvedValueOnce(childTeamCollection_2);++ await teamCollectionService.updateCollectionOrder(+ childTeamCollectionList[4].id,+ childTeamCollection_2.id,+ );+ expect(mockPrisma.$transaction).not.toHaveBeenCalled();+ expect(mockPubSub.publish).not.toHaveBeenCalled();+ });+test('should successfully update the order of the child TeamCollection list', async () => {// getCollection;mockPrisma.teamCollection.findUniqueOrThrow@@ -1451,6 +1479,21 @@ describe('importCollectionsFromJSON', () => {expect(result).toEqualLeft(TEAM_COLL_INVALID_JSON);});+ test('should throw TEAM_NOT_OWNER when the parent collection does not belong to the team', async () => {+ // getCollection (parent lookup)+ mockPrisma.teamCollection.findUniqueOrThrow.mockResolvedValueOnce({+ ...rootTeamCollection,+ teamID: 'another-team-id',+ });++ const result = await teamCollectionService.importCollectionsFromJSON(+ jsonString,+ rootTeamCollection.teamID,+ rootTeamCollection.id,+ );+ expect(result).toEqualLeft(TEAM_NOT_OWNER);+ });+test('should successfully create new TeamCollections in root and TeamRequests with valid inputs', async () => {mockPrisma.$transaction.mockImplementation(async (fn) => fn(mockPrisma));mockPrisma.teamCollection.findFirst.mockResolvedValueOnce(null);@@ -1465,6 +1508,10 @@ describe('importCollectionsFromJSON', () => {});test('should successfully create new TeamCollections in a child collection and TeamRequests with valid inputs', async () => {+ // getCollection (parent lookup)+ mockPrisma.teamCollection.findUniqueOrThrow.mockResolvedValueOnce({+ ...rootTeamCollection,+ });mockPrisma.$transaction.mockImplementation(async (fn) => fn(mockPrisma));mockPrisma.teamCollection.findFirst.mockResolvedValueOnce(null);mockPrisma.teamCollection.create.mockResolvedValueOnce(rootTeamCollection);diff --git a/packages/hoppscotch-backend/src/team-collection/team-collection.service.ts b/packages/hoppscotch-backend/src/team-collection/team-collection.service.tsindex 40a98e76d..95d915ae5 100644--- a/packages/hoppscotch-backend/src/team-collection/team-collection.service.ts+++ b/packages/hoppscotch-backend/src/team-collection/team-collection.service.ts@@ -20,6 +20,7 @@ import {TEAM_COLL_PARENT_TREE_GEN_FAILED,TEAM_MEMBER_NOT_FOUND,TEAM_COLL_CREATION_FAILED,+ TEAM_COLL_NOT_SAME_PARENT,} from '../errors';import { PubSubService } from '../pubsub/pubsub.service';import {@@ -210,6 +211,15 @@ export class TeamCollectionService {if (!Array.isArray(collectionsList.right))return E.left(TEAM_COLL_INVALID_JSON);+ // When importing into an existing parent, ensure the parent belongs to+ // the team+ if (parentID) {+ const parentCollection = await this.getCollection(parentID);+ if (E.isLeft(parentCollection)) return E.left(TEAM_COLL_NOT_FOUND);+ if (parentCollection.right.teamID !== teamID)+ return E.left(TEAM_NOT_OWNER);+ }+let teamCollections: DBTeamCollection[] = [];let queryList: Prisma.TeamCollectionCreateInput[] = [];try {@@ -279,7 +289,7 @@ export class TeamCollectionService {private cast(teamCollection: DBTeamCollection): TeamCollection {const data = transformCollectionData(teamCollection.data);- return <TeamCollection>{+ return {id: teamCollection.id,title: teamCollection.title,parentID: teamCollection.parentID,@@ -419,28 +429,6 @@ export class TeamCollectionService {}}- /**- * Check to see if Collection belongs to Team- *- * @param collectionID getChildCollectionsCount- * @param teamID The Team ID- * @returns An Option of a Boolean- */- private async isOwnerCheck(collectionID: string, teamID: string) {- try {- await this.prisma.teamCollection.findFirstOrThrow({- where: {- id: collectionID,- teamID,- },- });-- return O.some(true);- } catch (error) {- return O.none;- }- }-/*** Create a new TeamCollection*@@ -458,10 +446,13 @@ export class TeamCollectionService {const isTitleValid = isValidLength(title, this.TITLE_LENGTH);if (!isTitleValid) return E.left(TEAM_COLL_SHORT_TITLE);- // Check to see if parentTeamCollectionID belongs to this Team+ // Check that the parent collection belongs to this Teamif (parentID !== null) {- const isOwner = await this.isOwnerCheck(parentID, teamID);- if (O.isNone(isOwner)) return E.left(TEAM_NOT_OWNER);+ const parentCollection = await this.prisma.teamCollection.findFirst({+ where: { id: parentID, teamID },+ select: { id: true },+ });+ if (!parentCollection) return E.left(TEAM_NOT_OWNER);}if (data === '') return E.left(TEAM_COLL_DATA_INVALID);@@ -976,6 +967,10 @@ export class TeamCollectionService {if (collection.right.teamID !== subsequentCollection.right.teamID)return E.left(TEAM_COLL_NOT_SAME_TEAM);+ // Check if collection and subsequentCollection have the same parentID+ if (collection.right.parentID !== subsequentCollection.right.parentID)+ return E.left(TEAM_COLL_NOT_SAME_PARENT);+try {await this.prisma.$transaction(async (tx) => {try {diff --git a/packages/hoppscotch-backend/src/team-request/team-request.model.ts b/packages/hoppscotch-backend/src/team-request/team-request.model.tsindex 79363b4b5..ce93ee3f0 100644--- a/packages/hoppscotch-backend/src/team-request/team-request.model.ts+++ b/packages/hoppscotch-backend/src/team-request/team-request.model.ts@@ -30,12 +30,12 @@ export class TeamRequest {@ObjectType()export class RequestReorderData {- @Field({+ @Field(() => TeamRequest, {description: 'Team Request being moved',})request: TeamRequest;- @Field({+ @Field(() => TeamRequest, {description:'Team Request succeeding the request being moved in its new position',nullable: true,diff --git a/packages/hoppscotch-backend/src/team-request/team-request.service.spec.ts b/packages/hoppscotch-backend/src/team-request/team-request.service.spec.tsindex 3814844d0..d6baef933 100644--- a/packages/hoppscotch-backend/src/team-request/team-request.service.spec.ts+++ b/packages/hoppscotch-backend/src/team-request/team-request.service.spec.ts@@ -264,6 +264,7 @@ describe('createTeamRequest', () => {jest.spyOn(mockTeamCollectionService, 'getTeamOfCollection').mockResolvedValue(E.right(team));+ mockPrisma.teamCollection.findUnique.mockResolvedValue(teamCollection);mockPrisma.$transaction.mockImplementation(async (fn) => {return fn(mockPrisma);});@@ -271,13 +272,13 @@ describe('createTeamRequest', () => {mockPrisma.teamRequest.create.mockResolvedValue(dbRequest);const response = teamRequestService.createTeamRequest(- teamRequest.title,+ teamCollection.id,team.id,teamRequest.title,teamRequest.request,);- expect(response).resolves.toEqualRight(teamRequest);+ await expect(response).resolves.toEqualRight(teamRequest);});test('publishes creation to pubsub topic "team_req/<team_id>/req_created"', async () => {@@ -287,6 +288,7 @@ describe('createTeamRequest', () => {jest.spyOn(mockTeamCollectionService, 'getTeamOfCollection').mockResolvedValue(E.right(team));+ mockPrisma.teamCollection.findUnique.mockResolvedValue(teamCollection);mockPrisma.$transaction.mockImplementation(async (fn) => {return fn(mockPrisma);});@@ -294,7 +296,7 @@ describe('createTeamRequest', () => {mockPrisma.teamRequest.create.mockResolvedValue(dbRequest);await teamRequestService.createTeamRequest(- teamRequest.title,+ teamCollection.id,team.id,teamRequest.title,teamRequest.request,@@ -527,6 +529,7 @@ describe('findRequestAndNextRequest', () => {mockPrisma.teamRequest.findFirst.mockResolvedValueOnce(dbTeamRequests[0]).mockResolvedValueOnce(dbTeamRequests[4]);+ mockPrisma.teamCollection.findUnique.mockResolvedValueOnce(teamCollection);const result = await (teamRequestService as any).findRequestAndNextRequest(args.srcCollID,@@ -607,6 +610,54 @@ describe('findRequestAndNextRequest', () => {expect(result).toEqualLeft(TEAM_REQ_INVALID_TARGET_COLL_ID);});+ test('Should resolve left if the destination collection does not exist when nextRequestID is given', async () => {+ const args: MoveTeamRequestArgs = {+ srcCollID: teamRequests[0].collectionID,+ destCollID: 'non-existent-coll',+ requestID: teamRequests[0].id,+ nextRequestID: teamRequests[4].id,+ };++ mockPrisma.teamRequest.findFirst.mockResolvedValueOnce(dbTeamRequests[0]);+ mockPrisma.teamCollection.findUnique.mockResolvedValueOnce(null);++ const result = await (teamRequestService as any).findRequestAndNextRequest(+ args.srcCollID,+ args.requestID,+ args.destCollID,+ args.nextRequestID,+ );++ expect(result).toEqualLeft(TEAM_INVALID_COLL_ID);+ // The destination is validated before the nextRequest lookup, so only the+ // request itself should have been fetched+ expect(mockPrisma.teamRequest.findFirst).toHaveBeenCalledTimes(1);+ });+ test('Should resolve left if the destination collection belongs to a different team when nextRequestID is given', async () => {+ const args: MoveTeamRequestArgs = {+ srcCollID: teamRequests[0].collectionID,+ destCollID: 'cross-team-coll',+ requestID: teamRequests[0].id,+ nextRequestID: teamRequests[4].id,+ };++ mockPrisma.teamRequest.findFirst.mockResolvedValueOnce(dbTeamRequests[0]);+ mockPrisma.teamCollection.findUnique.mockResolvedValueOnce({+ ...teamCollection,+ id: 'cross-team-coll',+ teamID: 'different-team-id',+ });++ const result = await (teamRequestService as any).findRequestAndNextRequest(+ args.srcCollID,+ args.requestID,+ args.destCollID,+ args.nextRequestID,+ );++ expect(result).toEqualLeft(TEAM_REQ_INVALID_TARGET_COLL_ID);+ expect(mockPrisma.teamRequest.findFirst).toHaveBeenCalledTimes(1);+ });test('Should resolve left if the request is not found', () => {const args: MoveTeamRequestArgs = {srcCollID: teamRequests[0].collectionID,@@ -637,6 +688,7 @@ describe('findRequestAndNextRequest', () => {mockPrisma.teamRequest.findFirst.mockResolvedValueOnce(dbTeamRequests[0]).mockResolvedValueOnce(null);+ mockPrisma.teamCollection.findUnique.mockResolvedValueOnce(teamCollection);const result = (teamRequestService as any).findRequestAndNextRequest(args.srcCollID,diff --git a/packages/hoppscotch-backend/src/team-request/team-request.service.ts b/packages/hoppscotch-backend/src/team-request/team-request.service.tsindex 0faf18bc5..a43f58c0c 100644--- a/packages/hoppscotch-backend/src/team-request/team-request.service.ts+++ b/packages/hoppscotch-backend/src/team-request/team-request.service.ts@@ -35,7 +35,7 @@ export class TeamRequestService {* A helper function to cast the Prisma TeamRequest model to the TeamRequest model* @param tr TeamRequest model from Prisma*/- private cast(tr: DbTeamRequest) {+ private cast(tr: DbTeamRequest): TeamRequest {return {id: tr.id,collectionID: tr.collectionID,@@ -388,6 +388,17 @@ export class TeamRequestService {});if (!request) return E.left(TEAM_REQ_NOT_FOUND);+ // The destination collection must exist and belong to the same team as+ // the request+ const destCollection = await this.prisma.teamCollection.findUnique({+ where: { id: destCollID },+ select: { teamID: true },+ });+ if (!destCollection) return E.left(TEAM_INVALID_COLL_ID);+ if (destCollection.teamID !== request.teamID) {+ return E.left(TEAM_REQ_INVALID_TARGET_COLL_ID);+ }+let nextRequest = null;if (nextRequestID) {nextRequest = await this.prisma.teamRequest.findFirst({@@ -401,18 +412,6 @@ export class TeamRequestService {) {return E.left(TEAM_REQ_INVALID_TARGET_COLL_ID);}- } else {- // When nextRequestID is null, validate that the destination collection- // belongs to the same team as the request to prevent cross-team moves- const destCollection = await this.prisma.teamCollection.findUnique({- where: { id: destCollID },- select: { teamID: true },- });- if (!destCollection) return E.left(TEAM_INVALID_COLL_ID);-- if (destCollection.teamID !== request.teamID) {- return E.left(TEAM_REQ_INVALID_TARGET_COLL_ID);- }}return E.right({ request, nextRequest });diff --git a/packages/hoppscotch-backend/src/types/RequestTypes.ts b/packages/hoppscotch-backend/src/types/RequestTypes.tsindex 717db6ac7..2485251b5 100644--- a/packages/hoppscotch-backend/src/types/RequestTypes.ts+++ b/packages/hoppscotch-backend/src/types/RequestTypes.ts@@ -1,4 +1,10 @@+import { registerEnumType } from '@nestjs/graphql';+export enum ReqType {REST = 'REST',GQL = 'GQL',}++registerEnumType(ReqType, {+ name: 'ReqType',+});diff --git a/packages/hoppscotch-backend/src/user-collection/user-collections.model.ts b/packages/hoppscotch-backend/src/user-collection/user-collections.model.tsindex c7947c97a..1caf89421 100644--- a/packages/hoppscotch-backend/src/user-collection/user-collections.model.ts+++ b/packages/hoppscotch-backend/src/user-collection/user-collections.model.ts@@ -32,12 +32,12 @@ export class UserCollection {@ObjectType()export class UserCollectionReorderData {- @Field({+ @Field(() => UserCollection, {description: 'User Collection being moved',})userCollection: UserCollection;- @Field({+ @Field(() => UserCollection, {description:'User Collection succeeding the collection being moved in its new position',nullable: true,diff --git a/packages/hoppscotch-backend/src/user-history/user-history.model.ts b/packages/hoppscotch-backend/src/user-history/user-history.model.tsindex c384391bc..71c420fe7 100644--- a/packages/hoppscotch-backend/src/user-history/user-history.model.ts+++ b/packages/hoppscotch-backend/src/user-history/user-history.model.ts@@ -1,4 +1,4 @@-import { Field, ID, ObjectType, registerEnumType } from '@nestjs/graphql';+import { Field, ID, ObjectType } from '@nestjs/graphql';import { ReqType } from 'src/types/RequestTypes';@ObjectType()@@ -51,7 +51,3 @@ export class UserHistoryDeletedManyData {})reqType: ReqType;}--registerEnumType(ReqType, {- name: 'ReqType',-});diff --git a/packages/hoppscotch-backend/src/user-request/user-request.model.ts b/packages/hoppscotch-backend/src/user-request/user-request.model.tsindex eb2987fdc..5cf17ac19 100644--- a/packages/hoppscotch-backend/src/user-request/user-request.model.ts+++ b/packages/hoppscotch-backend/src/user-request/user-request.model.ts@@ -36,12 +36,12 @@ export class UserRequest {@ObjectType()export class UserRequestReorderData {- @Field({+ @Field(() => UserRequest, {description: 'User request being moved',})request: UserRequest;- @Field({+ @Field(() => UserRequest, {description:'User request succeeding the request being moved in its new position',nullable: true,diff --git a/packages/hoppscotch-cli/README.md b/packages/hoppscotch-cli/README.mdindex 8a36a4202..f3e9e6117 100644--- a/packages/hoppscotch-cli/README.md+++ b/packages/hoppscotch-cli/README.md@@ -35,6 +35,35 @@ hopp [options or commands] arguments- Outputs the response of each request.- Executes and outputs test-script response.+ #### GraphQL support:++ Collections can freely mix REST and GraphQL requests — both run in+ collection order through the same pipeline (environment templating,+ the full auth surface, pre-request/test scripts, collection-level+ script inheritance, metrics, and reports).++ - GraphQL requests execute as GraphQL-over-HTTP: a `POST` with a JSON+ `{"query", "variables", "operationName"}` body.+ - The **first operation** in the document runs; for multi-operation+ documents its name is injected as `operationName` automatically.+ - Environment variables resolve anywhere in the request — URL, headers,+ the query (including a whole document stored in a variable), and+ **inside `variables`**, including bare non-string positions like+ `{ "count": <<n>> }`. Invalid `variables` JSON fails the request with+ an error instead of sending a broken body.+ - Test scripts assert on the GraphQL response body as parsed JSON, e.g.+ `pw.expect(pw.response.body.data.hello).toBe("world")`.+ - **Subscriptions cannot run** in a single HTTP round-trip: they are+ reported as request errors, the run continues, and the exit code is+ non-zero (matching the app's collection runner).++ Runnable examples live in+ [`src/__tests__/e2e/fixtures/`](./src/__tests__/e2e/fixtures/):+ `collections/mixed-rest-gql-coll.json` (REST + GraphQL, run with+ `--env environments/gql-envs.json`) and `collections/gql-coll.json`+ (GraphQL only). They run in CI against the public echo server at+ `https://echo.hoppscotch.io/graphql`.+#### Options:##### `-e, --env <file_path_or_id> `diff --git a/packages/hoppscotch-cli/package.json b/packages/hoppscotch-cli/package.jsonindex 8bdb1faa3..3709acb58 100644--- a/packages/hoppscotch-cli/package.json+++ b/packages/hoppscotch-cli/package.json@@ -46,6 +46,7 @@"axios-cookiejar-support": "6.0.5","chalk": "5.6.2","commander": "14.0.3",+ "graphql": "16.13.2","isolated-vm": "6.1.2","js-md5": "0.8.3","jsonc-parser": "3.3.1",diff --git a/packages/hoppscotch-cli/src/__tests__/e2e/commands/test.spec.ts b/packages/hoppscotch-cli/src/__tests__/e2e/commands/test.spec.tsindex 48b80b665..4b7a79036 100644--- a/packages/hoppscotch-cli/src/__tests__/e2e/commands/test.spec.ts+++ b/packages/hoppscotch-cli/src/__tests__/e2e/commands/test.spec.ts@@ -1514,4 +1514,33 @@ describe("hopp test [options] <file_path_or_id>", { timeout: 100000 }, () => {expect(result.error).toBeNull();});});++ describe("Test `hopp test <file_path_or_id>` command with GraphQL requests:", () => {+ test("Successfully runs an all-GraphQL collection, including pre-request scripts and header templating", async () => {+ const args = `test ${getTestJsonFilePath("gql-coll.json", "collection")}`;+ const result = await runCLIWithNetworkRetry(args);+ if (result === null) return;++ // Assert content so a regression back to skip-GraphQL can't pass+ expect(result.stdout).toContain("echoes the POST method");+ expect(result.stdout).toContain("scripted header echoed");+ expect(result.error).toBeNull();+ });++ test("Successfully runs a collection mixing REST and GraphQL requests, resolving environment variables from the supplied env file", async () => {+ const COLL_PATH = getTestJsonFilePath(+ "mixed-rest-gql-coll.json",+ "collection"+ );+ const ENV_PATH = getTestJsonFilePath("gql-envs.json", "environment");+ const args = `test ${COLL_PATH} --env ${ENV_PATH}`;+ const result = await runCLIWithNetworkRetry(args);+ if (result === null) return;++ expect(result.stdout).toContain("REST responds 200");+ expect(result.stdout).toContain("env templated header echoed");+ expect(result.stdout).toContain("anonymous query in nested folder");+ expect(result.error).toBeNull();+ });+ });});diff --git a/packages/hoppscotch-cli/src/__tests__/e2e/fixtures/collections/gql-coll.json b/packages/hoppscotch-cli/src/__tests__/e2e/fixtures/collections/gql-coll.jsonnew file mode 100644index 000000000..d78ab6303--- /dev/null+++ b/packages/hoppscotch-cli/src/__tests__/e2e/fixtures/collections/gql-coll.json@@ -0,0 +1,50 @@+[+ {+ "v": 1,+ "name": "GraphQL Only",+ "folders": [],+ "requests": [+ {+ "v": 10,+ "name": "Named query",+ "url": "https://echo.hoppscotch.io/graphql",+ "headers": [],+ "query": "query RequestInfo { method url }",+ "variables": "{}",+ "auth": { "authType": "none", "authActive": true },+ "description": null,+ "responses": {},+ "preRequestScript": "",+ "testScript": "pw.test(\"echoes the POST method\", () => { pw.expect(pw.response.body.data.method).toBe(\"POST\") })"+ },+ {+ "v": 10,+ "name": "Scripted auth header",+ "url": "https://echo.hoppscotch.io/graphql",+ "headers": [+ { "key": "Authorization", "value": "Bearer <<myToken>>", "active": true, "description": "" }+ ],+ "query": "query AuthEcho { headers { key value } }",+ "variables": "{}",+ "auth": { "authType": "none", "authActive": true },+ "description": null,+ "responses": {},+ "preRequestScript": "pw.env.set(\"myToken\", \"secret123\")",+ "testScript": "pw.test(\"scripted header echoed\", () => { const auth = pw.response.body.data.headers.find((h) => h.key === \"authorization\"); pw.expect(auth.value).toBe(\"Bearer secret123\") })"+ },+ {+ "v": 10,+ "name": "Anonymous query",+ "url": "https://echo.hoppscotch.io/graphql",+ "headers": [],+ "query": "{ url }",+ "variables": "{}",+ "auth": { "authType": "none", "authActive": true },+ "description": null,+ "responses": {},+ "preRequestScript": "",+ "testScript": ""+ }+ ]+ }+]diff --git a/packages/hoppscotch-cli/src/__tests__/e2e/fixtures/collections/mixed-rest-gql-coll.json b/packages/hoppscotch-cli/src/__tests__/e2e/fixtures/collections/mixed-rest-gql-coll.jsonnew file mode 100644index 000000000..3e10644f6--- /dev/null+++ b/packages/hoppscotch-cli/src/__tests__/e2e/fixtures/collections/mixed-rest-gql-coll.json@@ -0,0 +1,57 @@+[+ {+ "v": 1,+ "name": "Mixed REST GQL Suite",+ "folders": [+ {+ "v": 1,+ "name": "Inherited",+ "folders": [],+ "requests": [+ {+ "v": 10,+ "name": "GQL nested in folder",+ "url": "https://echo.hoppscotch.io/graphql",+ "headers": [],+ "query": "{ method }",+ "variables": "{}",+ "auth": { "authType": "none", "authActive": true },+ "description": null,+ "responses": {},+ "preRequestScript": "",+ "testScript": "pw.test(\"anonymous query in nested folder\", () => { pw.expect(pw.response.body.data.method).toBe(\"POST\") })"+ }+ ]+ }+ ],+ "requests": [+ {+ "v": "1",+ "name": "REST echo",+ "method": "GET",+ "endpoint": "https://echo.hoppscotch.io",+ "params": [],+ "headers": [],+ "preRequestScript": "",+ "testScript": "pw.test(\"REST responds 200\", () => { pw.expect(pw.response.status).toBe(200); pw.expect(pw.response.body.method).toBe(\"GET\") })",+ "auth": { "authType": "none", "authActive": true },+ "body": { "contentType": null, "body": null }+ },+ {+ "v": 10,+ "name": "GQL env templated header",+ "url": "https://echo.hoppscotch.io/graphql",+ "headers": [+ { "key": "x-hopp-greeting", "value": "<<greeting>>", "active": true, "description": "" }+ ],+ "query": "query GreetingEcho { headers { key value } }",+ "variables": "{}",+ "auth": { "authType": "none", "authActive": true },+ "description": null,+ "responses": {},+ "preRequestScript": "",+ "testScript": "pw.test(\"env templated header echoed\", () => { const greeting = pw.response.body.data.headers.find((h) => h.key === \"x-hopp-greeting\"); pw.expect(greeting.value).toBe(\"hello-world\") })"+ }+ ]+ }+]diff --git a/packages/hoppscotch-cli/src/__tests__/e2e/fixtures/environments/gql-envs.json b/packages/hoppscotch-cli/src/__tests__/e2e/fixtures/environments/gql-envs.jsonnew file mode 100644index 000000000..d9fbaef32--- /dev/null+++ b/packages/hoppscotch-cli/src/__tests__/e2e/fixtures/environments/gql-envs.json@@ -0,0 +1,13 @@+{+ "id": "gql-envs",+ "v": 2,+ "name": "gql-envs",+ "variables": [+ {+ "key": "greeting",+ "initialValue": "hello-world",+ "currentValue": "hello-world",+ "secret": false+ }+ ]+}diff --git a/packages/hoppscotch-cli/src/__tests__/unit/collection-fixtures.spec.ts b/packages/hoppscotch-cli/src/__tests__/unit/collection-fixtures.spec.tsnew file mode 100644index 000000000..6b356f143--- /dev/null+++ b/packages/hoppscotch-cli/src/__tests__/unit/collection-fixtures.spec.ts@@ -0,0 +1,112 @@+import { describe, expect, test } from "vitest";+import { Environment, isGQLRequest } from "@hoppscotch/data";+import { mkdtempSync, readFileSync, writeFileSync } from "fs";+import { tmpdir } from "os";+import { join } from "path";++import { parseCollectionData } from "../../utils/mutators";+import { getTestJsonFilePath } from "../utils";++describe("collection ingestion — mixed and GraphQL fixtures", () => {+ test("mixed-rest-gql-coll.json parses with REST and GraphQL requests in order", async () => {+ const collections = await parseCollectionData(+ getTestJsonFilePath("mixed-rest-gql-coll.json", "collection"),+ {}+ );++ expect(collections).toHaveLength(1);+ const [collection] = collections;++ expect(collection.requests.map((r) => isGQLRequest(r))).toEqual([+ false,+ true,+ ]);++ expect(collection.folders).toHaveLength(1);+ expect(collection.folders[0].requests.map((r) => isGQLRequest(r))).toEqual([+ true,+ ]);++ const gqlRequest = collection.requests[1];+ if (isGQLRequest(gqlRequest)) {+ expect(gqlRequest.query).toContain("query GreetingEcho");+ expect(gqlRequest.headers[0].value).toContain("<<greeting>>");+ }+ });++ test("gql-coll.json parses as an all-GraphQL collection", async () => {+ const collections = await parseCollectionData(+ getTestJsonFilePath("gql-coll.json", "collection"),+ {}+ );++ expect(collections).toHaveLength(1);+ const requests = collections[0].requests;+ expect(requests).toHaveLength(3);+ expect(requests.every((r) => isGQLRequest(r))).toBe(true);++ const scripted = requests[1];+ if (isGQLRequest(scripted)) {+ expect(scripted.query).toContain("query AuthEcho");+ expect(scripted.preRequestScript).toContain("pw.env.set");+ }+ });+++ test("old-version GQL requests migrate to the latest schema on ingestion", async () => {+ // v9 predates responses and the script fields+ const legacyCollection = [+ {+ v: 1,+ name: "Legacy",+ folders: [],+ requests: [+ {+ v: 9,+ name: "Legacy GQL",+ url: "https://echo.hoppscotch.io/graphql",+ headers: [],+ query: "query Hello { method }",+ variables: "{}",+ auth: { authType: "none", authActive: true },+ },+ ],+ },+ ];+ const file = join(+ mkdtempSync(join(tmpdir(), "hopp-gql-migration-")),+ "legacy-coll.json"+ );+ writeFileSync(file, JSON.stringify(legacyCollection));++ const collections = await parseCollectionData(file, {});+ const request = collections[0].requests[0];+ expect(isGQLRequest(request)).toBe(true);+ if (isGQLRequest(request)) {+ expect(request.v).toBe(10);+ expect(request.preRequestScript).toBe("");+ expect(request.testScript).toBe("");+ expect(request.responses).toEqual({});+ }+ });++ test("gql-envs.json is a latest-version environment export", () => {+ const contents = JSON.parse(+ readFileSync(getTestJsonFilePath("gql-envs.json", "environment"), "utf8")+ );++ const parsed = Environment.safeParse(contents);+ expect(parsed.type).toBe("ok");+ if (parsed.type === "ok") {+ expect(parsed.value.v).toBe(2);+ expect(parsed.value.variables).toEqual([+ {+ key: "greeting",+ initialValue: "hello-world",+ currentValue: "hello-world",+ secret: false,+ },+ ]);+ }+ });+});diff --git a/packages/hoppscotch-cli/src/__tests__/unit/gql-auth-body.spec.ts b/packages/hoppscotch-cli/src/__tests__/unit/gql-auth-body.spec.tsnew file mode 100644index 000000000..e5614ac8c--- /dev/null+++ b/packages/hoppscotch-cli/src/__tests__/unit/gql-auth-body.spec.ts@@ -0,0 +1,86 @@+import { describe, expect, test, vi } from "vitest";+import { Environment, HoppGQLRequest } from "@hoppscotch/data";+import * as E from "fp-ts/Either";++import { preProcessGQLRequest } from "../../utils/gql-request";++// Capture what the signer is constructed with — the signature has to be+// computed over the body actually sent, not the stub placeholder+const signerCalls = vi.hoisted(() => [] as Record<string, unknown>[]);++vi.mock("aws4fetch", () => ({+ AwsV4Signer: class {+ constructor(opts: Record<string, unknown>) {+ signerCalls.push(opts);+ }+ async sign() {+ return { headers: new Map(), url: new URL("https://example.com") };+ }+ },+}));++const { getEffectiveRESTRequest } = await import("../../utils/pre-request");++const collection = {+ v: 12,+ name: "Base",+ folders: [],+ requests: [],+ headers: [],+ auth: { authType: "none", authActive: false },+ variables: [],+ preRequestScript: "",+ testScript: "",+} as any;++const gqlRequest = {+ v: 10,+ name: "Signed GQL",+ url: "https://example.com/graphql",+ headers: [],+ query: "query Hello { hello }",+ variables: '{ "id": "1" }',+ auth: {+ authType: "aws-signature",+ authActive: true,+ accessKey: "AKIAEXAMPLE",+ secretKey: "secret",+ region: "us-east-1",+ serviceName: "execute-api",+ serviceToken: "",+ addTo: "HEADERS",+ },+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",+} as unknown as HoppGQLRequest;++const emptyEnv: Environment = {+ v: 2,+ id: "env",+ name: "env",+ variables: [],+};++describe("GraphQL requests with signing auth", () => {+ test("aws-signature signs the assembled GraphQL payload, not the empty stub body", async () => {+ signerCalls.length = 0;++ const stub = preProcessGQLRequest(gqlRequest, collection);+ // The stub carries a placeholder body until effective-request time+ expect(stub.body.body).toBe("");++ const result = await getEffectiveRESTRequest(stub, emptyEnv);+ expect(E.isRight(result)).toBe(true);++ expect(signerCalls).toHaveLength(1);+ const signedBody = signerCalls[0].body as string;++ expect(JSON.parse(signedBody)).toEqual({+ query: "query Hello { hello }",+ variables: { id: "1" },+ operationName: "Hello",+ });+ });+});diff --git a/packages/hoppscotch-cli/src/__tests__/unit/gql-request.spec.ts b/packages/hoppscotch-cli/src/__tests__/unit/gql-request.spec.tsnew file mode 100644index 000000000..f1ee14b0c--- /dev/null+++ b/packages/hoppscotch-cli/src/__tests__/unit/gql-request.spec.ts@@ -0,0 +1,325 @@+import { describe, expect, test } from "vitest";+import {+ EnvironmentVariable,+ HoppCollection,+ HoppGQLRequest,+} from "@hoppscotch/data";+import * as E from "fp-ts/Either";++import {+ GQLStubRequest,+ buildEffectiveGQLPayload,+ isGQLStubRequest,+ preProcessGQLRequest,+} from "../../utils/gql-request";++const baseCollection = {+ v: 12,+ name: "Base",+ folders: [],+ requests: [],+ headers: [],+ auth: { authType: "none", authActive: false },+ variables: [],+ preRequestScript: "",+ testScript: "",+} as unknown as HoppCollection;++const baseRequest: HoppGQLRequest = {+ v: 10,+ name: "Get Hello",+ url: "https://echo.hoppscotch.io/graphql",+ headers: [],+ query: "query HelloOp { hello }",+ variables: '{ "id": "1" }',+ auth: { authType: "none", authActive: true },+ description: null,+ responses: {},+ preRequestScript: 'pw.env.set("a", "b")',+ testScript: 'pw.test("t", () => {})',+};++const envs = (vars: Record<string, string>): EnvironmentVariable[] =>+ Object.entries(vars).map(([key, value]) => ({+ key,+ initialValue: value,+ currentValue: value,+ secret: false,+ }));++const stubFor = (+ request: Partial<HoppGQLRequest>,+ collection: HoppCollection = baseCollection+): GQLStubRequest =>+ preProcessGQLRequest({ ...baseRequest, ...request } as HoppGQLRequest, collection);++const payloadFor = (+ request: Partial<HoppGQLRequest>,+ variables: EnvironmentVariable[] = [],+ collection: HoppCollection = baseCollection+) => {+ const result = buildEffectiveGQLPayload(+ stubFor(request, collection),+ variables+ );+ expect(E.isRight(result)).toBe(true);+ return JSON.parse((result as E.Right<string>).right);+};++describe("preProcessGQLRequest", () => {+ test("builds a REST-shaped POST stub carrying scripts and the raw query/variables", () => {+ const stub = stubFor({});++ expect(stub.method).toBe("POST");+ expect(stub.endpoint).toBe("https://echo.hoppscotch.io/graphql");+ expect(stub.body.contentType).toBe("application/json");+ expect(stub.preRequestScript).toBe('pw.env.set("a", "b")');+ expect(stub.testScript).toBe('pw.test("t", () => {})');+ expect(stub.gqlRaw).toEqual({+ query: "query HelloOp { hello }",+ variables: '{ "id": "1" }',+ });+ expect(isGQLStubRequest(stub)).toBe(true);+ });++ test("falls back to 'Untitled Request' for unnamed requests", () => {+ expect(stubFor({ name: "" }).name).toBe("Untitled Request");+ });++ test("an inactive request header does not suppress a same-key active parent header", () => {+ const collection = {+ ...baseCollection,+ headers: [+ { key: "x-parent", value: "parent-value", active: true, description: "" },+ ],+ } as HoppCollection;++ const stub = stubFor(+ {+ headers: [+ { key: "x-parent", value: "child-value", active: false, description: "" },+ ],+ },+ collection+ );++ expect(stub.headers).toEqual([+ { key: "x-parent", value: "parent-value", active: true, description: "" },+ ]);+ });++ test("an active request header wins over a same-key parent header; inactive parents are dropped", () => {+ const collection = {+ ...baseCollection,+ headers: [+ { key: "x-shared", value: "parent-value", active: true, description: "" },+ { key: "x-off", value: "off", active: false, description: "" },+ ],+ } as HoppCollection;++ const stub = stubFor(+ {+ headers: [+ { key: "x-shared", value: "child-value", active: true, description: "" },+ ],+ },+ collection+ );++ expect(stub.headers).toEqual([+ { key: "x-shared", value: "child-value", active: true, description: "" },+ ]);+ });++ test("auth inherit + active resolves to the parent auth", () => {+ const collection = {+ ...baseCollection,+ auth: { authType: "bearer", token: "parent-token", authActive: true },+ } as HoppCollection;++ const stub = stubFor(+ { auth: { authType: "inherit", authActive: true } },+ collection+ );++ expect(stub.auth).toEqual({+ authType: "bearer",+ token: "parent-token",+ authActive: true,+ });+ });++ test("auth inherit + inactive resolves to no auth even when the parent has auth", () => {+ const collection = {+ ...baseCollection,+ auth: { authType: "bearer", token: "parent-token", authActive: true },+ } as HoppCollection;++ const stub = stubFor(+ { auth: { authType: "inherit", authActive: false } },+ collection+ );++ expect(stub.auth).toEqual({ authType: "none", authActive: false });+ });++ test("explicit request-level auth is carried onto the stub", () => {+ const stub = stubFor({+ auth: { authType: "bearer", token: "req-token", authActive: true },+ });++ expect(stub.auth).toEqual({+ authType: "bearer",+ token: "req-token",+ authActive: true,+ });+ });+});++describe("buildEffectiveGQLPayload", () => {+ test("assembles query, parsed variables, and operationName for a named operation", () => {+ const payload = payloadFor({});++ expect(payload).toEqual({+ query: "query HelloOp { hello }",+ variables: { id: "1" },+ operationName: "HelloOp",+ });+ });++ test("omits operationName for anonymous operations", () => {+ const payload = payloadFor({ query: "{ hello }" });++ expect(payload.operationName).toBeUndefined();+ });++ test("selects the first operation of a multi-operation document", () => {+ const payload = payloadFor({+ query: "query First { a }\nquery Second { b }",+ });++ expect(payload.operationName).toBe("First");+ });++ test("an anonymous FIRST operation in a multi-op document sends no operationName (server reports the spec error)", () => {+ const payload = payloadFor({+ query: "{ a }\nquery Second { b }",+ });++ expect(payload.operationName).toBeUndefined();+ });++ test("resolves env templates in bare non-string variable positions", () => {+ const payload = payloadFor(+ { variables: '{ "count": <<n>> }' },+ envs({ n: "5" })+ );++ expect(payload.variables).toEqual({ count: 5 });+ });++ test("a multi-line env value as the whole query document survives intact", () => {+ const doc = "query FromEnv {\n method\n url\n}";+ const payload = payloadFor(+ { query: "<<doc>>", variables: "" },+ envs({ doc })+ );++ expect(payload.query).toBe(doc);+ expect(payload.operationName).toBe("FromEnv");+ });++ test("safe env values substitute into variables string positions", () => {+ const payload = payloadFor(+ { variables: '{ "m": "<<v>> from CLI" }' },+ envs({ v: "hello-world" })+ );++ expect(payload.variables.m).toBe("hello-world from CLI");+ });++ test("env values that break the variables JSON fail loudly instead of sending a mangled body", () => {+ // Substitution into `variables` is textual, so a raw quote in the value+ // breaks the JSON — the app fails this identically+ const result = buildEffectiveGQLPayload(+ stubFor({ variables: '{ "m": "<<v>>" }' }),+ envs({ v: 'has a "quote"' })+ );++ expect(E.isLeft(result)).toBe(true);+ if (E.isLeft(result)) {+ expect(String(result.left.data)).toContain("Invalid JSON");+ }+ });++ test("a literal subscription fails with REQUEST_ERROR before any network call", () => {+ const result = buildEffectiveGQLPayload(+ stubFor({ query: "subscription S { countdown }" }),+ []+ );++ expect(E.isLeft(result)).toBe(true);+ if (E.isLeft(result)) {+ expect(result.left.code).toBe("REQUEST_ERROR");+ expect(String(result.left.data)).toContain(+ "GraphQL subscriptions are not supported"+ );+ }+ });++ test("a templated document resolving to a subscription is detected after substitution", () => {+ const result = buildEffectiveGQLPayload(+ stubFor({ query: "<<subdoc>>" }),+ envs({ subdoc: "subscription S { countdown }" })+ );++ expect(E.isLeft(result)).toBe(true);+ if (E.isLeft(result)) {+ expect(result.left.code).toBe("REQUEST_ERROR");+ }+ });++ test("invalid variables JSON fails with REQUEST_ERROR instead of sending a mangled body", () => {+ const result = buildEffectiveGQLPayload(+ stubFor({ variables: '{ "m": broken' }),+ []+ );++ expect(E.isLeft(result)).toBe(true);+ if (E.isLeft(result)) {+ expect(result.left.code).toBe("REQUEST_ERROR");+ expect(String(result.left.data)).toContain("Invalid JSON");+ }+ });++ test("empty variables text omits the variables key entirely", () => {+ const payload = payloadFor({ variables: "" });++ expect("variables" in payload).toBe(false);+ });++ test("whitespace-only variables fail as invalid JSON (app kernel parity)", () => {+ const result = buildEffectiveGQLPayload(stubFor({ variables: " " }), []);++ expect(E.isLeft(result)).toBe(true);+ if (E.isLeft(result)) {+ expect(String(result.left.data)).toContain("Invalid JSON");+ }+ });++ test("empty and fragment-only documents are sent as-is without operationName", () => {+ expect(payloadFor({ query: "", variables: "" })).toEqual({ query: "" });++ const fragmentOnly = "fragment F on Query { method }";+ const payload = payloadFor({ query: fragmentOnly });+ expect(payload.query).toBe(fragmentOnly);+ expect(payload.operationName).toBeUndefined();+ });++ test("an unparseable document is sent as-is for the server to report", () => {+ const payload = payloadFor({ query: "query { unbalanced" });++ expect(payload.query).toBe("query { unbalanced");+ expect(payload.operationName).toBeUndefined();+ });+});diff --git a/packages/hoppscotch-cli/src/utils/collections.ts b/packages/hoppscotch-cli/src/utils/collections.tsindex 276d1542c..66fc4fb5c 100644--- a/packages/hoppscotch-cli/src/utils/collections.ts+++ b/packages/hoppscotch-cli/src/utils/collections.ts@@ -1,4 +1,8 @@-import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data";+import {+ HoppCollection,+ HoppRESTRequest,+ isGQLRequest,+} from "@hoppscotch/data";import chalk from "chalk";import { log } from "console";import * as A from "fp-ts/Array";@@ -27,6 +31,7 @@ import {} from "./display";import { exceptionColors } from "./getters";import { getPreRequestMetrics } from "./pre-request";+import { preProcessGQLRequest } from "./gql-request";import { buildJUnitReport, generateJUnitReportExport } from "./reporters/junit";import {getRequestMetrics,@@ -125,9 +130,12 @@ const processCollection = async (collection.testScript,]);- // Process each request in the collection+ // GraphQL requests become REST-shaped stubs so the shared pipeline runs+ // them unchanged; unrunnable stubs fail at effective-request timefor (const request of collection.requests) {- const _request = preProcessRequest(request as HoppRESTRequest, collection);+ const _request = isGQLRequest(request)+ ? preProcessGQLRequest(request, collection)+ : preProcessRequest(request as HoppRESTRequest, collection);const requestPath = `${path}/${_request.name}`;const collectionVariables = collection.variables.filter(diff --git a/packages/hoppscotch-cli/src/utils/gql-request.ts b/packages/hoppscotch-cli/src/utils/gql-request.tsnew file mode 100644index 000000000..448e97cb6--- /dev/null+++ b/packages/hoppscotch-cli/src/utils/gql-request.ts@@ -0,0 +1,150 @@+import {+ EnvironmentVariable,+ HoppCollection,+ HoppGQLRequest,+ HoppRESTAuth,+ HoppRESTRequest,+ getDefaultRESTRequest,+ parseTemplateString,+} from "@hoppscotch/data";+import * as E from "fp-ts/Either";+import { parse } from "graphql";+import type { OperationDefinitionNode } from "graphql";++import { HoppCLIError, error } from "../types/errors";++/**+ * A GraphQL request converted to a REST-shaped POST so the CLI's existing+ * pipeline (templating, auth, scripts, metrics, reporting) runs it unchanged.+ *+ * `gqlRaw` carries the untemplated query/variables; the wire payload is+ * assembled by {@link buildEffectiveGQLPayload} AFTER env templating —+ * assembling earlier would JSON-escape the text before substitution and+ * corrupt the payload on env values containing quotes or newlines.+ */+export interface GQLStubRequest extends HoppRESTRequest {+ gqlRaw: { query: string; variables: string };+}++export const isGQLStubRequest = (+ request: HoppRESTRequest+): request is GQLStubRequest => "gqlRaw" in request;++/**+ * Converts a GraphQL request into a {@link GQLStubRequest}. Header/auth+ * merging matches the app runner: inactive headers are dropped BEFORE the+ * merge (so they can't suppress an active parent header), and `inherit`+ * auth falls back to the parent only when active.+ */+export const preProcessGQLRequest = (+ request: HoppGQLRequest,+ collection: HoppCollection+): GQLStubRequest => {+ const requestHeaders = (request.headers ?? []).filter(+ (header) => header.active && header.key !== ""+ );+ const parentHeaders = (collection.headers ?? []).filter(+ (header) => header.active && header.key !== ""+ );+ const headers = [+ ...parentHeaders.filter(+ (parentHeader) =>+ !requestHeaders.some((header) => header.key === parentHeader.key)+ ),+ ...requestHeaders,+ ];++ // GQL auth is a structural subset of REST auth; inherited collection auth+ // can be a REST-only type (digest, HAWK, JWT…)+ const requestAuth = (request.auth ?? {+ authType: "none",+ authActive: false,+ }) as HoppRESTAuth;+ const auth: HoppRESTAuth =+ requestAuth.authType === "inherit"+ ? requestAuth.authActive && collection.auth+ ? (collection.auth as HoppRESTAuth)+ : { authType: "none", authActive: false }+ : requestAuth;++ return {+ ...getDefaultRESTRequest(),+ name: request.name || "Untitled Request",+ method: "POST",+ endpoint: request.url ?? "",+ params: [],+ headers,+ auth,+ preRequestScript: request.preRequestScript ?? "",+ testScript: request.testScript ?? "",+ // Placeholder — replaced from `gqlRaw` at effective-request time+ body: { contentType: "application/json", body: "" },+ requestVariables: [],+ gqlRaw: {+ query: request.query ?? "",+ variables: request.variables ?? "",+ },+ };+};++/**+ * Assembles the GraphQL-over-HTTP JSON payload with env templating applied,+ * mirroring the app's collection runner: the FIRST operation of the+ * ENV-RESOLVED document runs (templated documents only reveal their+ * operations after substitution), subscriptions and invalid variables JSON+ * fail the row before any network call, and unparseable documents are sent+ * as-is for the server to report.+ */+export const buildEffectiveGQLPayload = (+ request: GQLStubRequest,+ envVariables: EnvironmentVariable[]+): E.Either<HoppCLIError, string> => {+ const query = parseTemplateString(request.gqlRaw.query, envVariables);+ // No trim — the app kernel JSON.parses non-empty text as-is, so+ // whitespace-only variables fail identically in both runners+ const variablesText = parseTemplateString(+ request.gqlRaw.variables,+ envVariables+ );++ let operation: OperationDefinitionNode | null = null;+ try {+ const operations = parse(query).definitions.filter(+ (definition): definition is OperationDefinitionNode =>+ definition.kind === "OperationDefinition"+ );+ operation = operations[0] ?? null;+ } catch (_e) {+ // Unparseable document — the server's GraphQL error beats a client-side+ // parse message+ }++ if (operation?.operation === "subscription") {+ return E.left(+ error({+ code: "REQUEST_ERROR",+ data: `GraphQL subscriptions are not supported in the CLI runner: ${request.name}`,+ })+ );+ }++ let variables: unknown = undefined;+ if (variablesText) {+ try {+ variables = JSON.parse(variablesText);+ } catch (_e) {+ return E.left(+ error({+ code: "REQUEST_ERROR",+ data: `Invalid JSON in GraphQL variables: ${request.name}`,+ })+ );+ }+ }++ const payload: Record<string, unknown> = { query };+ if (variables !== undefined) payload.variables = variables;+ if (operation?.name?.value) payload.operationName = operation.name.value;++ return E.right(JSON.stringify(payload));+};diff --git a/packages/hoppscotch-cli/src/utils/mutators.ts b/packages/hoppscotch-cli/src/utils/mutators.tsindex 153e66b24..f997ffe9b 100644--- a/packages/hoppscotch-cli/src/utils/mutators.ts+++ b/packages/hoppscotch-cli/src/utils/mutators.ts@@ -1,4 +1,9 @@-import { Environment, HoppCollection, HoppRESTRequest } from "@hoppscotch/data";+import {+ Environment,+ HoppCollection,+ HoppGQLRequest,+ HoppRESTRequest,+} from "@hoppscotch/data";import fs from "fs/promises";import { entityReference } from "verzod";import { z } from "zod";@@ -14,9 +19,17 @@ const getValidRequests = (collectionFilePath: string) => {return collections.map((collection) => {- // Validate requests using zod schema+ // Unified collections can mix REST and GraphQL requests — validate each+ // entry against its own schema (REST first; a GraphQL request lacks+ // `endpoint`, so it can never mis-validate as REST). Order is preserved:+ // runs execute requests in collection order regardless of protocol.const requestSchemaParsedResult = z- .array(entityReference(HoppRESTRequest))+ .array(+ z.union([+ entityReference(HoppRESTRequest),+ entityReference(HoppGQLRequest),+ ])+ ).safeParse(collection.requests);// Handle validation errorsdiff --git a/packages/hoppscotch-cli/src/utils/pre-request.ts b/packages/hoppscotch-cli/src/utils/pre-request.tsindex 83979862e..5ed419ee6 100644--- a/packages/hoppscotch-cli/src/utils/pre-request.ts+++ b/packages/hoppscotch-cli/src/utils/pre-request.ts@@ -34,6 +34,7 @@ import {import { isHoppCLIError } from "./checks";import { arrayFlatMap, arraySort, tupleToRecord } from "./functions/array";import { getEffectiveFinalMetaData, getResolvedVariables } from "./getters";+import { buildEffectiveGQLPayload, isGQLStubRequest } from "./gql-request";import { stripComments } from "./jsonc";import { toFormData } from "./mutators";import { combineScriptsWithIIFE, filterValidScripts } from "@hoppscotch/js-sandbox/scripting";@@ -179,14 +180,15 @@ export async function getEffectiveRESTRequest(}const effectiveFinalParams = _effectiveFinalParams.right;- // Parsing final-body with applied ENVs.- const _effectiveFinalBody = getFinalBodyFromRequest(- request,- resolvedVariables- );+ // Parsing final-body with applied ENVs. GraphQL stubs assemble their+ // payload from the raw query/variables AFTER templating — see gql-request.ts+ const _effectiveFinalBody = isGQLStubRequest(request)+ ? buildEffectiveGQLPayload(request, resolvedVariables)+ : getFinalBodyFromRequest(request, resolvedVariables);if (E.isLeft(_effectiveFinalBody)) {return _effectiveFinalBody;}+ const effectiveFinalBody = _effectiveFinalBody.right;// Authenticationif (request.auth.authActive) {@@ -259,11 +261,10 @@ export async function getEffectiveRESTRequest(const amzDate = currentDate.toISOString().replace(/[:-]|\.\d{3}/g, "");const { method, endpoint } = request;- const body = getFinalBodyFromRequest(request, resolvedVariables);-const signer = new AwsV4Signer({method,- body: E.isRight(body) ? body.right?.toString() : undefined,+ // Must be the body actually sent, else the signature mismatches+ body: effectiveFinalBody?.toString(),datetime: amzDate,signQuery: addTo === "QUERY_PARAMS",accessKeyId: parseTemplateString(@@ -337,7 +338,8 @@ export async function getEffectiveRESTRequest(opaque: request.auth.opaque? parseTemplateString(request.auth.opaque, resolvedVariables): authInfo.opaque,- reqBody: typeof request.body.body === "string" ? request.body.body : "",+ reqBody:+ typeof effectiveFinalBody === "string" ? effectiveFinalBody : "",};// Step 3: Generate the Authorization header@@ -434,8 +436,6 @@ export async function getEffectiveRESTRequest(}}- const effectiveFinalBody = _effectiveFinalBody.right;-if (request.body.contentType &&!effectiveFinalHeaders.some(diff --git a/packages/hoppscotch-cli/src/utils/request.ts b/packages/hoppscotch-cli/src/utils/request.tsindex 3c42dd385..0548ef21f 100644--- a/packages/hoppscotch-cli/src/utils/request.ts+++ b/packages/hoppscotch-cli/src/utils/request.ts@@ -290,6 +290,13 @@ export const processRequest =// Ensure, the CLI fails with a non-zero exit code if there are any errorsreport.result = false;++ // REQUEST_ERROR here means the request could not be constructed+ // (GraphQL subscription / invalid variables) — nothing to send+ if (preRequestRes.left.code === "REQUEST_ERROR") {+ result.report = report;+ return result;+ }} else {// Updating effective-request and consuming updated envs after pre-request script execution({ effectiveRequest, updatedEnvs } = preRequestRes.right);diff --git a/packages/hoppscotch-cli/src/utils/workspace-access.ts b/packages/hoppscotch-cli/src/utils/workspace-access.tsindex 2c9a947fd..2ad5c305d 100644--- a/packages/hoppscotch-cli/src/utils/workspace-access.ts+++ b/packages/hoppscotch-cli/src/utils/workspace-access.ts@@ -6,6 +6,7 @@ import {HoppCollectionVariable,HoppRESTAuth,HoppRESTHeaders,+ HoppGQLRequest,HoppRESTRequest,} from "@hoppscotch/data";@@ -39,12 +40,17 @@ interface WorkspaceRequest {* Transforms the incoming list of workspace requests by applying `JSON.parse` to the `request` field.* It includes the `v` field indicating the schema version, but migration is handled already at the `parseCollectionData()` helper function.*+ * Unified team collections can mix REST and GraphQL requests — both are+ * returned (in order) and validated per-schema downstream in+ * `getValidRequests`; the runner routes each by shape at execution time.+ ** @param {WorkspaceRequest[]} requests - An array of workspace request objects to be transformed.- * @returns {HoppRESTRequest[]} The transformed array of requests conforming to the `HoppRESTRequest` type.+ * @returns The transformed array of REST/GraphQL requests.*/const transformWorkspaceRequests = (requests: WorkspaceRequest[]-): HoppRESTRequest[] => requests.map(({ request }) => JSON.parse(request));+): (HoppRESTRequest | HoppGQLRequest)[] =>+ requests.map(({ request }) => JSON.parse(request));/*** Apply relevant migrations for data conforming to older formatsdiff --git a/packages/hoppscotch-common/locales/en.json b/packages/hoppscotch-common/locales/en.jsonindex 4dd9e2988..c6673e9fe 100644--- a/packages/hoppscotch-common/locales/en.json+++ b/packages/hoppscotch-common/locales/en.json@@ -475,6 +475,7 @@"title": "Body"},"copied_to_clipboard": "Copied to clipboard!",+ "copy_to_clipboard": "Copy to clipboard","curl": {"click_to_load": "Click to load cURL command","copied": "cURL command copied to clipboard!",@@ -503,6 +504,7 @@"no_documentation_found": "No documentation found for folders or requests","no_request_data": "No request data available","no_requests_or_folders": "No requests or folders",+ "no_write_access": "You don't have write access to this documentation","not_set": "Not set","open_request_in_new_tab": "Open request in new tab","parameters": {@@ -518,6 +520,7 @@"button": "Publish","copy_url": "Copy URL","delete": "Delete Documentation",+ "delete_error": "Failed to delete the published documentation","unpublish_doc": "Are you sure you want to unpublish the documentation?","delete_success": "Published documentation deleted successfully","doc_title": "Title",@@ -587,6 +590,9 @@"untitled_collection": "Untitled Collection","untitled_request": "Untitled Request","value": "Value",+ "query": {+ "title": "Query"+ },"variables": {"no_vars": "No variables defined","title": "Variables"@@ -825,19 +831,25 @@"arguments": "Arguments","connection_switch_confirm": "Do you want to connect with the latest GraphQL endpoint?","connection_error_http": "Failed to fetch GraphQL Schema due to network error.",- "connection_switch_new_url": "Switching to a tab will disconnected you from the active GraphQL connection. New connection URL is",+ "connection_error_introspection_disabled": "Introspection is disabled on this server.",+ "connection_error_invalid_json": "Introspection response was not valid JSON — the endpoint may not be a GraphQL server.",+ "connection_switch_new_url": "Switching to this tab will disconnect you from the active GraphQL connection. The new connection URL is","connection_switch_url": "You're connected to a GraphQL endpoint the connection URL is","deprecated": "Deprecated","fields": "Fields","mutation": "Mutation","mutations": "Mutations",+ "operation_error": "Something went wrong while running the operation","schema": "Schema","show_depricated_values": "Show deprecated values","subscription": "Subscription",+ "subscription_log": "Subscription Log","subscriptions": "Subscriptions",+ "subscribing": "Connecting to subscription endpoint…","switch_connection": "Switch connection","url_placeholder": "Enter a GraphQL endpoint URL",- "query": "Query"+ "query": "Query",+ "waiting_for_events": "Subscribed. Waiting for events…"},"graphql_collections": {"title": "GraphQL Collections"@@ -1200,6 +1212,7 @@"show_content_type": "Show Content Type","different_collection": "Cannot reorder requests from different collections","duplicated": "Request duplicated",+ "rest_in_gql_collection": "This is a REST request — open it from the REST workspace","duration": "Duration","enter_curl": "Enter cURL command","generate_code": "Generate code",@@ -1212,6 +1225,7 @@"moved": "Request moved","name": "Request name","new": "New Request",+ "new_gql": "New GraphQL Request","order_changed": "Request Order Updated","override": "Override","override_help": "Set <kbd>Content-Type</kbd> in Headers",@@ -1234,7 +1248,9 @@"share_description": "Share Hoppscotch with your friends","share_request": "Share Request","stop": "Stop",+ "switch_protocol": "Switch protocol","title": "Request",+ "try": "Try","type": "Request type","url": "URL","url_placeholder": "Enter a URL or paste a cURL command",@@ -1269,6 +1285,7 @@"generate_data_schema": "Generate Data Schema","data_schema": "Data Schema","saved": "Response saved",+ "save_as_example": "Save as example","invalid_name": "Please provide a name for the response"},"script": {@@ -1376,6 +1393,7 @@"experimental_scripting_sandbox": "Experimental scripting sandbox","enable_experimental_mock_servers": "Enable Mock Servers","enable_experimental_documentation": "Enable Documentation",+ "enable_gql_in_rest_workspace": "Enable Unified GraphQL workspace","sync": "Synchronise","sync_collections": "Collections","sync_description": "These settings are synced to cloud.",@@ -1429,6 +1447,7 @@"proxy_auth": "You can also include username and password in the URL."},"shared_requests": {+ "auth_warning": "This request contains authentication credentials. Anyone with the share link will be able to read them — including tokens, passwords, and API keys.","button": "Button","button_info": "Create a 'Run in Hoppscotch' button for your website, blog or a README.","copy_html": "Copy HTML",@@ -1941,6 +1960,7 @@"snippets": "Snippets","run": "Run","run_again": "Run again",+ "running": "Running tests...","stop": "Stop","new_run": "New Run","iterations": "Iterations",diff --git a/packages/hoppscotch-common/src/components.d.ts b/packages/hoppscotch-common/src/components.d.tsindex 05bb83ac4..1211528f2 100644--- a/packages/hoppscotch-common/src/components.d.ts+++ b/packages/hoppscotch-common/src/components.d.ts@@ -68,8 +68,10 @@ declare module 'vue' {CollectionsDocumentationRequestPreview: typeof import('./components/collections/documentation/RequestPreview.vue')['default']CollectionsDocumentationSectionsAuth: typeof import('./components/collections/documentation/sections/Auth.vue')['default']CollectionsDocumentationSectionsCurlView: typeof import('./components/collections/documentation/sections/CurlView.vue')['default']+ CollectionsDocumentationSectionsGqlVariables: typeof import('./components/collections/documentation/sections/GqlVariables.vue')['default']CollectionsDocumentationSectionsHeaders: typeof import('./components/collections/documentation/sections/Headers.vue')['default']CollectionsDocumentationSectionsParameters: typeof import('./components/collections/documentation/sections/Parameters.vue')['default']+ CollectionsDocumentationSectionsQuery: typeof import('./components/collections/documentation/sections/Query.vue')['default']CollectionsDocumentationSectionsRequestBody: typeof import('./components/collections/documentation/sections/RequestBody.vue')['default']CollectionsDocumentationSectionsResponse: typeof import('./components/collections/documentation/sections/Response.vue')['default']CollectionsDocumentationSectionsVariables: typeof import('./components/collections/documentation/sections/Variables.vue')['default']@@ -108,6 +110,8 @@ declare module 'vue' {DocumentationHeader: typeof import('./components/documentation/Header.vue')['default']DocumentationSkeleton: typeof import('./components/documentation/Skeleton.vue')['default']Embeds: typeof import('./components/embeds/index.vue')['default']+ EmbedsGQLIndex: typeof import('./components/embeds/GQLIndex.vue')['default']+ EmbedsGQLRequest: typeof import('./components/embeds/GQLRequest.vue')['default']EmbedsHeader: typeof import('./components/embeds/Header.vue')['default']EmbedsRequest: typeof import('./components/embeds/Request.vue')['default']Environments: typeof import('./components/environments/index.vue')['default']@@ -123,6 +127,37 @@ declare module 'vue' {EnvironmentsTeamsEnvironment: typeof import('./components/environments/teams/Environment.vue')['default']FirebaseLogin: typeof import('./components/firebase/Login.vue')['default']FirebaseLogout: typeof import('./components/firebase/Logout.vue')['default']+ GqlArgument: typeof import('./components/gql/Argument.vue')['default']+ GqlArguments: typeof import('./components/gql/Arguments.vue')['default']+ GqlAuthorization: typeof import('./components/gql/Authorization.vue')['default']+ GqlDefaultValue: typeof import('./components/gql/DefaultValue.vue')['default']+ GqlDirectives: typeof import('./components/gql/Directives.vue')['default']+ GqlDocExplorer: typeof import('./components/gql/DocExplorer.vue')['default']+ GqlEnumValues: typeof import('./components/gql/EnumValues.vue')['default']+ GqlExampleResponse: typeof import('./components/gql/example/Response.vue')['default']+ GqlExampleResponseRequest: typeof import('./components/gql/example/ResponseRequest.vue')['default']+ GqlExampleResponseTab: typeof import('./components/gql/example/ResponseTab.vue')['default']+ GqlExplorerSection: typeof import('./components/gql/ExplorerSection.vue')['default']+ GqlField: typeof import('./components/gql/Field.vue')['default']+ GqlFieldDocumentation: typeof import('./components/gql/FieldDocumentation.vue')['default']+ GqlFieldLink: typeof import('./components/gql/FieldLink.vue')['default']+ GqlFields: typeof import('./components/gql/Fields.vue')['default']+ GqlHeaders: typeof import('./components/gql/Headers.vue')['default']+ GqlImplementsInterfaces: typeof import('./components/gql/ImplementsInterfaces.vue')['default']+ GqlQuery: typeof import('./components/gql/Query.vue')['default']+ GqlRequest: typeof import('./components/gql/Request.vue')['default']+ GqlRequestOptions: typeof import('./components/gql/RequestOptions.vue')['default']+ GqlRequestTab: typeof import('./components/gql/RequestTab.vue')['default']+ GqlResponse: typeof import('./components/gql/Response.vue')['default']+ GqlResponseMeta: typeof import('./components/gql/ResponseMeta.vue')['default']+ GqlSchema: typeof import('./components/gql/Schema.vue')['default']+ GqlSchemaDocumentation: typeof import('./components/gql/SchemaDocumentation.vue')['default']+ GqlSchemaSearch: typeof import('./components/gql/SchemaSearch.vue')['default']+ GqlSubscriptionLog: typeof import('./components/gql/SubscriptionLog.vue')['default']+ GqlTabHead: typeof import('./components/gql/TabHead.vue')['default']+ GqlTypeDocumentation: typeof import('./components/gql/TypeDocumentation.vue')['default']+ GqlTypeLink: typeof import('./components/gql/TypeLink.vue')['default']+ GqlVariable: typeof import('./components/gql/Variable.vue')['default']GraphqlArgument: typeof import('./components/graphql/Argument.vue')['default']GraphqlArguments: typeof import('./components/graphql/Arguments.vue')['default']GraphqlAuthorization: typeof import('./components/graphql/Authorization.vue')['default']@@ -154,6 +189,7 @@ declare module 'vue' {GraphqlVariable: typeof import('./components/graphql/Variable.vue')['default']History: typeof import('./components/history/index.vue')['default']HistoryGraphqlCard: typeof import('./components/history/graphql/Card.vue')['default']+ HistoryGraphqlMergedCard: typeof import('./components/history/graphql/MergedCard.vue')['default']HistoryPersonal: typeof import('./components/history/Personal.vue')['default']HistoryRestCard: typeof import('./components/history/rest/Card.vue')['default']HoppButtonPrimary: typeof import('@hoppscotch/ui')['HoppButtonPrimary']@@ -208,6 +244,7 @@ declare module 'vue' {HttpKeyValue: typeof import('./components/http/KeyValue.vue')['default']HttpParameters: typeof import('./components/http/Parameters.vue')['default']HttpPreRequestScript: typeof import('./components/http/PreRequestScript.vue')['default']+ HttpProtocolSwitcher: typeof import('./components/http/ProtocolSwitcher.vue')['default']HttpRawBody: typeof import('./components/http/RawBody.vue')['default']HttpReqChangeConfirmModal: typeof import('./components/http/ReqChangeConfirmModal.vue')['default']HttpRequest: typeof import('./components/http/Request.vue')['default']@@ -243,6 +280,7 @@ declare module 'vue' {IconLucideAlertTriangle: typeof import('~icons/lucide/alert-triangle')['default']IconLucideArrowLeft: typeof import('~icons/lucide/arrow-left')['default']IconLucideArrowUpRight: typeof import('~icons/lucide/arrow-up-right')['default']+ IconLucideBox: typeof import('~icons/lucide/box')['default']IconLucideBrush: typeof import('~icons/lucide/brush')['default']IconLucideCheck: typeof import('~icons/lucide/check')['default']IconLucideCheckCircle: typeof import('~icons/lucide/check-circle')['default']@@ -317,11 +355,13 @@ declare module 'vue' {SettingsProxy: typeof import('./components/settings/Proxy.vue')['default']Share: typeof import('./components/share/index.vue')['default']ShareCreateModal: typeof import('./components/share/CreateModal.vue')['default']+ ShareCustomizeGQLModal: typeof import('./components/share/CustomizeGQLModal.vue')['default']ShareCustomizeModal: typeof import('./components/share/CustomizeModal.vue')['default']ShareModal: typeof import('./components/share/Modal.vue')['default']ShareRequest: typeof import('./components/share/Request.vue')['default']ShareTemplatesButton: typeof import('./components/share/templates/Button.vue')['default']ShareTemplatesEmbeds: typeof import('./components/share/templates/Embeds.vue')['default']+ ShareTemplatesEmbedsGQL: typeof import('./components/share/templates/EmbedsGQL.vue')['default']ShareTemplatesLink: typeof import('./components/share/templates/Link.vue')['default']SmartAccentModePicker: typeof import('./components/smart/AccentModePicker.vue')['default']SmartChangeLanguage: typeof import('./components/smart/ChangeLanguage.vue')['default']diff --git a/packages/hoppscotch-common/src/components/app/Inspection.vue b/packages/hoppscotch-common/src/components/app/Inspection.vueindex fa628bf5d..c0a12ada6 100644--- a/packages/hoppscotch-common/src/components/app/Inspection.vue+++ b/packages/hoppscotch-common/src/components/app/Inspection.vue@@ -52,7 +52,7 @@</HoppSmartLink></span><span- v-if="inspector.action ? inspector.action.showAction : true"+ v-if="inspector.action ? inspector.action.showAction : false"class="flex space-x-2 p-2"><HoppButtonSecondarydiff --git a/packages/hoppscotch-common/src/components/app/ShortcutsPrompt.vue b/packages/hoppscotch-common/src/components/app/ShortcutsPrompt.vueindex b6eb3cd6d..9c6db28a1 100644--- a/packages/hoppscotch-common/src/components/app/ShortcutsPrompt.vue+++ b/packages/hoppscotch-common/src/components/app/ShortcutsPrompt.vue@@ -35,7 +35,7 @@</div><HoppButtonSecondary:label="`${t('app.documentation')}`"- to="https://docs.hoppscotch.io/documentation/features/rest-api-testing#response"+ :to="documentationUrl":icon="IconExternalLink"blankoutline@@ -49,5 +49,15 @@ import { useI18n } from "~/composables/i18n"import IconExternalLink from "~icons/lucide/external-link"import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"+withDefaults(+ defineProps<{+ documentationUrl?: string+ }>(),+ {+ documentationUrl:+ "https://docs.hoppscotch.io/documentation/features/rest-api-testing#response",+ }+)+const t = useI18n()</script>diff --git a/packages/hoppscotch-common/src/components/app/spotlight/entry/RESTRequest.vue b/packages/hoppscotch-common/src/components/app/spotlight/entry/RESTRequest.vueindex 95f2510e8..3d8c69ccc 100644--- a/packages/hoppscotch-common/src/components/app/spotlight/entry/RESTRequest.vue+++ b/packages/hoppscotch-common/src/components/app/spotlight/entry/RESTRequest.vue@@ -13,6 +13,12 @@>{{ request.method.toUpperCase() }}</span>+ <span+ v-else-if="request && isGQLRequest(request)"+ class="flex flex-shrink-0 items-center rounded-md border border-dividerDark px-1"+ >+ <IconGraphql class="svg-icons h-3.5 w-3.5 text-accent" />+ </span><span v-if="request" class="block">{{ request.name }}</span>@@ -22,8 +28,10 @@<script setup lang="ts">import { HoppCollection } from "@hoppscotch/data"import { computed } from "vue"+import IconGraphql from "~icons/hopp/graphql"import { restCollectionStore } from "~/newstore/collections"import { getMethodLabelColorClassOf } from "~/helpers/rest/labelColoring"+import { isGQLRequest } from "~/helpers/request-type"const props = defineProps<{folderPath: stringdiff --git a/packages/hoppscotch-common/src/components/collections/AddRequest.vue b/packages/hoppscotch-common/src/components/collections/AddRequest.vueindex 381e76968..a4815a16b 100644--- a/packages/hoppscotch-common/src/components/collections/AddRequest.vue+++ b/packages/hoppscotch-common/src/components/collections/AddRequest.vue@@ -2,7 +2,7 @@<HoppSmartModalv-if="show"dialog- :title="t('request.new')"+ :title="t(requestType === 'gql' ? 'request.new_gql' : 'request.new')"@close="hideModal"><template #body>@@ -50,10 +50,12 @@ const props = withDefaults(defineProps<{show?: booleanloadingState?: boolean+ requestType?: "rest" | "gql"}>(),{show: false,loadingState: false,+ requestType: "rest",})diff --git a/packages/hoppscotch-common/src/components/collections/Collection.vue b/packages/hoppscotch-common/src/components/collections/Collection.vueindex 08c345d69..d6179b201 100644--- a/packages/hoppscotch-common/src/components/collections/Collection.vue+++ b/packages/hoppscotch-common/src/components/collections/Collection.vue@@ -137,6 +137,7 @@class="flex flex-col focus:outline-none"tabindex="0"@keyup.r="requestAction?.$el.click()"+ @keyup.g="gqlRequestAction?.$el.click()"@keyup.n="folderAction?.$el.click()"@keyup.e="edit?.$el.click()"@keyup.d="duplicateAction?.$el.click()"@@ -164,6 +165,19 @@}"/>+ <HoppSmartItem+ v-if="!hasNoTeamAccess && isGqlWorkspaceEnabled"+ ref="gqlRequestAction"+ :icon="IconGraphql"+ :label="t('request.new_gql')"+ :shortcut="['G']"+ @click="+ () => {+ emit('add-gql-request')+ hide()+ }+ "+ /><HoppSmartItemv-if="!hasNoTeamAccess"ref="folderAction"@@ -326,6 +340,7 @@<script setup lang="ts">import { useI18n } from "@composables/i18n"import { useDocumentationVisibility } from "~/composables/documentationVisibility"+import { useGqlWorkspaceVisibility } from "~/composables/gqlWorkspaceVisibility"import { HoppCollection } from "@hoppscotch/data"import { computed, ref, watch } from "vue"import { TippyComponent } from "vue-tippy"@@ -350,6 +365,7 @@ import IconSettings2 from "~icons/lucide/settings-2"import IconTrash2 from "~icons/lucide/trash-2"import IconArrowUpDown from "~icons/lucide/arrow-up-down"import IconBook from "~icons/lucide/book"+import IconGraphql from "~icons/hopp/graphql"import { CurrentSortValuesService } from "~/services/current-sort.service"import { useService } from "dioc/vue"import { useMockServerStatus } from "~/composables/mockServer"@@ -403,6 +419,7 @@ const props = withDefaults(const emit = defineEmits<{(event: "toggle-children"): void(event: "add-request"): void+ (event: "add-gql-request"): void(event: "add-folder"): void(event: "run-collection"): void(event: "edit-collection"): void@@ -430,6 +447,7 @@ const emit = defineEmits<{const tippyActions = ref<HTMLDivElement | null>(null)const requestAction = ref<HTMLButtonElement | null>(null)+const gqlRequestAction = ref<HTMLButtonElement | null>(null)const folderAction = ref<HTMLButtonElement | null>(null)const edit = ref<HTMLButtonElement | null>(null)const duplicateAction = ref<HTMLButtonElement | null>(null)@@ -443,6 +461,7 @@ const sortAction = ref<HTMLButtonElement | null>(null)const documentationAction = ref<HTMLButtonElement | null>(null)const { isDocumentationVisible } = useDocumentationVisibility()+const { isGqlWorkspaceEnabled } = useGqlWorkspaceVisibility()const dragging = ref(false)const ordering = ref(false)diff --git a/packages/hoppscotch-common/src/components/collections/EditRequest.vue b/packages/hoppscotch-common/src/components/collections/EditRequest.vueindex ed45e7add..a46c48e74 100644--- a/packages/hoppscotch-common/src/components/collections/EditRequest.vue+++ b/packages/hoppscotch-common/src/components/collections/EditRequest.vue@@ -97,7 +97,7 @@<script setup lang="ts">import { useI18n } from "@composables/i18n"import { useToast } from "@composables/toast"-import { HoppRESTRequest } from "@hoppscotch/data"+import { HoppRESTRequest, HoppGQLRequest } from "@hoppscotch/data"import { useVModel } from "@vueuse/core"import { ref, watch } from "vue"import {@@ -116,7 +116,7 @@ const props = withDefaults(show: booleanloadingState?: booleanmodelValue?: string- requestContext: HoppRESTRequest | null+ requestContext: HoppRESTRequest | HoppGQLRequest | null}>(),{show: false,diff --git a/packages/hoppscotch-common/src/components/collections/ExampleResponse.vue b/packages/hoppscotch-common/src/components/collections/ExampleResponse.vueindex d14952a42..e09d5ba4e 100644--- a/packages/hoppscotch-common/src/components/collections/ExampleResponse.vue+++ b/packages/hoppscotch-common/src/components/collections/ExampleResponse.vue@@ -128,9 +128,12 @@ import { ref, PropType, computed } from "vue"import { useI18n } from "@composables/i18n"import { TippyComponent } from "vue-tippy"import { useService } from "dioc/vue"-import { RESTTabService } from "~/services/tab/rest"-import { HoppRESTRequestResponse } from "@hoppscotch/data"-import { HoppRESTSaveContext } from "~/helpers/rest/document"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"+import {+ HoppGQLRequestResponse,+ HoppRESTRequestResponse,+} from "@hoppscotch/data"+import { HoppTabSaveContext } from "~/helpers/tab/document"import findStatusGroup from "@helpers/findStatusGroup"const t = useI18n()@@ -147,7 +150,7 @@ type SaveContext = {const props = defineProps({response: {- type: Object as PropType<HoppRESTRequestResponse>,+ type: Object as PropType<HoppRESTRequestResponse | HoppGQLRequestResponse>,default: null,required: true,},@@ -184,14 +187,14 @@ const emit = defineEmits<{(event: "select-response", payload: ResponsePayload): void}>()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const pathToIndex = (path: string) => {const pathArr = path.split("/")return pathArr[pathArr.length - 1]}-const getSaveContext = (): HoppRESTSaveContext => {+const getSaveContext = (): HoppTabSaveContext => {if (props.saveContext.collectionsType === "my-collections") {return {originLocation: "user-collection",diff --git a/packages/hoppscotch-common/src/components/collections/MyCollections.vue b/packages/hoppscotch-common/src/components/collections/MyCollections.vueindex dbcd055d3..bce6490d4 100644--- a/packages/hoppscotch-common/src/components/collections/MyCollections.vue+++ b/packages/hoppscotch-common/src/components/collections/MyCollections.vue@@ -65,6 +65,13 @@folder: node.data.data.data,})"+ @add-gql-request="+ node.data.type === 'collections' &&+ emit('add-gql-request', {+ path: node.id,+ folder: node.data.data.data,+ })+ "@add-folder="node.data.type === 'collections' &&emit('add-folder', {@@ -176,6 +183,13 @@folder: node.data.data.data,})"+ @add-gql-request="+ node.data.type === 'folders' &&+ emit('add-gql-request', {+ path: node.id,+ folder: node.data.data.data,+ })+ "@add-folder="node.data.type === 'folders' &&emit('add-folder', {@@ -262,7 +276,7 @@:is-active="isActiveRequest(node.data.data.parentIndex,- node.data.data.data._ref_id ?? node.data.data.data.id+ node.data.data.data._ref_id ?? node.data.data.data.id ?? '')":is-selected="@@ -365,7 +379,7 @@folderPath: node.data.data.parentIndex,requestIndex: node.id,requestRefID:- node.data.data.data._ref_id ?? node.data.data.data.id,+ node.data.data.data._ref_id ?? node.data.data.data.id ?? '',})"@update-request-order="@@ -459,7 +473,11 @@ import IconPlus from "~icons/lucide/plus"import IconHelpCircle from "~icons/lucide/help-circle"import IconImport from "~icons/lucide/folder-down"import IconArrowUpDown from "~icons/lucide/arrow-up-down"-import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data"+import {+ HoppCollection,+ HoppRESTRequest,+ HoppGQLRequest,+} from "@hoppscotch/data"import { computed, PropType, ref, Ref, toRef } from "vue"import { GetMyTeamsQuery } from "~/helpers/backend/graphql"import { ChildrenResult, SmartTreeAdapter } from "@hoppscotch/ui/helpers"@@ -469,7 +487,7 @@ import { pipe } from "fp-ts/function"import * as O from "fp-ts/Option"import { Picked } from "~/helpers/types/HoppPicked.js"import { useService } from "dioc/vue"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { useDebounceFn } from "@vueuse/core"import { CurrentSortValuesService } from "~/services/current-sort.service"@@ -496,7 +514,7 @@ type Requests = {isLastItem: booleandata: {parentIndex: string- data: HoppRESTRequest+ data: HoppRESTRequest | HoppGQLRequest}}@@ -543,7 +561,7 @@ const props = defineProps({type ResponsePayload = {folderPath: stringrequestIndex: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequestresponseName: stringresponseID: string}@@ -557,6 +575,13 @@ const emit = defineEmits<{folder: HoppCollection}): void+ (+ event: "add-gql-request",+ payload: {+ path: string+ folder: HoppCollection+ }+ ): void(event: "add-folder",payload: {@@ -606,7 +631,7 @@ const emit = defineEmits<{folderPath: stringrequestIndex: stringrequestRefID: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequest}): void(@@ -621,7 +646,7 @@ const emit = defineEmits<{payload: {folderPath: stringrequestIndex: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequest}): void(event: "edit-response", payload: ResponsePayload): void@@ -629,7 +654,7 @@ const emit = defineEmits<{event: "duplicate-request",payload: {folderPath: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequest}): void(event: "duplicate-response", payload: ResponsePayload): void@@ -647,7 +672,7 @@ const emit = defineEmits<{(event: "select-request",payload: {- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequestfolderPath: stringrequestIndex: stringisActive: boolean@@ -664,14 +689,14 @@ const emit = defineEmits<{(event: "share-request",payload: {- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequest}): void(event: "add-example",payload: {folderPath: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequestrequestIndex: number}): void@@ -764,7 +789,7 @@ const isSelected = ({)}-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const active = computed(() =>tabs.currentActiveTab.value.document.type !== "test-runner" &&@@ -789,7 +814,7 @@ const isActiveRequest = (folderPath: string, requestRefID: string) => {}const selectRequest = (data: {- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequestfolderPath: stringrequestIndex: string}) => {diff --git a/packages/hoppscotch-common/src/components/collections/Request.vue b/packages/hoppscotch-common/src/components/collections/Request.vueindex 1b615dc98..327702ed5 100644--- a/packages/hoppscotch-common/src/components/collections/Request.vue+++ b/packages/hoppscotch-common/src/components/collections/Request.vue@@ -36,7 +36,11 @@><spanclass="pointer-events-none flex w-8 items-center justify-start truncate px-0.5"- :style="{ color: getMethodLabelColorClassOf(request.method) }"+ :style="{+ color: isGQL+ ? undefined+ : getMethodLabelColorClassOf((request as HoppRESTRequest).method),+ }"><component:is="IconCheckCircle"@@ -45,8 +49,13 @@:class="{ 'text-accent': isSelected }"/><HoppSmartSpinner v-else-if="isRequestLoading" />+ <component+ :is="IconGraphql"+ v-else-if="isGQL"+ class="svg-icons h-3.5 w-3.5 text-accent"+ /><span v-else class="truncate text-tiny font-semibold">- {{ request.method }}+ {{ (request as HoppRESTRequest).method }}</span></span><span@@ -211,7 +220,9 @@<div class="flex flex-col w-full pl-3"><CollectionsExampleResponsev-for="[index, [key, value]] of Object.entries(- Object.entries(request.responses)+ Object.entries(+ (request as HoppRESTRequest | HoppGQLRequest).responses+ ))":key="key":response-name="key"@@ -246,7 +257,9 @@ import IconArrowDown from "~icons/lucide/chevron-down"import IconBook from "~icons/lucide/book"import IconPlusCircle from "~icons/lucide/plus-circle"import { ref, PropType, watch, computed } from "vue"-import { HoppRESTRequest } from "@hoppscotch/data"+import { HoppRESTRequest, HoppGQLRequest } from "@hoppscotch/data"+import { isGQLRequest } from "@hoppscotch/data"+import IconGraphql from "~icons/hopp/graphql"import { useI18n } from "@composables/i18n"import { useDocumentationVisibility } from "~/composables/documentationVisibility"import { TippyComponent } from "vue-tippy"@@ -265,7 +278,7 @@ const t = useI18n()const props = defineProps({request: {- type: Object as PropType<HoppRESTRequest>,+ type: Object as PropType<HoppRESTRequest | HoppGQLRequest>,default: () => ({}),required: true,},@@ -355,6 +368,8 @@ const addExampleAction = ref<HTMLButtonElement | null>(null)const { isDocumentationVisible } = useDocumentationVisibility()+const isGQL = computed(() => isGQLRequest(props.request))+const dragging = ref(false)const ordering = ref(false)const orderingLastItem = ref(false)diff --git a/packages/hoppscotch-common/src/components/collections/SaveRequest.vue b/packages/hoppscotch-common/src/components/collections/SaveRequest.vueindex cd9f99106..2dca294c8 100644--- a/packages/hoppscotch-common/src/components/collections/SaveRequest.vue+++ b/packages/hoppscotch-common/src/components/collections/SaveRequest.vue@@ -41,7 +41,7 @@{{ t("collection.select_location") }}</label><CollectionsGraphql- v-if="mode === 'graphql'"+ v-if="mode === 'legacy-graphql'":picked="picked":save-request="true"@select="onSelect"@@ -123,7 +123,7 @@ import {HoppGQLRequest,HoppRESTRequest,generateUniqueRefId,- isHoppRESTRequest,+ isGQLRequest,} from "@hoppscotch/data"import { computedWithControl } from "@vueuse/core"import { useService } from "dioc/vue"@@ -152,7 +152,8 @@ import {} from "~/newstore/collections"import { platform } from "~/platform"import { GQLTabService } from "~/services/tab/graphql"-import { RESTTabService } from "~/services/tab/rest"+import { TeamCollectionsService } from "~/services/team-collection.service"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { TeamWorkspace } from "~/services/workspace.service"import IconSparkle from "~icons/lucide/sparkles"import IconThumbsDown from "~icons/lucide/thumbs-down"@@ -162,8 +163,9 @@ import { handleTokenValidation } from "~/helpers/handleTokenValidation"const t = useI18n()const toast = useToast()-const RESTTabs = useService(RESTTabService)+const workspaceTabs = useService(WorkspaceTabsService)const GQLTabs = useService(GQLTabService)+const teamCollectionService = useService(TeamCollectionsService)type CollectionType =| {@@ -175,12 +177,12 @@ type CollectionType =const props = withDefaults(defineProps<{show: boolean- mode: "rest" | "graphql"+ mode: "workspace" | "legacy-graphql"request?: HoppRESTRequest | HoppGQLRequest | null}>(),{show: false,- mode: "rest",+ mode: "workspace",request: null,})@@ -202,19 +204,21 @@ const gqlRequestName = computedWithControl(() => GQLTabs.currentActiveTab.value.document.request.name)-const restRequestName = computedWithControl(- () => RESTTabs.currentActiveTab.value,- () =>- RESTTabs.currentActiveTab.value.document.type === "request"- ? RESTTabs.currentActiveTab.value.document.request.name- : ""+const workspaceRequestName = computedWithControl(+ () => workspaceTabs.currentActiveTab.value,+ () => {+ const doc = workspaceTabs.currentActiveTab.value.document+ if (doc.type === "request" || doc.type === "gql-request")+ return doc.request.name+ return ""+ })const reqName = computed(() => {if (props.request) {return props.request.name- } else if (props.mode === "rest") {- return restRequestName.value+ } else if (props.mode === "workspace") {+ return workspaceRequestName.value}return gqlRequestName.value})@@ -224,11 +228,11 @@ const requestContext = computed(() => {return props.request}- if (- props.mode === "rest" &&- RESTTabs.currentActiveTab.value.document.type === "request"- ) {- return RESTTabs.currentActiveTab.value.document.request+ if (props.mode === "workspace") {+ const doc = workspaceTabs.currentActiveTab.value.document+ if (doc.type === "request" || doc.type === "gql-request") {+ return doc.request+ }}return GQLTabs.currentActiveTab.value.document.request@@ -257,14 +261,13 @@ const submittedFeedback = ref(false)const { submitFeedback, isSubmitFeedbackPending } = useSubmitFeedback()watch(- () => [RESTTabs.currentActiveTab.value, GQLTabs.currentActiveTab.value],+ () => [workspaceTabs.currentActiveTab.value, GQLTabs.currentActiveTab.value],() => {- if (- props.mode === "rest" &&- RESTTabs.currentActiveTab.value.document.type === "request"- ) {- requestName.value =- RESTTabs.currentActiveTab.value?.document.request.name ?? ""+ if (props.mode === "workspace") {+ const doc = workspaceTabs.currentActiveTab.value.document+ if (doc.type === "request" || doc.type === "gql-request") {+ requestName.value = doc.request.name ?? ""+ }} else {requestName.value =GQLTabs.currentActiveTab.value?.document.request.name ?? ""@@ -328,105 +331,141 @@ const saveRequestAs = async () => {return}- const requestUpdated =- props.mode === "rest"- ? cloneDeep(- RESTTabs.currentActiveTab.value.document.type === "request"- ? RESTTabs.currentActiveTab.value.document.request- : null- )- : cloneDeep(GQLTabs.currentActiveTab.value.document.request)+ const requestUpdated = (() => {+ if (props.mode === "workspace") {+ const doc = workspaceTabs.currentActiveTab.value.document+ if (doc.type === "request" || doc.type === "gql-request") {+ return cloneDeep(doc.request)+ }+ return null+ }+ return cloneDeep(GQLTabs.currentActiveTab.value.document.request)+ })()if (!requestUpdated) returnrequestUpdated.name = requestName.value- // A copy is a new entry and needs its own `_ref_id` — equal ref ids are- // treated as the same request, which would bind the copy's tab to the source- if (- isHoppRESTRequest(requestUpdated) &&- (picked.value.pickedType === "my-collection" ||- picked.value.pickedType === "my-folder" ||- picked.value.pickedType === "teams-collection" ||- picked.value.pickedType === "teams-folder")- ) {+ // New entries need a fresh `_ref_id` and no `id`; otherwise sync would edit the original row instead of creating a new one.+ const isNewCollectionEntry =+ picked.value.pickedType === "my-collection" ||+ picked.value.pickedType === "my-folder" ||+ picked.value.pickedType === "teams-collection" ||+ picked.value.pickedType === "teams-folder" ||+ picked.value.pickedType === "gql-my-collection" ||+ picked.value.pickedType === "gql-my-folder"++ if (isNewCollectionEntry) {+ requestUpdated._ref_id = generateUniqueRefId("req")+ delete requestUpdated.id+ } else if (!requestUpdated._ref_id) {requestUpdated._ref_id = generateUniqueRefId("req")}if (picked.value.pickedType === "my-collection") {- if (!isHoppRESTRequest(requestUpdated))- throw new Error("requestUpdated is not a REST Request")-const insertionIndex = saveRESTRequestAs(`${picked.value.collectionIndex}`,requestUpdated)- if (RESTTabs.currentActiveTab.value.document.type !== "request") return+ const folderPath = `${picked.value.collectionIndex}`++ if (isGQLRequest(requestUpdated)) {+ workspaceTabs.currentActiveTab.value.document = {+ type: "gql-request",+ request: requestUpdated as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext: {+ originLocation: "user-collection",+ folderPath,+ requestIndex: insertionIndex,+ requestRefID: requestUpdated._ref_id ?? requestUpdated.id,+ exampleID: undefined,+ },+ inheritedProperties: cascadeParentCollectionForProperties(+ folderPath,+ "rest"+ ),+ }+ } else {+ if (workspaceTabs.currentActiveTab.value.document.type !== "request")+ return++ workspaceTabs.currentActiveTab.value.document = {+ request: requestUpdated as HoppRESTRequest,+ isDirty: false,+ type: "request",+ saveContext: {+ originLocation: "user-collection",+ folderPath,+ requestIndex: insertionIndex,+ requestRefID: requestUpdated._ref_id ?? requestUpdated.id,+ exampleID: undefined,+ },+ }- RESTTabs.currentActiveTab.value.document = {- request: requestUpdated,- isDirty: false,- type: "request",- saveContext: {- originLocation: "user-collection",- folderPath: `${picked.value.collectionIndex}`,- requestIndex: insertionIndex,- exampleID: undefined,- requestRefID: requestUpdated._ref_id,- },+ workspaceTabs.currentActiveTab.value.document.inheritedProperties =+ cascadeParentCollectionForProperties(folderPath, "rest")}- RESTTabs.currentActiveTab.value.document.inheritedProperties =- cascadeParentCollectionForProperties(- `${picked.value.collectionIndex}`,- "rest"- )-platform.analytics?.logEvent({type: "HOPP_SAVE_REQUEST",createdNow: true,- platform: "rest",+ platform: isGQLRequest(requestUpdated) ? "gql" : "rest",workspaceType: "personal",})requestSaved()} else if (picked.value.pickedType === "my-folder") {- if (!isHoppRESTRequest(requestUpdated))- throw new Error("requestUpdated is not a REST Request")-const insertionIndex = saveRESTRequestAs(picked.value.folderPath,requestUpdated)- RESTTabs.currentActiveTab.value.document = {- request: requestUpdated,- isDirty: false,- type: "request",- saveContext: {- originLocation: "user-collection",- folderPath: picked.value.folderPath,- requestIndex: insertionIndex,- requestRefID: requestUpdated._ref_id,- },- }+ if (isGQLRequest(requestUpdated)) {+ workspaceTabs.currentActiveTab.value.document = {+ type: "gql-request",+ request: requestUpdated as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext: {+ originLocation: "user-collection",+ folderPath: picked.value.folderPath,+ requestIndex: insertionIndex,+ requestRefID: requestUpdated._ref_id ?? requestUpdated.id,+ },+ inheritedProperties: cascadeParentCollectionForProperties(+ picked.value.folderPath,+ "rest"+ ),+ }+ } else {+ workspaceTabs.currentActiveTab.value.document = {+ request: requestUpdated as HoppRESTRequest,+ isDirty: false,+ type: "request",+ saveContext: {+ originLocation: "user-collection",+ folderPath: picked.value.folderPath,+ requestIndex: insertionIndex,+ requestRefID: requestUpdated._ref_id ?? requestUpdated.id,+ },+ }- RESTTabs.currentActiveTab.value.document.inheritedProperties =- cascadeParentCollectionForProperties(picked.value.folderPath, "rest")+ workspaceTabs.currentActiveTab.value.document.inheritedProperties =+ cascadeParentCollectionForProperties(picked.value.folderPath, "rest")+ }platform.analytics?.logEvent({type: "HOPP_SAVE_REQUEST",createdNow: true,- platform: "rest",+ platform: isGQLRequest(requestUpdated) ? "gql" : "rest",workspaceType: "personal",})requestSaved()} else if (picked.value.pickedType === "my-request") {- if (!isHoppRESTRequest(requestUpdated))- throw new Error("requestUpdated is not a REST Request")-// Overwriting replaces the target's content, not its identity — keep the// target's own `_ref_id` and backend `id` so its tabs stay bound to it and// the source doesn't share identity with the copy@@ -455,57 +494,67 @@ const saveRequestAs = async () => {requestUpdated)- RESTTabs.currentActiveTab.value.document = {- request: requestUpdated,- isDirty: false,- type: "request",- saveContext: {- originLocation: "user-collection",- folderPath: picked.value.folderPath,- requestIndex: picked.value.requestIndex,- requestRefID: requestUpdated._ref_id ?? requestUpdated.id,- },- }+ if (isGQLRequest(requestUpdated)) {+ workspaceTabs.currentActiveTab.value.document = {+ type: "gql-request",+ request: requestUpdated as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext: {+ originLocation: "user-collection",+ folderPath: picked.value.folderPath,+ requestIndex: picked.value.requestIndex,+ requestRefID: requestUpdated._ref_id ?? requestUpdated.id,+ },+ inheritedProperties: cascadeParentCollectionForProperties(+ picked.value.folderPath,+ "rest"+ ),+ }+ } else {+ workspaceTabs.currentActiveTab.value.document = {+ request: requestUpdated as HoppRESTRequest,+ isDirty: false,+ type: "request",+ saveContext: {+ originLocation: "user-collection",+ folderPath: picked.value.folderPath,+ requestIndex: picked.value.requestIndex,+ requestRefID: requestUpdated._ref_id ?? requestUpdated.id,+ },+ }- RESTTabs.currentActiveTab.value.document.inheritedProperties =- cascadeParentCollectionForProperties(picked.value.folderPath, "rest")+ workspaceTabs.currentActiveTab.value.document.inheritedProperties =+ cascadeParentCollectionForProperties(picked.value.folderPath, "rest")+ }platform.analytics?.logEvent({type: "HOPP_SAVE_REQUEST",createdNow: false,- platform: "rest",+ platform: isGQLRequest(requestUpdated) ? "gql" : "rest",workspaceType: "personal",})requestSaved()} else if (picked.value.pickedType === "teams-collection") {- if (!isHoppRESTRequest(requestUpdated))- throw new Error("requestUpdated is not a REST Request")-updateTeamCollectionOrFolder(picked.value.collectionID, requestUpdated)platform.analytics?.logEvent({type: "HOPP_SAVE_REQUEST",createdNow: true,- platform: "rest",+ platform: isGQLRequest(requestUpdated) ? "gql" : "rest",workspaceType: "team",})} else if (picked.value.pickedType === "teams-folder") {- if (!isHoppRESTRequest(requestUpdated))- throw new Error("requestUpdated is not a REST Request")-updateTeamCollectionOrFolder(picked.value.folderID, requestUpdated)platform.analytics?.logEvent({type: "HOPP_SAVE_REQUEST",createdNow: true,- platform: "rest",+ platform: isGQLRequest(requestUpdated) ? "gql" : "rest",workspaceType: "team",})} else if (picked.value.pickedType === "teams-request") {- if (!isHoppRESTRequest(requestUpdated))- throw new Error("requestUpdated is not a REST Request")-if (collectionsType.value.type !== "team-collections" ||!collectionsType.value.selectedTeam@@ -522,7 +571,7 @@ const saveRequestAs = async () => {platform.analytics?.logEvent({type: "HOPP_SAVE_REQUEST",createdNow: false,- platform: "rest",+ platform: isGQLRequest(requestUpdated) ? "gql" : "rest",workspaceType: "team",})@@ -637,7 +686,7 @@ const saveRequestAs = async () => {*/const updateTeamCollectionOrFolder = (collectionID: string,- requestUpdated: HoppRESTRequest+ requestUpdated: HoppRESTRequest | HoppGQLRequest) => {if (collectionsType.value.type !== "team-collections" ||@@ -662,16 +711,37 @@ const updateTeamCollectionOrFolder = ((result) => {const { createRequestInCollection } = result- RESTTabs.currentActiveTab.value.document = {- request: requestUpdated,- isDirty: false,- type: "request",- saveContext: {- originLocation: "team-collection",- requestID: createRequestInCollection.id,- collectionID: createRequestInCollection.collection.id,- teamID: createRequestInCollection.collection.team.id,- },+ const saveContext = {+ originLocation: "team-collection" as const,+ requestID: createRequestInCollection.id,+ collectionID: createRequestInCollection.collection.id,+ teamID: createRequestInCollection.collection.team.id,+ }++ // Cascade team folder auth/headers/variables onto the saved tab —+ // without this, inherited auth doesn't apply until reload+ const inheritedProperties =+ teamCollectionService.cascadeParentCollectionForProperties(+ collectionID+ )++ if (isGQLRequest(requestUpdated)) {+ workspaceTabs.currentActiveTab.value.document = {+ type: "gql-request",+ request: requestUpdated as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext,+ inheritedProperties,+ }+ } else {+ workspaceTabs.currentActiveTab.value.document = {+ type: "request",+ request: requestUpdated as HoppRESTRequest,+ isDirty: false,+ saveContext,+ inheritedProperties,+ }}modalLoadingState.value = false@@ -685,7 +755,7 @@ const requestSaved = (tab: "REST" | "GQL" = "REST") => {toast.success(`${t("request.added")}`)nextTick(() => {if (tab === "REST") {- RESTTabs.currentActiveTab.value.document.isDirty = false+ workspaceTabs.currentActiveTab.value.document.isDirty = false} else {GQLTabs.currentActiveTab.value.document.isDirty = false}diff --git a/packages/hoppscotch-common/src/components/collections/TeamCollections.vue b/packages/hoppscotch-common/src/components/collections/TeamCollections.vueindex 3a56c3a27..8db4faa0b 100644--- a/packages/hoppscotch-common/src/components/collections/TeamCollections.vue+++ b/packages/hoppscotch-common/src/components/collections/TeamCollections.vue@@ -91,6 +91,13 @@folder: node.data.data.data,})"+ @add-gql-request="+ node.data.type === 'collections' &&+ emit('add-gql-request', {+ path: node.id,+ folder: node.data.data.data,+ })+ "@add-folder="node.data.type === 'collections' &&emit('add-folder', {@@ -208,6 +215,13 @@folder: node.data.data.data,})"+ @add-gql-request="+ node.data.type === 'folders' &&+ emit('add-gql-request', {+ path: node.id,+ folder: node.data.data.data,+ })+ "@add-folder="node.data.type === 'folders' &&emit('add-folder', {@@ -526,11 +540,11 @@ import { TeamCollection } from "~/helpers/teams/TeamCollection"import { TeamRequest } from "~/helpers/teams/TeamRequest"import { ChildrenResult, SmartTreeAdapter } from "@hoppscotch/ui/helpers"import { cloneDeep } from "lodash-es"-import { HoppRESTRequest } from "@hoppscotch/data"+import { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"import { pipe } from "fp-ts/function"import * as O from "fp-ts/Option"import { Picked } from "~/helpers/types/HoppPicked.js"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { useService } from "dioc/vue"import { TeamWorkspace } from "~/services/workspace.service"import { useDebounceFn } from "@vueuse/core"@@ -538,7 +552,7 @@ import { CurrentSortValuesService } from "~/services/current-sort.service"const t = useI18n()const colorMode = useColorMode()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)type CollectionType =| {@@ -623,6 +637,13 @@ const emit = defineEmits<{folder: TeamCollection}): void+ (+ event: "add-gql-request",+ payload: {+ path: string+ folder: TeamCollection+ }+ ): void(event: "add-folder",payload: {@@ -714,7 +735,7 @@ const emit = defineEmits<{(event: "share-request",payload: {- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequest}): void(diff --git a/packages/hoppscotch-common/src/components/collections/documentation/CollectionPreview.vue b/packages/hoppscotch-common/src/components/collections/documentation/CollectionPreview.vueindex 589209f4f..95dd62b05 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/CollectionPreview.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/CollectionPreview.vue@@ -5,7 +5,7 @@class="flex-1 min-w-0 flex flex-col space-y-8 overflow-y-auto"><div class="px-4">- <h1 class="text-3xl font-bold text-secondaryDark my-2">+ <h1 class="text-3xl font-bold text-secondaryDark my-2 truncate">{{ collectionName }}</h1></div>diff --git a/packages/hoppscotch-common/src/components/collections/documentation/CollectionStructure.vue b/packages/hoppscotch-common/src/components/collections/documentation/CollectionStructure.vueindex 9431c1d04..7714f725c 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/CollectionStructure.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/CollectionStructure.vue@@ -10,7 +10,7 @@class="sticky top-0 z-[99] py-2 border-b border-divider bg-primaryLight flex items-center justify-between space-x-3"><div- class="font-medium text-secondaryDark flex flex-1 items-center text-xs px-4 truncate cursor-pointer transition-colors"+ class="font-medium text-secondaryDark flex min-w-0 flex-1 items-center text-xs px-4 truncate cursor-pointer transition-colors"@click="scrollToTop"><span class="truncate">@@ -51,7 +51,7 @@<CollectionsDocumentationRequestItemv-for="(request, requestIndex) in collectionRequests":key="getRequestId(request, requestIndex)"- :request="request as HoppRESTRequest"+ :request="request":depth="0"@request-select="onRequestSelect"/>@@ -108,7 +108,7 @@ const props = withDefaults()const emit = defineEmits<{- (e: "request-select", request: HoppRESTRequest): void+ (e: "request-select", request: HoppRequest): void(e: "folder-select", folder: HoppCollection): void(e: "scroll-to-top"): void}>()@@ -198,7 +198,7 @@ const toggleAllFolders = () => {}}-const onRequestSelect = (request: HoppRESTRequest) => {+const onRequestSelect = (request: HoppRequest) => {emit("request-select", request)}diff --git a/packages/hoppscotch-common/src/components/collections/documentation/FolderItem.vue b/packages/hoppscotch-common/src/components/collections/documentation/FolderItem.vueindex a3b11d856..f39d5541b 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/FolderItem.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/FolderItem.vue@@ -51,7 +51,7 @@<CollectionsDocumentationRequestItemv-for="(request, requestIndex) in folder.requests":key="getRequestId(request, requestIndex)"- :request="request as HoppRESTRequest"+ :request="request":depth="depth + 1"@request-select="emit('request-select', $event)"/>@@ -91,7 +91,7 @@ const folderName = computed(() => props.folder.name)const emit = defineEmits<{(e: "toggle-folder", folderId: string): void- (e: "request-select", request: HoppRESTRequest): void+ (e: "request-select", request: HoppRequest): void(e: "folder-select", folder: HoppCollection): void}>()diff --git a/packages/hoppscotch-common/src/components/collections/documentation/Preview.vue b/packages/hoppscotch-common/src/components/collections/documentation/Preview.vueindex 44a5e5896..cebb94f48 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/Preview.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/Preview.vue@@ -2,7 +2,7 @@<divid="documentation-container"ref="documentationContainerRef"- class="rounded-md flex-1 relative overflow-y-auto h-full"+ class="rounded-md flex-1 min-w-0 relative overflow-y-auto h-full"><divv-if="isLoading"@@ -107,9 +107,9 @@<div class="p-0"><CollectionsDocumentationRequestPreviewv-if="item.type === 'request'"- :request="item.item as HoppRESTRequest"+ :request="item.item as DocRequest":documentation-description="- (item.item as HoppRESTRequest).description || ''+ getRequestDescription(item.item as DocRequest)":collection-i-d="collectionID":collection-path="collectionPath"@@ -120,7 +120,7 @@:read-only="!hasTeamWriteAccess"@update:documentation-description="(value) =>- ((item.item as HoppRESTRequest).description = value)+ setRequestDescription(item.item as DocRequest, value)"@close-modal="closeModal"/>@@ -177,7 +177,11 @@import { ref, watch, nextTick, computed } from "vue"import { useVModel, useIntersectionObserver } from "@vueuse/core"import { useService } from "dioc/vue"-import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data"+import {+ HoppCollection,+ HoppGQLRequest,+ HoppRESTRequest,+} from "@hoppscotch/data"import { TeamCollectionsService } from "~/services/team-collection.service"import { DocumentationItem } from "~/composables/useDocumentationWorker"import LazyDocumentationItem from "./LazyDocumentationItem.vue"@@ -185,6 +189,14 @@ import { useI18n } from "~/composables/i18n"const t = useI18n()+type DocRequest = HoppRESTRequest | HoppGQLRequest++const getRequestDescription = (req: DocRequest): string => req.description || ""++const setRequestDescription = (req: DocRequest, value: string) => {+ req.description = value+}+type CollectionType = HoppCollection | nullconst props = withDefaults(@@ -240,7 +252,7 @@ const collectionDescription = useVModel({ passive: true })-const selectedRequest = ref<HoppRESTRequest | null>(null)+const selectedRequest = ref<HoppRESTRequest | HoppGQLRequest | null>(null)const selectedFolder = ref<HoppCollection | null>(null)const selectedItemId = ref<string | null>(null)@@ -385,7 +397,7 @@ const scrollToItemByNameAndType = (/*** Handles a request being selected from the collection structure*/-const handleRequestSelect = (request: HoppRESTRequest) => {+const handleRequestSelect = (request: HoppRESTRequest | HoppGQLRequest) => {selectedRequest.value = requestselectedFolder.value = nullselectedItemId.value = request.id || nulldiff --git a/packages/hoppscotch-common/src/components/collections/documentation/PublishDocSnapshotPreview.vue b/packages/hoppscotch-common/src/components/collections/documentation/PublishDocSnapshotPreview.vueindex 6b81de21f..b0ae714d8 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/PublishDocSnapshotPreview.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/PublishDocSnapshotPreview.vue@@ -208,6 +208,7 @@ import { ref, watch, markRaw, computed } from "vue"import { useI18n } from "~/composables/i18n"import {HoppCollection,+ HoppGQLRequest,HoppRESTRequest,Environment,translateToNewEnvironmentVariables,@@ -290,7 +291,7 @@ const handleCopyUrl = () => {type SnapshotDocumentationItem = {id: stringtype: "folder" | "request"- item: HoppCollection | HoppRESTRequest+ item: HoppCollection | HoppRESTRequest | HoppGQLRequestinheritedProperties: HoppInheritedProperty}@@ -380,14 +381,17 @@ const flattenCollection = (}if (collection.requests && collection.requests.length > 0) {- ;(collection.requests as HoppRESTRequest[]).forEach((request) => {- items.push({- id: request.id || (request as any)._ref_id || `request-${request.name}`,- type: "request",- item: request,- inheritedProperties: currentInheritedProps,- })- })+ ;(collection.requests as (HoppRESTRequest | HoppGQLRequest)[]).forEach(+ (request) => {+ items.push({+ id:+ request.id || (request as any)._ref_id || `request-${request.name}`,+ type: "request",+ item: request,+ inheritedProperties: currentInheritedProps,+ })+ }+ )}return itemsdiff --git a/packages/hoppscotch-common/src/components/collections/documentation/RequestItem.vue b/packages/hoppscotch-common/src/components/collections/documentation/RequestItem.vueindex 5a839e90c..5f8f4bd7b 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/RequestItem.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/RequestItem.vue@@ -1,9 +1,13 @@<template><div- class="py-1.5 space-x-2 flex items-center group cursor-pointer"+ class="py-1.5 space-x-2 flex min-w-0 items-center group cursor-pointer"@click.stop="$emit('request-select', actualRequest)">+ <span v-if="isGql" class="flex flex-shrink-0 items-center px-1">+ <IconGraphql class="svg-icons h-3.5 w-3.5 text-accent" />+ </span><span+ v-elseclass="text-tiny px-1 rounded-sm":class="getMethodClass(requestMethod)">@@ -18,10 +22,11 @@</template><script lang="ts" setup>-import { HoppRESTRequest } from "@hoppscotch/data"+import { HoppGQLRequest, HoppRESTRequest, isGQLRequest } from "@hoppscotch/data"import { computed } from "vue"+import IconGraphql from "~icons/hopp/graphql"-type HoppRequest = HoppRESTRequest+type HoppRequest = HoppRESTRequest | HoppGQLRequestconst props = defineProps<{request: HoppRequest@@ -29,19 +34,22 @@ const props = defineProps<{}>()defineEmits<{- (e: "request-select", request: HoppRESTRequest): void+ (e: "request-select", request: HoppRequest): void}>()-const actualRequest = computed<HoppRESTRequest>(() => {+const actualRequest = computed<HoppRequest>(() => {return props.request})+const isGql = computed<boolean>(() => isGQLRequest(props.request))+const requestName = computed<string>(() => {return props.request.name || "Untitled Request"})const requestMethod = computed<string>(() => {- return props.request.method+ if (isGql.value) return ""+ return (props.request as HoppRESTRequest).method})/**diff --git a/packages/hoppscotch-common/src/components/collections/documentation/RequestPreview.vue b/packages/hoppscotch-common/src/components/collections/documentation/RequestPreview.vueindex bc6af3025..ffcc61157 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/RequestPreview.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/RequestPreview.vue@@ -3,14 +3,21 @@<div v-if="request" class="space-y-8"><div class="flex-col space-y-4"><div class="flex items-center justify-between mb-2">- <div class="flex items-center gap-3">+ <div class="flex min-w-0 items-center gap-3"><span- class="px-2 py-1 text-xs font-mono rounded"+ v-if="isGqlRequest"+ class="flex flex-shrink-0 items-center rounded px-2 py-1"+ >+ <IconGraphql class="svg-icons h-4 w-4 text-accent" />+ </span>+ <span+ v-else+ class="flex-shrink-0 px-2 py-1 text-xs font-mono rounded":class="getMethodClass(requestMethod)">{{ requestMethod }}</span>- <h1 class="text-2xl font-bold text-secondaryDark">+ <h1 class="min-w-0 truncate text-2xl font-bold text-secondaryDark">{{ requestName }}</h1></div>@@ -24,12 +31,12 @@class="text-secondaryLight text-sm break-all bg-primaryLight py-1 pl-2 rounded-md flex justify-between items-center"><span>- {{ getFullEndpoint }}+ {{ requestUrl }}</span><span><HoppSmartItem:icon="IconCopy"- @click="copyToClipboard(getFullEndpoint)"+ @click="copyToClipboard(requestUrl)"/></span></div>@@ -44,40 +51,68 @@/></div>- <CollectionsDocumentationSectionsCurlView- :request="request"- :collection-i-d="collectionID"- :collection-path="collectionPath"- :folder-path="folderPath"- :request-index="requestIndex"- :team-i-d="teamID"- :inherited-properties="inheritedProperties"- :environment-variables="environmentVariables"- />-- <CollectionsDocumentationSectionsAuth- :auth="request?.auth"- :inherited-auth="inheritedProperties?.auth"- />-- <CollectionsDocumentationSectionsHeaders- :headers="request?.headers || []"- :inherited-headers="inheritedProperties?.headers"- />-- <CollectionsDocumentationSectionsParameters- :params="request?.params || []"- />-- <CollectionsDocumentationSectionsVariables- :variables="request?.requestVariables || []"- />-- <CollectionsDocumentationSectionsRequestBody :body="request?.body" />-- <CollectionsDocumentationSectionsResponse- :response-examples="getResponseExamples()"- />+ <template v-if="isGqlRequest">+ <CollectionsDocumentationSectionsQuery+ :query="(request as HoppGQLRequest).query"+ />++ <CollectionsDocumentationSectionsAuth+ :auth="request?.auth"+ :inherited-auth="inheritedProperties?.auth"+ />++ <CollectionsDocumentationSectionsHeaders+ :headers="(request as HoppGQLRequest)?.headers || []"+ :inherited-headers="inheritedProperties?.headers"+ />++ <CollectionsDocumentationSectionsGqlVariables+ :variables="(request as HoppGQLRequest).variables"+ />++ <CollectionsDocumentationSectionsResponse+ :response-examples="getResponseExamples()"+ />+ </template>++ <template v-else>+ <CollectionsDocumentationSectionsCurlView+ :request="request as HoppRESTRequest"+ :collection-i-d="collectionID"+ :collection-path="collectionPath"+ :folder-path="folderPath"+ :request-index="requestIndex"+ :team-i-d="teamID"+ :inherited-properties="inheritedProperties"+ :environment-variables="environmentVariables"+ />++ <CollectionsDocumentationSectionsAuth+ :auth="request?.auth"+ :inherited-auth="inheritedProperties?.auth"+ />++ <CollectionsDocumentationSectionsHeaders+ :headers="(request as HoppRESTRequest)?.headers || []"+ :inherited-headers="inheritedProperties?.headers"+ />++ <CollectionsDocumentationSectionsParameters+ :params="(request as HoppRESTRequest)?.params || []"+ />++ <CollectionsDocumentationSectionsVariables+ :variables="(request as HoppRESTRequest)?.requestVariables || []"+ />++ <CollectionsDocumentationSectionsRequestBody+ :body="(request as HoppRESTRequest)?.body"+ />++ <CollectionsDocumentationSectionsResponse+ :response-examples="getResponseExamples()"+ />+ </template></div><div v-else class="text-center py-8 text-secondaryLight">@@ -91,16 +126,19 @@import {Environment,HoppCollectionVariable,+ HoppGQLRequest,HoppRESTRequest,+ isGQLRequest,makeRESTRequest,} from "@hoppscotch/data"import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"import { ref, computed, watch } from "vue"import IconCopy from "~icons/lucide/copy"import IconExternalLink from "~icons/lucide/external-link"+import IconGraphql from "~icons/hopp/graphql"import { useToast } from "~/composables/toast"import { useService } from "dioc/vue"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { TeamCollectionsService } from "~/services/team-collection.service"import { DocumentationService } from "~/services/documentation.service"import { cascadeParentCollectionForProperties } from "~/newstore/collections"@@ -121,7 +159,7 @@ const toast = useToast()const props = withDefaults(defineProps<{documentationDescription?: string- request?: HoppRESTRequest | null+ request?: HoppRESTRequest | HoppGQLRequest | nullcollectionID?: stringcollectionPath?: string | nullfolderPath?: string | null@@ -152,17 +190,22 @@ const emit = defineEmits<{(event: "close-modal"): void}>()-const restTabs = useService(RESTTabService)+const workspaceTabs = useService(WorkspaceTabsService)const teamCollectionsService = useService(TeamCollectionsService)const documentationService = useService(DocumentationService)+const isGqlRequest = computed<boolean>(() =>+ props.request ? isGQLRequest(props.request) : false+)+const requestName = computed<string>(() => {if (!props.request) return ""return props.request.name || t("documentation.untitled_request")})const requestMethod = computed<string>(() => {- return props.request?.method || "GET"+ if (!props.request || isGqlRequest.value) return "GET"+ return (props.request as HoppRESTRequest).method || "GET"})const requestId = computed<string>(() => {@@ -205,8 +248,9 @@ const inheritedProperties = computed(() => {})const getEffectiveRequest = async () => {- if (!props.request) return null+ if (!props.request || isGqlRequest.value) return null+ const restReq = props.request as HoppRESTRequestlet collectionVariables: HoppCollectionVariable[] = []if (inheritedProperties.value) {@@ -215,7 +259,7 @@ const getEffectiveRequest = async () => {)}- const requestVariables = (props.request.requestVariables || []).map(+ const requestVariables = (restReq.requestVariables || []).map((requestVariable) => {if (requestVariable.active)return {@@ -249,7 +293,7 @@ const getEffectiveRequest = async () => {const effectiveReq = await getEffectiveRESTRequest(makeRESTRequest({- ...props.request,+ ...restReq,}),env,true,@@ -272,13 +316,15 @@ watch(function getResponseExamples() {if (!props.request) return null- if (- props.request.responses &&- Object.keys(props.request.responses).length > 0- ) {+ // Both REST and GQL requests now carry a `responses` map of the same shape;+ // the documentation section consumes a generic `{name,statusCode,headers,body}`.+ const responses = (props.request as HoppRESTRequest | HoppGQLRequest)+ .responses++ if (responses && Object.keys(responses).length > 0) {const examples = []- for (const [name, response] of Object.entries(props.request.responses)) {+ for (const [name, response] of Object.entries(responses)) {if (response && typeof response === "object") {const example = {name: name || "Response Example",@@ -363,6 +409,12 @@ function getMethodClass(method: string): string {const getFullEndpoint = ref("")+const requestUrl = computed<string>(() => {+ if (!props.request) return ""+ if (isGqlRequest.value) return (props.request as HoppGQLRequest).url || ""+ return getFullEndpoint.value+})+const updateFullEndpoint = async () => {const res = await getEffectiveRequest()@@ -442,14 +494,27 @@ const openInNewTab = () => {collectionID: props.folderPath!,}- const possibleTeamTab = restTabs.getTabRefWithSaveContext(saveContext)+ const possibleTeamTab =+ workspaceTabs.getTabRefWithSaveContext(saveContext)if (possibleTeamTab) {- restTabs.setActiveTab(possibleTeamTab.value.id)+ workspaceTabs.setActiveTab(possibleTeamTab.value.id)+ } else if (isGqlRequest.value) {+ workspaceTabs.createNewTab({+ type: "gql-request",+ request: cloneDeep(props.request) as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext,+ inheritedProperties:+ teamCollectionsService.cascadeParentCollectionForProperties(+ props.folderPath!+ ),+ })} else {- restTabs.createNewTab({+ workspaceTabs.createNewTab({type: "request",- request: cloneDeep(props.request),+ request: cloneDeep(props.request) as HoppRESTRequest,isDirty: false,saveContext,inheritedProperties:@@ -466,14 +531,29 @@ const openInNewTab = () => {requestRefID: requestId.value,}- const possibleUserTab = restTabs.getTabRefWithSaveContext(saveContext)+ const possibleUserTab =+ workspaceTabs.getTabRefWithSaveContext(saveContext)if (possibleUserTab) {- restTabs.setActiveTab(possibleUserTab.value.id)+ workspaceTabs.setActiveTab(possibleUserTab.value.id)+ } else if (isGqlRequest.value) {+ workspaceTabs.createNewTab({+ type: "gql-request",+ request: cloneDeep(props.request) as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext,+ // "rest" is correct for a GQL request here: docs only render+ // unified collections, whose paths index restCollectionStore+ inheritedProperties: cascadeParentCollectionForProperties(+ props.folderPath,+ "rest"+ ),+ })} else {- restTabs.createNewTab({+ workspaceTabs.createNewTab({type: "request",- request: cloneDeep(props.request),+ request: cloneDeep(props.request) as HoppRESTRequest,isDirty: false,saveContext,inheritedProperties: cascadeParentCollectionForProperties(@@ -483,17 +563,28 @@ const openInNewTab = () => {})}} else {- // Fallback: create a new tab without save context+ // Fallback when collection-type can't be determined from props.console.warn("Unable to determine collection type, creating tab without save context")- restTabs.createNewTab({- type: "request",- request: cloneDeep(props.request),- isDirty: false,- saveContext: undefined,- inheritedProperties: undefined,- })+ if (isGqlRequest.value) {+ workspaceTabs.createNewTab({+ type: "gql-request",+ request: cloneDeep(props.request) as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext: undefined,+ inheritedProperties: undefined,+ })+ } else {+ workspaceTabs.createNewTab({+ type: "request",+ request: cloneDeep(props.request) as HoppRESTRequest,+ isDirty: false,+ saveContext: undefined,+ inheritedProperties: undefined,+ })+ }}emit("close-modal")diff --git a/packages/hoppscotch-common/src/components/collections/documentation/index.vue b/packages/hoppscotch-common/src/components/collections/documentation/index.vueindex 49f23bd09..42d6adae1 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/index.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/index.vue@@ -10,7 +10,7 @@<template #body><div class="w-full h-[80vh] overflow-hidden"><div class="flex h-full">- <div class="flex-1 flex">+ <div class="flex min-w-0 flex-1"><CollectionsDocumentationPreviewv-if="currentCollection"v-model:documentation-description="documentationDescription"@@ -259,7 +259,11 @@ import { useToast } from "~/composables/toast"import { useDocumentationWorker } from "~/composables/useDocumentationWorker"import { useService } from "dioc/vue"-import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data"+import {+ HoppCollection,+ HoppGQLRequest,+ HoppRESTRequest,+} from "@hoppscotch/data"import { TeamCollection } from "~/helpers/teams/TeamCollection"import {@@ -278,8 +282,8 @@ import {} from "~/helpers/backend/helpers"import { GQLError } from "~/helpers/backend/GQLClient"import { getErrorMessage } from "~/helpers/backend/mutations/MockServer"-import { HoppRESTSaveContext } from "~/helpers/rest/document"-import { RESTTabService } from "~/services/tab/rest"+import { HoppTabSaveContext } from "~/helpers/tab/document"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import {DocumentationService,@@ -324,7 +328,7 @@ const props = withDefaults(folderPath?: string | nullrequestIndex?: number | nullrequestID?: string | null- request?: HoppRESTRequest | null+ request?: HoppRESTRequest | HoppGQLRequest | nullteamID?: stringisTeamCollection?: boolean}>(),@@ -344,7 +348,7 @@ const props = withDefaults()const documentationService = useService(DocumentationService)-const restTabs = useService(RESTTabService)+const restTabs = useService(WorkspaceTabsService)/*** Mirrors a saved documentation description onto any open tabs of the request —@@ -352,7 +356,7 @@ const restTabs = useService(RESTTabService)* description back over the one just saved.*/const syncOpenRequestTabDescription = (- saveContext: HoppRESTSaveContext,+ saveContext: HoppTabSaveContext,description: string) => {const possibleTabs = restTabs.getTabsRefWithSaveContext(saveContext)@@ -362,7 +366,8 @@ const syncOpenRequestTabDescription = (// tab is closed, and it's read again after a tickconst tabDocument = possibleTab.value.document- if (tabDocument.type !== "request") continue+ if (tabDocument.type !== "request" && tabDocument.type !== "gql-request")+ continueconst wasDirty = tabDocument.isDirtytabDocument.request.description = descriptiondiff --git a/packages/hoppscotch-common/src/components/collections/documentation/sections/GqlVariables.vue b/packages/hoppscotch-common/src/components/collections/documentation/sections/GqlVariables.vuenew file mode 100644index 000000000..6c0f5d939--- /dev/null+++ b/packages/hoppscotch-common/src/components/collections/documentation/sections/GqlVariables.vue@@ -0,0 +1,42 @@+<template>+ <div v-if="hasVariables" class="w-full space-y-2">+ <h2+ class="text-sm font-semibold text-secondaryDark flex items-end px-4 p-2 border-b border-divider"+ >+ <span>{{ t("documentation.variables.title") }}</span>+ </h2>+ <div class="px-4 py-2">+ <pre+ class="bg-primaryLight p-3 rounded my-2 overflow-auto max-h-64 text-xs font-mono text-secondaryLight"+ >{{ formatted }}</pre>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { computed } from "vue"+import { useI18n } from "~/composables/i18n"++const t = useI18n()++const props = defineProps<{+ variables?: string+}>()++// GQL variables are stored as a JSON string. An empty `{}` is the schema+// default — render the section only when the user has actually populated it.+const hasVariables = computed(() => {+ if (!props.variables) return false+ const trimmed = props.variables.trim()+ return trimmed.length > 0 && trimmed !== "{}"+})++const formatted = computed(() => {+ if (!props.variables) return ""+ try {+ return JSON.stringify(JSON.parse(props.variables), null, 2)+ } catch {+ return props.variables+ }+})+</script>diff --git a/packages/hoppscotch-common/src/components/collections/documentation/sections/Query.vue b/packages/hoppscotch-common/src/components/collections/documentation/sections/Query.vuenew file mode 100644index 000000000..2583584a3--- /dev/null+++ b/packages/hoppscotch-common/src/components/collections/documentation/sections/Query.vue@@ -0,0 +1,48 @@+<template>+ <div v-if="query" class="w-full space-y-2">+ <h2+ class="text-sm font-semibold text-secondaryDark flex items-end justify-between px-4 p-2 border-b border-divider"+ >+ <span>{{ t("documentation.query.title") }}</span>+ <HoppSmartItem+ :icon="copied ? IconCheck : IconCopy"+ :title="t('documentation.copy_to_clipboard')"+ @click="copyToClipboard"+ />+ </h2>+ <div class="px-4 py-2">+ <pre+ class="bg-primaryLight p-3 rounded my-2 overflow-auto max-h-96 text-xs font-mono text-secondaryLight whitespace-pre"+ >{{ query }}</pre>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { ref } from "vue"+import IconCopy from "~icons/lucide/copy"+import IconCheck from "~icons/lucide/check"+import { useI18n } from "~/composables/i18n"+import { useToast } from "~/composables/toast"++const t = useI18n()+const toast = useToast()++const props = defineProps<{+ query?: string+}>()++const copied = ref(false)++const copyToClipboard = async () => {+ if (!props.query) return+ try {+ await navigator.clipboard.writeText(props.query)+ copied.value = true+ toast.success(t("documentation.copied_to_clipboard"))+ setTimeout(() => (copied.value = false), 1000)+ } catch (err) {+ console.error("Failed to copy: ", err)+ }+}+</script>diff --git a/packages/hoppscotch-common/src/components/collections/documentation/sections/RequestBody.vue b/packages/hoppscotch-common/src/components/collections/documentation/sections/RequestBody.vueindex 6d7edcf0a..1678014a8 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/sections/RequestBody.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/sections/RequestBody.vue@@ -19,8 +19,7 @@<div v-if="body.contentType === 'application/json'"><preclass="bg-primaryLight p-3 rounded my-2 overflow-auto max-h-64 text-xs font-mono text-secondaryLight"- >{{ formatJSON(body.body) }}</pre- >+ >{{ formatJSON(body.body) }}</pre></div><div v-else-if="body.contentType === 'application/x-www-form-urlencoded'">@@ -55,8 +54,7 @@<div v-else><preclass="bg-primaryLight p-3 rounded my-2 overflow-auto max-h-64 font-mono text-secondaryLight"- >{{ body.body }}</pre- >+ >{{ body.body }}</pre></div></div></div>diff --git a/packages/hoppscotch-common/src/components/collections/documentation/sections/Response.vue b/packages/hoppscotch-common/src/components/collections/documentation/sections/Response.vueindex b2367bbab..2812033fc 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/sections/Response.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/sections/Response.vue@@ -51,14 +51,12 @@<div v-if="isJsonResponse(example)"><preclass="bg-primaryLight p-3 rounded my-2 overflow-auto max-h-64 text-sm font-mono text-secondaryLight"- >{{ formatJSON(example.body) }}</pre- >+ >{{ formatJSON(example.body) }}</pre></div><div v-else><preclass="bg-primaryLight p-3 rounded my-2 overflow-auto max-h-64 text-sm font-mono text-secondaryLight"- >{{ example.body }}</pre- >+ >{{ example.body }}</pre></div></div></HoppSmartTab>diff --git a/packages/hoppscotch-common/src/components/collections/graphql/index.vue b/packages/hoppscotch-common/src/components/collections/graphql/index.vueindex cd454fc36..cd4027500 100644--- a/packages/hoppscotch-common/src/components/collections/graphql/index.vue+++ b/packages/hoppscotch-common/src/components/collections/graphql/index.vue@@ -186,6 +186,7 @@ import {getDefaultGQLRequest,HoppCollection,HoppGQLRequest,+ isGQLRequest,} from "@hoppscotch/data"import { Picked } from "~/helpers/types/HoppPicked"import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"@@ -528,6 +529,12 @@ const selectRequest = ({folderPath: stringrequestIndex: number}) => {+ // GQL collections can hold REST-shaped requests (mixed import) — they+ // can't open as GQL tabs on this page+ if (!isGQLRequest(request)) {+ toast.error(t("request.rest_in_gql_collection"))+ return+ }const possibleTab = tabs.getTabRefWithSaveContext({originLocation: "user-collection",folderPath: folderPath,diff --git a/packages/hoppscotch-common/src/components/collections/index.vue b/packages/hoppscotch-common/src/components/collections/index.vueindex d0b241070..6ac9a15ff 100644--- a/packages/hoppscotch-common/src/components/collections/index.vue+++ b/packages/hoppscotch-common/src/components/collections/index.vue@@ -42,6 +42,7 @@"@add-folder="addFolder"@add-request="addRequest"+ @add-gql-request="addGqlRequest"@edit-request="editRequest"@edit-collection="editCollection"@edit-folder="editFolder"@@ -94,6 +95,7 @@:collection-move-loading="collectionMoveLoading":request-move-loading="requestMoveLoading"@add-request="addRequest"+ @add-gql-request="addGqlRequest"@add-folder="addFolder"@collection-click="handleCollectionClick"@duplicate-collection="duplicateCollection"@@ -150,6 +152,7 @@<CollectionsAddRequest:show="showModalAddRequest":loading-state="modalLoadingState"+ :request-type="requestTypeToAdd"@add-request="onAddRequest"@hide-modal="displayModalAddRequest(false)"/>@@ -304,13 +307,20 @@ import {generateUniqueRefId,getDefaultRESTRequest,HoppCollection,+ HoppGQLRequest,+ HoppGQLRequestResponse,HoppRESTAuth,HoppRESTHeaders,HoppRESTRequest,HoppRESTRequestResponse,+ isGQLRequest,makeCollection,+ makeHoppGQLResponseOriginalRequest,makeHoppRESTResponseOriginalRequest,} from "@hoppscotch/data"+import { getDefaultGQLRequest } from "~/helpers/graphql/default"+import { parse as parseGQLDocument } from "graphql"+import type { OperationDefinitionNode } from "graphql"import { useService } from "dioc/vue"import { stripJsonSerializedModulePrefix } from "@hoppscotch/js-sandbox/scripting"@@ -366,6 +376,7 @@ import { stripRefIdReplacer } from "~/helpers/import-export/export"import { hoppCollectionToOpenAPI } from "~/helpers/import-export/export/openapi"import TeamEnvironmentAdapter from "~/helpers/teams/TeamEnvironmentAdapter"import { TeamSearchService } from "~/helpers/teams/TeamsSearch.service"+import { HoppTabDocument } from "~/helpers/tab/document"import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"import { Picked } from "~/helpers/types/HoppPicked"import {@@ -396,7 +407,7 @@ import { currentReorderingStatus$ } from "~/newstore/reordering"import { platform } from "~/platform"import { PersistedOAuthConfig } from "~/services/oauth/oauth.service"import { PersistenceService } from "~/services/persistence"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { TeamWorkspace, WorkspaceService } from "~/services/workspace.service"import { RESTOptionTabs } from "../http/RequestOptions.vue"import { Collection as NodeCollection } from "./MyCollections.vue"@@ -417,7 +428,7 @@ import {const t = useI18n()const toast = useToast()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const props = defineProps({saveRequest: {@@ -461,8 +472,9 @@ const editingCollectionPath = ref<string | null>(null)const editingFolder = ref<HoppCollection | TeamCollection | null>(null)const editingFolderName = ref<string | null>(null)const editingFolderPath = ref<string | null>(null)+const requestTypeToAdd = ref<"rest" | "gql">("rest")-const editingRequest = ref<HoppRESTRequest | null>(null)+const editingRequest = ref<HoppRESTRequest | HoppGQLRequest | null>(null)const editingRequestName = ref("")const editingResponseName = ref("")const editingResponseOldName = ref("")@@ -494,6 +506,18 @@ const currentUser = useReadonlyStream(const myCollections = useReadonlyStream(restCollections$, [], "deep")+const setRequestTabResponses = (+ tabRef: { value: { document: HoppTabDocument } },+ responses: HoppRESTRequest["responses"] | HoppGQLRequest["responses"]+) => {+ const doc = tabRef.value.document+ if (doc.type === "request") {+ doc.request.responses = responses as HoppRESTRequest["responses"]+ } else if (doc.type === "gql-request") {+ doc.request.responses = responses as HoppGQLRequest["responses"]+ }+}+// Draggingconst draggingToRoot = ref(false)const collectionMoveLoading = ref<string[]>([])@@ -707,15 +731,16 @@ const filteredCollections = computed(() => {const isMatch = (text: string) => text.toLowerCase().includes(filterText)- const isRequestMatch = (request: HoppRESTRequest) =>- isMatch(request.name) || isMatch(request.endpoint)+ const isRequestMatch = (request: HoppRESTRequest | HoppGQLRequest) =>+ isMatch(request.name) ||+ (!isGQLRequest(request) && isMatch(request.endpoint)) ||+ (isGQLRequest(request) && isMatch(request.url))for (const collection of collections) {const filteredRequests = []const filteredFolders = []for (const request of collection.requests) {- if (isRequestMatch(request as HoppRESTRequest))- filteredRequests.push(request)+ if (isRequestMatch(request)) filteredRequests.push(request)}for (const folder of collection.folders) {if (isMatch(folder.name)) filteredFolders.push(folder)@@ -1006,14 +1031,27 @@ const addRequest = (payload: {const { path, folder } = payloadeditingFolder.value = foldereditingFolderPath.value = path+ requestTypeToAdd.value = "rest"+ displayModalAddRequest(true)+}++const addGqlRequest = (payload: {+ path: string+ folder: HoppCollection | TeamCollection+}) => {+ const { path, folder } = payload+ editingFolder.value = folder+ editingFolderPath.value = path+ requestTypeToAdd.value = "gql"displayModalAddRequest(true)}const onAddRequest = async (requestName: string) => {- const newRequest = {- ...getDefaultRESTRequest(),- name: requestName,- }+ const isGqlRequest = requestTypeToAdd.value === "gql"++ const newRequest = isGqlRequest+ ? { ...getDefaultGQLRequest(), name: requestName }+ : { ...getDefaultRESTRequest(), name: requestName }const path = editingFolderPath.valueif (!path) return@@ -1023,24 +1061,40 @@ const onAddRequest = async (requestName: string) => {const insertionIndex = saveRESTRequestAs(path, newRequest)- tabs.createNewTab({- type: "request",- request: newRequest,- isDirty: false,- saveContext: {- originLocation: "user-collection",- folderPath: path,- requestIndex: insertionIndex,- requestRefID: newRequest._ref_id,- },- inheritedProperties: cascadeParentCollectionForProperties(path, "rest"),- })+ if (isGqlRequest) {+ tabs.createNewTab({+ type: "gql-request",+ request: newRequest as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext: {+ originLocation: "user-collection",+ folderPath: path,+ requestIndex: insertionIndex,+ requestRefID: (newRequest as HoppGQLRequest)._ref_id,+ },+ inheritedProperties: cascadeParentCollectionForProperties(path, "rest"),+ })+ } else {+ tabs.createNewTab({+ type: "request",+ request: newRequest as HoppRESTRequest,+ isDirty: false,+ saveContext: {+ originLocation: "user-collection",+ folderPath: path,+ requestIndex: insertionIndex,+ requestRefID: (newRequest as HoppRESTRequest)._ref_id,+ },+ inheritedProperties: cascadeParentCollectionForProperties(path, "rest"),+ })+ }platform.analytics?.logEvent({type: "HOPP_SAVE_REQUEST",workspaceType: "personal",createdNow: true,- platform: "rest",+ platform: isGqlRequest ? "gql" : "rest",})displayModalAddRequest(false)@@ -1061,7 +1115,7 @@ const onAddRequest = async (requestName: string) => {platform.analytics?.logEvent({type: "HOPP_SAVE_REQUEST",workspaceType: "team",- platform: "rest",+ platform: isGqlRequest ? "gql" : "rest",createdNow: true,})@@ -1075,20 +1129,42 @@ const onAddRequest = async (requestName: string) => {(result) => {const { createRequestInCollection } = result- tabs.createNewTab({- type: "request",- request: newRequest,- isDirty: false,- saveContext: {- originLocation: "team-collection",- requestID: createRequestInCollection.id,- collectionID: path,- teamID: createRequestInCollection.collection.team.id,- requestRefID: newRequest._ref_id,- },- inheritedProperties:- teamCollectionService.cascadeParentCollectionForProperties(path),- })+ if (isGqlRequest) {+ tabs.createNewTab({+ type: "gql-request",+ request: newRequest as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext: {+ originLocation: "team-collection",+ requestID: createRequestInCollection.id,+ collectionID: path,+ teamID: createRequestInCollection.collection.team.id,+ requestRefID: (newRequest as HoppGQLRequest)._ref_id,+ },+ inheritedProperties:+ teamCollectionService.cascadeParentCollectionForProperties(+ path+ ),+ })+ } else {+ tabs.createNewTab({+ type: "request",+ request: newRequest as HoppRESTRequest,+ isDirty: false,+ saveContext: {+ originLocation: "team-collection",+ requestID: createRequestInCollection.id,+ collectionID: path,+ teamID: createRequestInCollection.collection.team.id,+ requestRefID: (newRequest as HoppRESTRequest)._ref_id,+ },+ inheritedProperties:+ teamCollectionService.cascadeParentCollectionForProperties(+ path+ ),+ })+ }modalLoadingState.value = falsedisplayModalAddRequest(false)@@ -1355,7 +1431,7 @@ const duplicateCollection = async ({const editRequest = (payload: {folderPath: string | undefinedrequestIndex: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequest}) => {const { folderPath, requestIndex, request } = payloadeditingRequest.value = request@@ -1396,7 +1472,8 @@ const updateEditingRequest = async (newName: string) => {if (possibleActiveTab &&- possibleActiveTab.value.document.type === "request"+ (possibleActiveTab.value.document.type === "request" ||+ possibleActiveTab.value.document.type === "gql-request")) {possibleActiveTab.value.document.request.name = requestUpdated.namenextTick(() => {@@ -1438,7 +1515,11 @@ const updateEditingRequest = async (newName: string) => {requestID,})- if (possibleTab && possibleTab.value.document.type === "request") {+ if (+ possibleTab &&+ (possibleTab.value.document.type === "request" ||+ possibleTab.value.document.type === "gql-request")+ ) {possibleTab.value.document.request.name = requestNamenextTick(() => {possibleTab.value.document.isDirty = false@@ -1450,7 +1531,7 @@ const updateEditingRequest = async (newName: string) => {type ResponseConfigPayload = {folderPath: string | undefinedrequestIndex: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequestresponseName: stringresponseID: string}@@ -1521,12 +1602,17 @@ const updateEditingResponse = (newName: string) => {if (possibleExampleActiveTab &&- possibleExampleActiveTab.value.document.type === "example-response"+ (possibleExampleActiveTab.value.document.type === "example-response" ||+ possibleExampleActiveTab.value.document.type === "gql-example-response")) {possibleExampleActiveTab.value.document.response.name = newNamenextTick(() => {- if (possibleExampleActiveTab.value.document.type === "test-runner")+ const docType = possibleExampleActiveTab.value.document.type+ if (+ docType !== "example-response" &&+ docType !== "gql-example-response"+ )returnpossibleExampleActiveTab.value.document.isDirty = false@@ -1539,13 +1625,8 @@ const updateEditingResponse = (newName: string) => {})}- // update the request tab responses if it's open- if (- possibleRequestActiveTab &&- possibleRequestActiveTab.value.document.type === "request"- ) {- possibleRequestActiveTab.value.document.request.responses =- request.responses+ if (possibleRequestActiveTab) {+ setRequestTabResponses(possibleRequestActiveTab, request.responses)}displayModalEditResponse(false)@@ -1591,11 +1672,17 @@ const updateEditingResponse = (newName: string) => {if (possibleActiveResponseTab &&- possibleActiveResponseTab.value.document.type === "example-response"+ (possibleActiveResponseTab.value.document.type === "example-response" ||+ possibleActiveResponseTab.value.document.type ===+ "gql-example-response")) {possibleActiveResponseTab.value.document.response.name = newNamenextTick(() => {- if (possibleActiveResponseTab.value.document.type === "test-runner")+ const docType = possibleActiveResponseTab.value.document.type+ if (+ docType !== "example-response" &&+ docType !== "gql-example-response"+ )returnpossibleActiveResponseTab.value.document.isDirty = falsepossibleActiveResponseTab.value.document.saveContext = {@@ -1606,30 +1693,26 @@ const updateEditingResponse = (newName: string) => {})}- // update the request tab responses if it's open- if (- possibleRequestActiveTab &&- possibleRequestActiveTab.value.document.type === "request"- ) {- possibleRequestActiveTab.value.document.request.responses =- request.responses+ if (possibleRequestActiveTab) {+ setRequestTabResponses(possibleRequestActiveTab, request.responses)}}}const duplicateRequest = async (payload: {folderPath: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequest}) => {const { folderPath, request } = payloadif (!folderPath) returnconst { id: _, ...requestWithoutID } = request+ const cloned = cloneDeep(requestWithoutID)const newRequest = {- ...cloneDeep(requestWithoutID),+ ...cloned,_ref_id: generateUniqueRefId("req"),name: `${request.name} - ${t("action.duplicate")}`,- }+ } as HoppRESTRequest | HoppGQLRequestif (collectionsType.value.type === "my-collections") {const isValidToken = await handleTokenValidation()@@ -1704,13 +1787,8 @@ const duplicateResponse = async (payload: ResponseConfigPayload) => {folderPath,})- // update the request tab responses if it's open- if (- possibleRequestActiveTab &&- possibleRequestActiveTab.value.document.type === "request"- ) {- possibleRequestActiveTab.value.document.request.responses =- updatedRequest.responses+ if (possibleRequestActiveTab) {+ setRequestTabResponses(possibleRequestActiveTab, updatedRequest.responses)}} else if (hasTeamWriteAccess.value) {duplicateRequestLoading.value = true@@ -1737,25 +1815,21 @@ const duplicateResponse = async (payload: ResponseConfigPayload) => {))()- // update the request tab responses if it's open+ // update the request tab responses if it's open (REST or GQL)const possibleRequestActiveTab = tabs.getTabRefWithSaveContext({originLocation: "team-collection",requestID: requestIndex,})- if (- possibleRequestActiveTab &&- possibleRequestActiveTab.value.document.type === "request"- ) {- possibleRequestActiveTab.value.document.request.responses =- updatedRequest.responses+ if (possibleRequestActiveTab) {+ setRequestTabResponses(possibleRequestActiveTab, updatedRequest.responses)}}}const addExample = (payload: {folderPath: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequestrequestIndex: string | number}) => {const { folderPath, request, requestIndex } = payload@@ -1767,8 +1841,12 @@ const addExample = (payload: {return}- // Additional validation for required request properties- if (!request.name && !request.endpoint) {+ // Additional validation for required request properties — accept either the+ // REST endpoint or the GQL url as proof we have a real request.+ const hasUrl = isGQLRequest(request)+ ? !!request.url+ : !!(request as HoppRESTRequest).endpoint+ if (!request.name && !hasUrl) {console.error("Request missing required properties:", request)toast.error(t("error.invalid_request"))return@@ -1802,6 +1880,13 @@ const onAddExample = async () => {return}+ // GQL examples have a parallel-but-distinct shape (GQL originalRequest,+ // no method/params/body). Handle them via the gql-example-response tab type.+ if (isGQLRequest(request)) {+ await addGQLExample(request, exampleName)+ return+ }+// Check if example name already existsif (request.responses && request.responses[exampleName]) {toast.error(t("response.duplicate_name_error"))@@ -1972,6 +2057,170 @@ const onAddExample = async () => {}}+/**+ * GQL counterpart of the REST add-example flow inside `onAddExample`. Builds a+ * `HoppGQLRequestResponse` with an empty body, persists it under the parent+ * request's `responses` map, and opens it as a new `gql-example-response` tab.+ * Persistence goes through the REST mutation in both personal and team paths+ * because unified-workspace GQL bodies live in REST collection rows.+ */+const addGQLExample = async (request: HoppGQLRequest, exampleName: string) => {+ if (request.responses && request.responses[exampleName]) {+ toast.error(t("response.duplicate_name_error"))+ return+ }++ const originalRequest = makeHoppGQLResponseOriginalRequest({+ name: request.name,+ url: request.url,+ query: request.query,+ variables: request.variables,+ headers: request.headers,+ auth: request.auth,+ })++ // Stamp the operation identity from the request's document (first+ // operation — the one a run would execute) so the mock server can match+ // this example; without stamps the matcher skips it entirely+ let operationName: string | undefined+ let operationType: string | undefined+ try {+ const operation = parseGQLDocument(request.query).definitions.find(+ (definition): definition is OperationDefinitionNode =>+ definition.kind === "OperationDefinition"+ )+ if (operation) {+ operationType = operation.operation+ operationName = operation.name?.value+ }+ } catch (_e) {+ // Unparseable document — leave the example unstamped+ }++ const newExample: HoppGQLRequestResponse = {+ name: exampleName,+ code: 200,+ status: "OK",+ headers: [],+ body: "",+ originalRequest,+ ...(operationType ? { operationType } : {}),+ ...(operationName ? { operationName } : {}),+ }++ const newExampleID = Object.keys(request.responses ?? {}).length.toString()++ const updatedRequest: HoppGQLRequest = {+ ...request,+ responses: {+ ...(request.responses ?? {}),+ [exampleName]: newExample,+ },+ }++ if (collectionsType.value.type === "my-collections") {+ const folderPath = editingFolderPath.value+ const requestIndex = editingRequestIndex.value+ if (folderPath === null || requestIndex === null) return++ const isValidToken = await handleTokenValidation()+ if (!isValidToken) return++ editRESTRequest(folderPath, requestIndex, updatedRequest)+ toast.success(t("response.saved"))++ const possibleRequestActiveTab = tabs.getTabRefWithSaveContext({+ originLocation: "user-collection",+ requestIndex,+ folderPath,+ })+ if (+ possibleRequestActiveTab &&+ possibleRequestActiveTab.value.document.type === "gql-request"+ ) {+ possibleRequestActiveTab.value.document.request.responses =+ updatedRequest.responses+ }++ displayModalAddExample(false)++ tabs.createNewTab({+ response: { ...cloneDeep(newExample), name: exampleName },+ isDirty: false,+ type: "gql-example-response",+ saveContext: {+ originLocation: "user-collection",+ folderPath,+ requestIndex,+ exampleID: newExampleID,+ },+ inheritedProperties: cascadeParentCollectionForProperties(+ folderPath,+ "rest"+ ),+ })+ return+ }++ if (hasTeamWriteAccess.value) {+ if (!editingRequestID.value) return+ modalLoadingState.value = true++ const data = {+ requestID: editingRequestID.value,+ data: { title: request.name, request: JSON.stringify(updatedRequest) },+ }++ pipe(+ runMutation(UpdateRequestDocument, data),+ TE.match(+ (err: GQLError<string>) => {+ toast.error(`${getErrorMessage(err)}`)+ modalLoadingState.value = false+ },+ () => {+ modalLoadingState.value = false+ toast.success(t("response.saved"))+ displayModalAddExample(false)++ const requestID = editingRequestID.value+ const collectionID = editingFolderPath.value+ if (!requestID) return++ const possibleRequestActiveTab = tabs.getTabRefWithSaveContext({+ originLocation: "team-collection",+ requestID,+ })+ if (+ possibleRequestActiveTab &&+ possibleRequestActiveTab.value.document.type === "gql-request"+ ) {+ possibleRequestActiveTab.value.document.request.responses =+ updatedRequest.responses+ }++ tabs.createNewTab({+ response: { ...cloneDeep(newExample), name: exampleName },+ isDirty: false,+ type: "gql-example-response",+ saveContext: {+ originLocation: "team-collection",+ requestID,+ collectionID: collectionID ?? undefined,+ exampleID: newExampleID,+ },+ inheritedProperties: collectionID+ ? teamCollectionService.cascadeParentCollectionForProperties(+ collectionID+ )+ : undefined,+ })+ }+ )+ )()+ }+}+const removeCollection = (id: string) => {if (collectionsType.value.type === "my-collections")editingCollectionIndex.value = parseInt(id)@@ -2196,16 +2445,19 @@ const onRemoveRequest = async () => {requestIndex,})- // If there is a tab attached to this request, dissociate its state and mark it dirty- if (possibleTab && possibleTab.value.document.type === "request") {- possibleTab.value.document.saveContext = null- possibleTab.value.document.isDirty = true-- // since the request is deleted, we need to remove the saved responses as well- possibleTab.value.document.request.responses = {}-- // remove inherited properties- possibleTab.value.document.inheritedProperties = undefined+ if (possibleTab) {+ const doc = possibleTab.value.document+ if (doc.type === "request") {+ doc.saveContext = null+ doc.isDirty = true+ doc.request.responses = {}+ doc.inheritedProperties = undefined+ } else if (doc.type === "gql-request") {+ doc.saveContext = null+ doc.isDirty = true+ doc.request.responses = {}+ doc.inheritedProperties = undefined+ }}const requestToRemove = navigateToFolderWithIndexPath(@@ -2261,15 +2513,19 @@ const onRemoveRequest = async () => {requestID,})- if (possibleTab && possibleTab.value.document.type === "request") {- possibleTab.value.document.saveContext = null- possibleTab.value.document.isDirty = true-- // since the request is deleted, we need to remove the saved responses as well- possibleTab.value.document.request.responses = {}-- // remove inherited properties- possibleTab.value.document.inheritedProperties = undefined+ if (possibleTab) {+ const doc = possibleTab.value.document+ if (doc.type === "request") {+ doc.saveContext = null+ doc.isDirty = true+ doc.request.responses = {}+ doc.inheritedProperties = undefined+ } else if (doc.type === "gql-request") {+ doc.saveContext = null+ doc.isDirty = true+ doc.request.responses = {}+ doc.inheritedProperties = undefined+ }}}}@@ -2303,7 +2559,7 @@ const onRemoveResponse = async () => {delete request.responses[responseName]- const requestUpdated: HoppRESTRequest = {+ const requestUpdated: HoppRESTRequest | HoppGQLRequest = {...request,}@@ -2330,10 +2586,13 @@ const onRemoveResponse = async () => {folderPath,})- // If there is a tab attached to this request, close it and set the active tab to the first one+ // If there is a tab attached to this response (REST or GQL example), close+ // it and set the active tab to the first one.if (possibleActiveResponseTab &&- possibleActiveResponseTab.value.document.type === "example-response"+ (possibleActiveResponseTab.value.document.type === "example-response" ||+ possibleActiveResponseTab.value.document.type ===+ "gql-example-response")) {const activeTabs = tabs.getActiveTabs()@@ -2355,13 +2614,8 @@ const onRemoveResponse = async () => {}}- // update the request tab responses if it's open- if (- possibleRequestActiveTab &&- possibleRequestActiveTab.value.document.type === "request"- ) {- possibleRequestActiveTab.value.document.request.responses =- requestUpdated.responses+ if (possibleRequestActiveTab) {+ setRequestTabResponses(possibleRequestActiveTab, requestUpdated.responses)}toast.success(t("state.deleted"))@@ -2404,10 +2658,13 @@ const onRemoveResponse = async () => {requestID,})- // If there is a tab attached to this request, close it and set the active tab to the first one+ // If there is a tab attached to this response (REST or GQL example), close+ // it and set the active tab to the first one.if (possibleActiveResponseTab &&- possibleActiveResponseTab.value.document.type === "example-response"+ (possibleActiveResponseTab.value.document.type === "example-response" ||+ possibleActiveResponseTab.value.document.type ===+ "gql-example-response")) {const activeTabs = tabs.getActiveTabs()@@ -2429,13 +2686,8 @@ const onRemoveResponse = async () => {}}- // update the request tab responses if it's open- if (- possibleRequestActiveTab &&- possibleRequestActiveTab.value.document.type === "request"- ) {- possibleRequestActiveTab.value.document.request.responses =- requestUpdated.responses+ if (possibleRequestActiveTab) {+ setRequestTabResponses(possibleRequestActiveTab, requestUpdated.responses)}}}@@ -2450,7 +2702,7 @@ const selectPicked = (payload: Picked | null) => {* @param selectedRequest The request that the user clicked on emitted from the collection tree*/const selectRequest = (selectedRequest: {- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequestfolderPath: stringrequestIndex: stringisActive: boolean@@ -2474,17 +2726,34 @@ const selectRequest = (selectedRequest: {teamCollectionService.cascadeParentCollectionForProperties(folderPath)}+ const isGql = isGQLRequest(request)+const possibleTab = tabs.getTabRefWithSaveContext({originLocation: "team-collection",requestID: requestIndex,})- if (possibleTab && possibleTab.value.document.type === "request") {+ if (possibleTab) {tabs.setActiveTab(possibleTab.value.id)+ } else if (isGql) {+ tabs.createNewTab({+ type: "gql-request",+ request: cloneDeep(request) as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext: {+ originLocation: "team-collection",+ requestID: requestIndex,+ collectionID: folderPath,+ exampleID: undefined,+ requestRefID: request.id,+ },+ inheritedProperties: inheritedProperties,+ })} else {tabs.createNewTab({type: "request",- request: cloneDeep(request),+ request: cloneDeep(request) as HoppRESTRequest,isDirty: false,saveContext: {originLocation: "team-collection",@@ -2497,6 +2766,8 @@ const selectRequest = (selectedRequest: {})}} else {+ const isGql = isGQLRequest(request)+possibleTab = tabs.getTabRefWithSaveContext({originLocation: "user-collection",requestIndex: parseInt(requestIndex),@@ -2506,11 +2777,27 @@ const selectRequest = (selectedRequest: {if (possibleTab) {tabs.setActiveTab(possibleTab.value.id)+ } else if (isGql) {+ tabs.createNewTab({+ type: "gql-request",+ request: cloneDeep(request) as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext: {+ originLocation: "user-collection",+ folderPath: folderPath!,+ requestIndex: parseInt(requestIndex),+ requestRefID: request._ref_id ?? request.id,+ },+ inheritedProperties: cascadeParentCollectionForProperties(+ folderPath,+ "rest"+ ),+ })} else {- // If not, open the request in a new tabtabs.createNewTab({type: "request",- request: cloneDeep(request),+ request: cloneDeep(request) as HoppRESTRequest,isDirty: false,saveContext: {originLocation: "user-collection",@@ -2531,12 +2818,82 @@ const selectResponse = (payload: {folderPath: stringrequestIndex: stringresponseName: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequestresponseID: string}) => {const { folderPath, requestIndex, responseName, request, responseID } =payload+ // GQL examples have their own tab document type (`gql-example-response`)+ // backed by a GQL-shaped response payload; route there instead of the REST+ // `example-response` path which renders REST-only components.+ if (isGQLRequest(request)) {+ const gqlResponse = request.responses[responseName]+ if (!gqlResponse) return++ if (collectionsType.value.type === "my-collections") {+ const possibleTab = tabs.getTabRefWithSaveContext({+ originLocation: "user-collection",+ requestIndex: parseInt(requestIndex),+ folderPath: folderPath!,+ exampleID: responseID,+ })++ if (possibleTab) {+ tabs.setActiveTab(possibleTab.value.id)+ } else {+ tabs.createNewTab({+ response: {+ ...cloneDeep(gqlResponse),+ name: responseName,+ },+ isDirty: false,+ type: "gql-example-response",+ saveContext: {+ originLocation: "user-collection",+ folderPath: folderPath!,+ requestIndex: parseInt(requestIndex),+ exampleID: responseID,+ },+ inheritedProperties: cascadeParentCollectionForProperties(+ folderPath,+ "rest"+ ),+ })+ }+ } else {+ const possibleTab = tabs.getTabRefWithSaveContext({+ originLocation: "team-collection",+ requestID: requestIndex,+ exampleID: responseID,+ })++ if (possibleTab) {+ tabs.setActiveTab(possibleTab.value.id)+ } else {+ tabs.createNewTab({+ response: {+ ...cloneDeep(gqlResponse),+ name: responseName,+ },+ isDirty: false,+ type: "gql-example-response",+ saveContext: {+ originLocation: "team-collection",+ requestID: requestIndex,+ collectionID: folderPath,+ exampleID: responseID,+ },+ inheritedProperties:+ teamCollectionService.cascadeParentCollectionForProperties(+ folderPath+ ),+ })+ }+ }+ return+ }+const response = request.responses[responseName]if (collectionsType.value.type === "my-collections") {@@ -2644,8 +3001,11 @@ const dropRequest = async (payload: {requestRefID,})- // If there is a tab attached to this request, change save its save context- if (possibleTab && possibleTab.value.document.type === "request") {+ if (+ possibleTab &&+ (possibleTab.value.document.type === "request" ||+ possibleTab.value.document.type === "gql-request")+ ) {possibleTab.value.document.saveContext = {originLocation: "user-collection",folderPath: destinationCollectionIndex,@@ -2701,7 +3061,11 @@ const dropRequest = async (payload: {requestID: requestIndex,})- if (possibleTab && possibleTab.value.document.type === "request") {+ if (+ possibleTab &&+ (possibleTab.value.document.type === "request" ||+ possibleTab.value.document.type === "gql-request")+ ) {possibleTab.value.document.saveContext = {originLocation: "team-collection",requestID: requestIndex,@@ -3352,7 +3716,11 @@ const doExportOpenAPI = async (format: "json" | "yaml") => {}}-const shareRequest = ({ request }: { request: HoppRESTRequest }) => {+const shareRequest = ({+ request,+}: {+ request: HoppRESTRequest | HoppGQLRequest+}) => {if (currentUser.value) {// opens the share request modalinvokeAction("share.request", {@@ -3836,6 +4204,7 @@ const getErrorMessage = (err: GQLError<string>) => {case "team_req/requests_not_from_same_collection":return t("request.different_collection")case "team/team_collections_have_different_parents":+ case "team_coll/not_same_parent":return t("collection.different_parent")default:return t("error.something_went_wrong")diff --git a/packages/hoppscotch-common/src/components/documentation/Content.vue b/packages/hoppscotch-common/src/components/documentation/Content.vueindex 7361eeb05..677d8e1ff 100644--- a/packages/hoppscotch-common/src/components/documentation/Content.vue+++ b/packages/hoppscotch-common/src/components/documentation/Content.vue@@ -51,9 +51,9 @@/><CollectionsDocumentationRequestPreviewv-if="item.type === 'request'"- :request="item.item as HoppRESTRequest"+ :request="item.item as DocRequest":documentation-description="- (item.item as HoppRESTRequest).description || ''+ getRequestDescription(item.item as DocRequest)":collection-i-d="collectionData.id":inherited-properties="getInheritedProperties(item)"@@ -69,17 +69,26 @@<script setup lang="ts">import { PropType, ref, onMounted } from "vue"-import { Environment, HoppCollection, HoppRESTRequest } from "@hoppscotch/data"+import {+ Environment,+ HoppCollection,+ HoppGQLRequest,+ HoppRESTRequest,+} from "@hoppscotch/data"import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"import { useRouter, useRoute } from "vue-router"+type DocRequest = HoppRESTRequest | HoppGQLRequest+type DocumentationItem = {id: stringtype: "folder" | "request"- item: HoppCollection | HoppRESTRequest+ item: HoppCollection | DocRequestinheritedProperties: HoppInheritedProperty}+const getRequestDescription = (req: DocRequest): string => req.description || ""+const props = defineProps({collectionData: {type: Object as PropType<HoppCollection>,diff --git a/packages/hoppscotch-common/src/components/embeds/GQLIndex.vue b/packages/hoppscotch-common/src/components/embeds/GQLIndex.vuenew file mode 100644index 000000000..8624f539a--- /dev/null+++ b/packages/hoppscotch-common/src/components/embeds/GQLIndex.vue@@ -0,0 +1,126 @@+<template>+ <component+ :is="platform.ui?.additionalEmbedsComponent"+ v-if="showCustomEmbedsView"+ v-bind="props"+ />++ <AppPaneLayout v-else layout-id="embed-primary" :is-embed="true">+ <template #primary>+ <EmbedsHeader :shared-request-u-r-l="sharedRequestURL" />+ <div class="flex flex-col flex-1">+ <EmbedsGQLRequest+ :model-tab="modelTab"+ :shared-request-u-r-l="sharedRequestURL"+ />+ <div class="flex flex-col flex-1">+ <!-- In-tab Run/Stop stays enabled — it runs the operation at the+ cursor, which the top button (first operation only) can't -->+ <GqlRequestOptions+ v-model="tab.document.request"+ v-model:option-tab="selectedOptionTab"+ :tab-id="tab.id"+ :url="tab.document.request.url"+ :response="tab.document.response"+ :properties="properties"+ :envs="scopedEnvs"+ @update:response="onResponseUpdate"+ />+ </div>+ </div>+ </template>+ <template #secondary>+ <GqlResponse+ v-model:document="tab.document"+ :tab-id="tab.id"+ :response="tab.document.response ?? null"+ />+ </template>+ </AppPaneLayout>+</template>++<script lang="ts" setup>+import { computed, onBeforeUnmount, ref, useModel } from "vue"+import { useService } from "dioc/vue"+import { HoppTab } from "~/services/tab"+import { HoppGQLRequestDocument } from "~/helpers/tab/document"+import { platform } from "~/platform"+import type { GQLOptionTabs } from "~/components/graphql/RequestOptions.vue"+import {+ GQLTabConnectionService,+ type GQLResponseEvent,+} from "~/services/gql-tab-connection.service"+import type { AggregateEnvironment } from "~/newstore/environments"++// Mirrors components/embeds/index.vue but mounts the GraphQL component+// tree — GqlRequestOptions for the four-tab editor, gql/Response for the+// response/subscription log. Stays separate from the REST shell so neither+// tree carries protocol-specific branching internally.+const props = defineProps<{+ modelTab: HoppTab<HoppGQLRequestDocument>+ properties: string[]+ sharedRequestID: string+}>()++const tab = useModel(props, "modelTab")++// Explicitly EMPTY env scope — the viewer's stored environments must not+// surface anywhere in the embed (GQL requests carry no request variables)+const scopedEnvs: AggregateEnvironment[] = []++const gqlTabConn = useService(GQLTabConnectionService)++// Close the schema-poll socket and any live subscription when the embed+// iframe is unmounted (host navigation, route change). Without this the+// connection-service keeps the tab context — including a potentially open+// WebSocket — alive for the rest of the page session.+onBeforeUnmount(() => {+ gqlTabConn.cleanupTab(tab.value.id)+})++// Tracks which sub-tab (Query / Variables / Headers / Authorization) is+// currently visible. Owned locally by the embed shell so the tab strip is+// interactive without needing the share-er to pre-select one.+//+// `properties` is untrusted shortcode data, so initialise from the first+// *known* tab it actually lists (in render order) rather than casting+// `properties[0]` — a stray/unknown entry would otherwise select a tab that+// `GqlRequestOptions` never renders, leaving a blank editor. An empty+// `properties` array means "show all" there, so fall back to `query`.+const GQL_OPTION_TABS: GQLOptionTabs[] = [+ "query",+ "variables",+ "headers",+ "authorization",+]+const selectedOptionTab = ref<GQLOptionTabs>(+ GQL_OPTION_TABS.find((tab) => props.properties.includes(tab)) ?? "query"+)++// `GqlRequestOptions` watches the per-tab message stream from the connection+// service and re-emits each event as `update:response`. The embed owns the+// document, so we fold these events back into `tab.document.response` —+// matching the workspace flow where the parent (http/RequestOptions or its+// pages parent) does the same.+const onResponseUpdate = (events: GQLResponseEvent[]) => {+ tab.value.document.response = events+}++const shortcodeBaseURL = computed(+ () => import.meta.env.VITE_SHORTCODE_BASE_URL ?? "https://hopp.sh"+)++const sharedRequestURL = computed(() => {+ return `${shortcodeBaseURL.value}/r/${props.sharedRequestID}`+})++const showCustomEmbedsView = computed(() => {+ const { organization, ui } = platform++ return (+ organization &&+ !organization.isDefaultCloudInstance &&+ ui?.additionalEmbedsComponent+ )+})+</script>diff --git a/packages/hoppscotch-common/src/components/embeds/GQLRequest.vue b/packages/hoppscotch-common/src/components/embeds/GQLRequest.vuenew file mode 100644index 000000000..5452ad02e--- /dev/null+++ b/packages/hoppscotch-common/src/components/embeds/GQLRequest.vue@@ -0,0 +1,127 @@+<template>+ <div class="sticky top-0 z-10">+ <div+ class="flex-none flex-shrink-0 p-4 bg-primary sm:flex sm:flex-shrink-0 sm:space-x-2"+ >+ <div+ class="flex flex-1 overflow-hidden border divide-x rounded text-secondaryDark divide-divider min-w-[12rem] overflow-x-auto border-divider"+ >+ <span+ class="flex items-center justify-center px-4 py-2 font-semibold transition rounded-l text-accent"+ >+ <component :is="IconGraphql" class="h-4 w-4" />+ </span>+ <div+ class="flex items-center flex-1 flex-shrink-0 min-w-0 truncate rounded-r"+ >+ <!-- Empty env scope — viewer envs must not resolve here -->+ <SmartEnvInput+ v-model="tab.document.request.url"+ :envs="[]"+ :readonly="true"+ />+ </div>+ </div>+ <div class="flex mt-2 space-x-2 sm:mt-0">+ <HoppButtonPrimary+ id="run"+ :title="`${t('request.run')} <kbd>${getSpecialKey()}</kbd><kbd>↩</kbd>`"+ :label="`${+ subscriptionState === 'SUBSCRIBED'+ ? t('request.stop')+ : t('request.run')+ }`"+ class="flex-1 min-w-20"+ outline+ @click="subscriptionState === 'SUBSCRIBED' ? stopQuery() : runQuery()"+ />+ <div class="flex">+ <HoppButtonSecondary+ :title="`${t(+ 'request.save'+ )} <kbd>${getSpecialKey()}</kbd><kbd>S</kbd>`"+ :label="t('request.save')"+ filled+ :icon="IconSave"+ class="flex-1 rounded"+ blank+ outline+ :to="sharedRequestURL"+ />+ </div>+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"+import IconSave from "~icons/lucide/save"+import IconGraphql from "~icons/hopp/graphql"+import { computed, useModel } from "vue"+import { useI18n } from "~/composables/i18n"+import { useService } from "dioc/vue"+import { GQLTabConnectionService } from "~/services/gql-tab-connection.service"+import { HoppTab } from "~/services/tab"+import { HoppGQLRequestDocument } from "~/helpers/tab/document"+import { parse } from "graphql"+import type { OperationDefinitionNode } from "graphql"++const t = useI18n()++const props = defineProps<{+ modelTab: HoppTab<HoppGQLRequestDocument>+ sharedRequestURL: string+}>()++const tab = useModel(props, "modelTab")++const gqlTabConn = useService(GQLTabConnectionService)++// Reactive subscription state for the live tab — flips the Run/Stop label+// based on whether the user has an active subscription open.+const subscriptionState = computed(+ () => gqlTabConn.getTabSubscriptionState(tab.value.id).value+)++// Pull the first operation definition out of the query so a Run click+// matches the workspace behaviour (which always knows what operation to+// run). The shortcode's stored query is canonical, so this is a parse on+// every Run rather than a per-keystroke parse.+const firstOperation = (): OperationDefinitionNode | null => {+ try {+ const ast = parse(tab.value.document.request.query)+ return (+ (ast.definitions.find((d) => d.kind === "OperationDefinition") as+ OperationDefinitionNode | undefined) ?? null+ )+ } catch {+ return null+ }+}++const runQuery = async () => {+ const op = firstOperation()+ try {+ await gqlTabConn.runTabGQLOperation(tab.value.id, {+ name: tab.value.document.request.name,+ url: tab.value.document.request.url,+ request: tab.value.document.request,+ inheritedHeaders: [],+ query: tab.value.document.request.query,+ variables: tab.value.document.request.variables,+ operationName: op?.name?.value,+ operationType: op?.operation ?? "query",+ // Viewer envs must not resolve into a shared request's execution+ isolatedEnvs: true,+ })+ } catch (_e) {+ // Connection service routes the error onto the response stream; no+ // additional UI work needed here.+ }+}++const stopQuery = () => {+ gqlTabConn.unsubscribeTab(tab.value.id)+}+</script>diff --git a/packages/hoppscotch-common/src/components/embeds/Request.vue b/packages/hoppscotch-common/src/components/embeds/Request.vueindex dea18bb7b..24cf2a1cc 100644--- a/packages/hoppscotch-common/src/components/embeds/Request.vue+++ b/packages/hoppscotch-common/src/components/embeds/Request.vue@@ -55,7 +55,7 @@import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"import IconSave from "~icons/lucide/save"import { Ref } from "vue"-import { computed, useModel } from "vue"+import { computed, onBeforeUnmount, useModel } from "vue"import { ref } from "vue"import { useI18n } from "~/composables/i18n"import { useToast } from "~/composables/toast"@@ -64,7 +64,7 @@ import { useStreamSubscriber } from "~/composables/stream"import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"import { runRESTRequest$ } from "~/helpers/RequestRunner"import { HoppTab } from "~/services/tab"-import { HoppRequestDocument } from "~/helpers/rest/document"+import { HoppRequestDocument } from "~/helpers/tab/document"import { transformRequestVariablesToAggregateEnv } from "~/helpers/utils/environments"const toast = useToast()@@ -99,10 +99,16 @@ const newSendRequest = async () => {loading.value = true- const [cancel, streamPromise] = runRESTRequest$(tab)+ // Viewer envs must not resolve into a shared request's execution+ const [cancel, streamPromise] = runRESTRequest$(tab, { isolatedEnvs: true })+ // Store the cancel handle synchronously — `runRESTRequest$` returns it+ // immediately, before the stream resolves. If we waited until after the+ // `await` below, an unmount during that window would leave `onBeforeUnmount`+ // with a null handle and leak the in-flight request.+ requestCancelFunc.value = cancel+const streamResult = await streamPromise- requestCancelFunc.value = cancelif (E.isRight(streamResult)) {subscribeToStream(streamResult.right,@@ -186,4 +192,12 @@ const cancelRequest = () => {updateRESTResponse(null)}++// Cancel any in-flight REST request when the embed iframe is destroyed+// (host navigation, SPA route change). Otherwise the runner stays+// subscribed to the response stream after the component is gone — small+// memory leak that grows if a user clicks between several embed links.+onBeforeUnmount(() => {+ requestCancelFunc.value?.()+})</script>diff --git a/packages/hoppscotch-common/src/components/embeds/index.vue b/packages/hoppscotch-common/src/components/embeds/index.vueindex f1460ab6a..230fe01e3 100644--- a/packages/hoppscotch-common/src/components/embeds/index.vue+++ b/packages/hoppscotch-common/src/components/embeds/index.vue@@ -14,11 +14,14 @@:shared-request-u-r-l="sharedRequestURL"/><div class="flex flex-col flex-1">+ <!-- Both scopes carry only the shared request's own variables —+ viewer envs never surface in the embed editors --><HttpRequestOptionsv-model="tab.document.request"v-model:option-tab="selectedOptionTab":properties="properties":envs="tabRequestVariables"+ :scoped-envs="tabRequestVariables"/></div></div>@@ -33,7 +36,7 @@import { computed, useModel } from "vue"import { ref } from "vue"import { HoppTab } from "~/services/tab"-import { HoppRequestDocument } from "~/helpers/rest/document"+import { HoppRequestDocument } from "~/helpers/tab/document"import { platform } from "~/platform"import { RESTOptionTabs } from "../http/RequestOptions.vue"import { transformRequestVariablesToAggregateEnv } from "~/helpers/utils/environments"diff --git a/packages/hoppscotch-common/src/components/environments/Add.vue b/packages/hoppscotch-common/src/components/environments/Add.vueindex 7f47f6d8b..bcdb49ca6 100644--- a/packages/hoppscotch-common/src/components/environments/Add.vue+++ b/packages/hoppscotch-common/src/components/environments/Add.vue@@ -85,14 +85,14 @@ import {updateEnvironment,} from "~/newstore/environments"import { CurrentValueService } from "~/services/current-environment-value.service"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { Scope } from "./Selector.vue"import { GlobalEnvironment } from "@hoppscotch/data"const t = useI18n()const toast = useToast()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const currentEnvironmentValueService = useService(CurrentValueService)const props = defineProps<{@@ -239,12 +239,18 @@ const addEnvironment = async () => {if (replaceWithVariable.value) {//replace the current tab endpoint with the variable name with << and >>const variableName = `<<${editingName.value}>>`- //replace the currenttab endpoint containing the value in the text with variablename- tabs.currentActiveTab.value.document.request.endpoint =- tabs.currentActiveTab.value.document.request.endpoint.replace(+ const doc = tabs.currentActiveTab.value.document+ if (doc.type === "request") {+ doc.request.endpoint = doc.request.endpoint.replace(editingValue.value,variableName)+ } else if (doc.type === "gql-request") {+ doc.request.url = doc.request.url.replace(+ editingValue.value,+ variableName+ )+ }}hideModal()diff --git a/packages/hoppscotch-common/src/components/environments/index.vue b/packages/hoppscotch-common/src/components/environments/index.vueindex 5f3604528..29de810d6 100644--- a/packages/hoppscotch-common/src/components/environments/index.vue+++ b/packages/hoppscotch-common/src/components/environments/index.vue@@ -165,33 +165,18 @@ const updateEnvironmentType = (newEnvironmentType: EnvironmentType) => {const workspace = workspaceService.currentWorkspace-// Switch to my environments if workspace is personal and to team environments if workspace is team-// also resets selected environment if workspace is personal and the previous selected environment was a team environment+// Switch to my environments if workspace is personal and to team+// environments if workspace is team. Resetting a stale team-env selection+// is handled by WorkspaceService.changeWorkspace — the single funnel every+// workspace switch goes through, mounted or not.watch(workspace,(newWorkspace) => {- const { type: newWorkspaceType } = newWorkspace-- if (newWorkspaceType === "personal") {+ if (newWorkspace.type === "personal") {switchToMyEnvironments()} else {updateSelectedTeam(newWorkspace)}-- const newTeamID =- newWorkspaceType === "team" ? newWorkspace.teamID : undefined-- // Set active environment to the `No environment` state- // if navigating away from a team workspace- if (- selectedEnvironmentIndex.value.type === "TEAM_ENV" &&- newTeamID &&- selectedEnvironmentIndex.value.teamID !== newTeamID- ) {- setSelectedEnvironmentIndex({- type: "NO_ENV_SELECTED",- })- }},{ immediate: true })diff --git a/packages/hoppscotch-common/src/components/gql/Argument.vue b/packages/hoppscotch-common/src/components/gql/Argument.vuenew file mode 100644index 000000000..e1f85abf9--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Argument.vue@@ -0,0 +1,103 @@+<template>+ <template v-if="inline">+ <span+ class="hopp-doc-explorer-argument inline-flex items-center gap-1 cursor-pointer hover:text-accent transition"+ tabindex="0"+ @click="handleClick"+ @keydown="handleKeydown"+ >+ <span class="hopp-doc-explorer-argument-name">{{ arg.name }}</span>+ <span class="text-secondaryLight">:</span>+ <GqlTypeLink :type="arg.type" />+ <GqlDefaultValue v-if="showDefaultValue !== false" :field="arg" />+ </span>+ </template>++ <div+ v-else+ class="group flex items-center gap-1 px-4 py-2 transition hover:bg-primaryLight cursor-pointer"+ :class="{ 'line-through opacity-60': arg.deprecationReason }"+ tabindex="0"+ @click="handleClick"+ @keydown="handleKeydown"+ >+ <div class="flex flex-1 min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1">+ <button+ v-if="showAddButton"+ class="flex items-center justify-center rounded transition hover:text-accent"+ :class="{+ 'text-accent': queryBuilder.isArgumentInOperation(arg),+ 'text-secondaryLight': !queryBuilder.isArgumentInOperation(arg),+ }"+ type="button"+ @click.stop="insertQuery"+ >+ <icon-lucide-plus-circle+ v-if="!queryBuilder.isArgumentInOperation(arg)"+ class="svg-icons"+ />+ <icon-lucide-circle-check v-else class="svg-icons" />+ </button>+ <span class="hopp-doc-explorer-argument-name text-sm font-medium">+ {{ arg.name }}+ </span>+ <span class="text-secondaryLight">:</span>+ <GqlTypeLink :type="arg.type" />+ <GqlDefaultValue v-if="showDefaultValue !== false" :field="arg" />+ </div>+ </div>+</template>++<script setup lang="ts">+import { onBeforeUnmount } from "vue"+import type { GraphQLArgument } from "graphql"+import { debounce } from "lodash-es"+import { useExplorer } from "~/helpers/graphql/explorer"+import { useService } from "dioc/vue"+import { GQLQueryBuilderService } from "~/services/gql-query-builder.service"++const queryBuilder = useService(GQLQueryBuilderService)++interface ArgumentProps {+ arg: GraphQLArgument+ showDefaultValue?: boolean+ inline?: boolean+ showAddButton?: boolean+}++const props = withDefaults(defineProps<ArgumentProps>(), {+ showDefaultValue: false,+ inline: false,+ showAddButton: false,+})++const { push } = useExplorer()++const handleClick = () => {+ push({ name: props.arg.name, def: props.arg })+}++// Keyboard mirror of the click for the focusable span/div. The target guard+// matters because keydown bubbles — only act when the container itself is+// focused, so a focused child's Enter/Space (the add button, type links) isn't+// hijacked. No `role="button"`: these wrap interactive children, which it+// disallows.+const handleKeydown = (e: KeyboardEvent) => {+ if (e.target !== e.currentTarget) return+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault()+ handleClick()+ }+}++const insertQuery = debounce(() => {+ queryBuilder.handleAddArgument(props.arg)+}, 50)++// Cancel any pending debounced insert on unmount (docs explorer closing /+// navigation) so it can't write to the long-lived query-builder service after+// the component is gone.+onBeforeUnmount(() => {+ insertQuery.cancel()+})+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Arguments.vue b/packages/hoppscotch-common/src/components/gql/Arguments.vuenew file mode 100644index 000000000..a3754033d--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Arguments.vue@@ -0,0 +1,32 @@+<template>+ <template v-if="'args' in field">+ <GqlExplorerSection+ v-if="field.args.length > 0"+ :title="t('graphql.arguments')"+ >+ <GqlArgument+ v-for="arg in field.args"+ :key="arg.name"+ :arg="arg"+ :show-add-button="!readonly"+ />+ </GqlExplorerSection>+ </template>+</template>++<script setup lang="ts">+import { GraphQLField } from "graphql"+import { useI18n } from "~/composables/i18n"++const t = useI18n()++withDefaults(+ defineProps<{+ field: GraphQLField<any, any>+ readonly?: boolean+ }>(),+ {+ readonly: false,+ }+)+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Authorization.vue b/packages/hoppscotch-common/src/components/gql/Authorization.vuenew file mode 100644index 000000000..e6f997180--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Authorization.vue@@ -0,0 +1,337 @@+<template>+ <div class="flex flex-1 flex-col">+ <div+ class="sticky top-sidebarPrimaryStickyFold z-10 flex items-center justify-between border-y border-dividerLight bg-primary pl-4"+ >+ <span class="flex items-center">+ <label class="truncate font-semibold text-secondaryLight">+ {{ t("authorization.type") }}+ </label>+ <tippy+ interactive+ trigger="click"+ theme="popover"+ :on-shown="() => tippyActions.focus()"+ >+ <HoppSmartSelectWrapper>+ <HoppButtonSecondary+ class="ml-2 rounded-none pr-8"+ :label="authName"+ />+ </HoppSmartSelectWrapper>+ <template #content="{ hide }">+ <div+ ref="tippyActions"+ class="flex flex-col focus:outline-none"+ tabindex="0"+ @keyup.escape="hide()"+ >+ <HoppSmartItem+ v-for="item in authTypes"+ :key="item.key"+ :label="item.label"+ :icon="item.key === authType ? IconCircleDot : IconCircle"+ :active="item.key === authType"+ @click="+ () => {+ item.handler+ ? item.handler()+ : (auth = { ...auth, authType: item.key } as HoppGQLAuth)+ hide()+ }+ "+ />+ </div>+ </template>+ </tippy>+ </span>+ <div class="flex">+ <HoppSmartCheckbox+ :on="authActive"+ class="px-2"+ @change="authActive = !authActive"+ >+ {{ t("state.enabled") }}+ </HoppSmartCheckbox>+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ to="https://docs.hoppscotch.io/documentation/features/authorization"+ blank+ :title="t('app.wiki')"+ :icon="IconHelpCircle"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.clear')"+ :icon="IconTrash2"+ @click="clearContent"+ />+ </div>+ </div>+ <HoppSmartPlaceholder+ v-if="auth.authType === 'none'"+ :src="`/images/states/${colorMode.value}/login.svg`"+ :alt="`${t('empty.authorization')}`"+ :text="t('empty.authorization')"+ >+ <template #body>+ <HoppButtonSecondary+ outline+ :label="t('app.documentation')"+ to="https://docs.hoppscotch.io/documentation/features/authorization"+ blank+ :icon="IconExternalLink"+ reverse+ />+ </template>+ </HoppSmartPlaceholder>+ <div v-else class="flex flex-1 border-b border-dividerLight">+ <div class="w-2/3 border-r border-dividerLight">+ <div v-if="auth.authType === 'basic'">+ <div class="flex flex-1 border-b border-dividerLight">+ <SmartEnvInput+ v-model="auth.username"+ :auto-complete-env="true"+ :envs="envs"+ :placeholder="t('authorization.username')"+ />+ </div>+ <div class="flex flex-1 border-b border-dividerLight">+ <SmartEnvInput+ v-model="auth.password"+ :auto-complete-env="true"+ :envs="envs"+ :placeholder="t('authorization.password')"+ />+ </div>+ </div>+ <div v-if="auth.authType === 'inherit'" class="p-4">+ <span v-if="inheritedProperties?.auth">+ {{+ t("authorization.inherited_from", {+ auth: getAuthName(+ (inheritedProperties.auth.inheritedAuth as HoppGQLAuth)+ .authType+ ),+ collection: inheritedProperties?.auth.parentName,+ })+ }}+ </span>+ <span v-else>+ {{ t("authorization.save_to_inherit") }}+ </span>+ </div>+ <div v-if="auth.authType === 'bearer'">+ <div class="flex flex-1 border-b border-dividerLight">+ <SmartEnvInput+ v-model="auth.token"+ :auto-complete-env="true"+ :envs="envs"+ placeholder="Token"+ />+ </div>+ </div>+ <div v-if="auth.authType === 'oauth-2'">+ <div class="flex flex-1 border-b border-dividerLight">+ <SmartEnvInput+ v-model="auth.grantTypeInfo.token"+ :auto-complete-env="true"+ :envs="envs"+ placeholder="Token"+ />+ </div>+ <!-- source names the HOSTING PAGE, not the protocol: "REST" routes+ the generated token + post-redirect back to the unified+ workspace ("/", WorkspaceTabsService — where this GQL tab+ lives); "GraphQL" targets the legacy /graphql page -->+ <HttpAuthorizationOAuth2 v-model="auth" source="REST" :envs="envs" />+ </div>+ <div v-if="auth.authType === 'api-key'">+ <HttpAuthorizationApiKey v-model="auth" :envs="envs" />+ </div>+ <div v-if="auth.authType === 'aws-signature'">+ <HttpAuthorizationAWSSign v-model="auth" :envs="envs" />+ </div>+ </div>+ <div+ class="z-[9] sticky top-upperTertiaryStickyFold h-full min-w-[12rem] max-w-1/3 flex-shrink-0 overflow-auto overflow-x-auto bg-primary p-4"+ >+ <div class="pb-2 text-secondaryLight">+ {{ t("helpers.authorization") }}+ </div>+ <HoppSmartAnchor+ class="link"+ :label="t('authorization.learn')"+ :icon="IconExternalLink"+ to="https://docs.hoppscotch.io/documentation/features/authorization"+ blank+ reverse+ />+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { useI18n } from "@composables/i18n"+import { pluckRef } from "@composables/ref"+import { useColorMode } from "@composables/theming"+import {+ HoppGQLAuth,+ HoppGQLAuthOAuth2,+ HoppGQLAuthAWSSignature,+} from "@hoppscotch/data"+import { useVModel } from "@vueuse/core"+import { computed, ref } from "vue"++import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"+import { AggregateEnvironment } from "~/newstore/environments"++import IconCircle from "~icons/lucide/circle"+import IconCircleDot from "~icons/lucide/circle-dot"+import IconExternalLink from "~icons/lucide/external-link"+import IconHelpCircle from "~icons/lucide/help-circle"+import IconTrash2 from "~icons/lucide/trash-2"++import { getDefaultAuthCodeOauthFlowParams } from "~/services/oauth/flows/authCode"++type AuthType = {+ key: HoppGQLAuth["authType"]+ label: string+ handler?: () => void+}++const t = useI18n()++const colorMode = useColorMode()++const props = defineProps<{+ modelValue: HoppGQLAuth+ inheritedProperties?: HoppInheritedProperty+ // Embed-only env scope; omit to use the global aggregate envs+ envs?: AggregateEnvironment[]+}>()++const emit = defineEmits<{+ (e: "update:modelValue", value: HoppGQLAuth): void+}>()++const auth = useVModel(props, "modelValue", emit)++const selectOAuth2AuthType = () => {+ const defaultGrantTypeInfo: HoppGQLAuthOAuth2["grantTypeInfo"] = {+ ...getDefaultAuthCodeOauthFlowParams(),+ grantType: "AUTHORIZATION_CODE",+ token: "",+ }++ // @ts-expect-error - the existing grantTypeInfo might be in the auth object, typescript doesnt know that+ const existingGrantTypeInfo = auth.value.grantTypeInfo as+ HoppGQLAuthOAuth2["grantTypeInfo"] | undefined++ const grantTypeInfo = existingGrantTypeInfo+ ? existingGrantTypeInfo+ : defaultGrantTypeInfo++ auth.value = {+ ...auth.value,+ authType: "oauth-2",+ addTo: "HEADERS",+ grantTypeInfo: grantTypeInfo,+ }+}++const selectAPIKeyAuthType = () => {+ auth.value = {+ ...auth.value,+ authType: "api-key",+ addTo: "HEADERS",+ } as HoppGQLAuth+}++const selectAWSSignatureAuthType = () => {+ const {+ accessKey = "",+ secretKey = "",+ region = "",+ serviceName = "",+ addTo = "HEADERS",+ } = auth.value as HoppGQLAuthAWSSignature++ auth.value = {+ ...auth.value,+ authType: "aws-signature",+ addTo,+ accessKey,+ secretKey,+ region,+ serviceName,+ }+}++const authTypes: AuthType[] = [+ {+ key: "inherit",+ label: "Inherit",+ },+ {+ key: "none",+ label: "None",+ },+ {+ key: "basic",+ label: "Basic Auth",+ },+ {+ key: "bearer",+ label: "Bearer",+ },+ {+ key: "oauth-2",+ label: "OAuth 2.0",+ handler: selectOAuth2AuthType,+ },+ {+ key: "api-key",+ label: "API Key",+ handler: selectAPIKeyAuthType,+ },+ {+ key: "aws-signature",+ label: "AWS Signature",+ handler: selectAWSSignatureAuthType,+ },+]++const AUTH_KEY_NAME: Record<HoppGQLAuth["authType"], string> = {+ basic: "Basic Auth",+ bearer: "Bearer",+ "oauth-2": "OAuth 2.0",+ "api-key": "API key",+ none: "None",+ inherit: "Inherit",+ "aws-signature": "AWS Signature",+}++const authType = pluckRef(auth, "authType")++const authName = computed(() =>+ AUTH_KEY_NAME[authType.value] ? AUTH_KEY_NAME[authType.value] : "None"+)++const getAuthName = (type: HoppGQLAuth["authType"] | undefined) => {+ if (!type) return "None"+ return AUTH_KEY_NAME[type] ? AUTH_KEY_NAME[type] : "None"+}++const authActive = pluckRef(auth, "authActive")++const clearContent = () => {+ auth.value = {+ authType: "inherit",+ authActive: true,+ }+}++const tippyActions = ref<any | null>(null)+</script>diff --git a/packages/hoppscotch-common/src/components/gql/DefaultValue.vue b/packages/hoppscotch-common/src/components/gql/DefaultValue.vuenew file mode 100644index 000000000..eb06d8594--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/DefaultValue.vue@@ -0,0 +1,34 @@+<template>+ <template v-if="defaultValueAst">+ <span class="text-secondaryLight"> = </span>+ <span class="hopp-doc-explorer-default-value">+ {{ printDefault(defaultValueAst) }}+ </span>+ </template>+</template>++<script setup lang="ts">+import { astFromValue, print } from "graphql"+import type { ValueNode } from "graphql"+import { ExplorerFieldDef } from "~/helpers/graphql/explorer"+import { computed } from "vue"++const props = defineProps<{+ field: ExplorerFieldDef+}>()++const printDefault = (ast?: ValueNode | null): string => {+ if (!ast) return ""+ return print(ast)+}++const defaultValueAst = computed(() => {+ if (+ !("defaultValue" in props.field) ||+ props.field.defaultValue === undefined+ ) {+ return null+ }+ return astFromValue(props.field.defaultValue, props.field.type)+})+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Directives.vue b/packages/hoppscotch-common/src/components/gql/Directives.vuenew file mode 100644index 000000000..52363fa5f--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Directives.vue@@ -0,0 +1,24 @@+<template>+ <GqlExplorerSection v-if="directives.length > 0" title="Directives">+ <div+ v-for="directive in directives"+ :key="directive.name.value"+ class="px-4 py-2"+ >+ <span class="text-sm font-medium text-secondaryDark">+ @{{ directive?.name?.value }}+ </span>+ </div>+ </GqlExplorerSection>+</template>++<script setup lang="ts">+import { ExplorerFieldDef } from "~/helpers/graphql/explorer"+import { computed } from "vue"++const props = defineProps<{+ field: ExplorerFieldDef+}>()++const directives = computed(() => props.field.astNode?.directives || [])+</script>diff --git a/packages/hoppscotch-common/src/components/gql/DocExplorer.vue b/packages/hoppscotch-common/src/components/gql/DocExplorer.vuenew file mode 100644index 000000000..26f2e1148--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/DocExplorer.vue@@ -0,0 +1,110 @@+<template>+ <section+ v-if="schema"+ :key="activeTabId"+ class="hopp-doc-explorer flex flex-col h-full"+ aria-label="Documentation Explorer"+ >+ <div class="sticky top-0 z-10 bg-primary border-b border-dividerLight">+ <GqlSchemaSearch />+ <nav+ v-if="navStack.length > 1"+ class="flex items-center gap-1 overflow-x-auto whitespace-nowrap px-4 py-2 text-tiny"+ aria-label="Schema explorer breadcrumb"+ >+ <template v-for="(item, index) in navStack" :key="index">+ <button+ v-if="index < navStack.length - 1"+ type="button"+ class="rounded px-1.5 py-0.5 text-secondaryLight transition hover:bg-primaryLight hover:text-secondaryDark"+ @click="navigateToIndex(index)"+ >+ {{ item.name }}+ </button>+ <span v-else class="rounded px-1.5 py-0.5 font-semibold text-accent">+ {{ item.name }}+ </span>+ <icon-lucide-chevron-right+ v-if="index < navStack.length - 1"+ class="svg-icons text-secondaryLight flex-shrink-0"+ />+ </template>+ </nav>+ </div>++ <div class="hopp-doc-explorer-content flex flex-col flex-1 overflow-y-auto">+ <template v-if="navStack.length === 1">+ <GqlSchemaDocumentation :schema="schema" />+ </template>+ <template v-else-if="isType(currentNavItem.def)">+ <div class="px-4 py-3 bg-primary sticky top-0 z-[6]">+ <h2+ class="text-lg font-semibold text-secondaryDark break-words flex items-center gap-2"+ >+ <icon-lucide-box class="svg-icons text-accent flex-shrink-0" />+ {{ currentNavItem.name }}+ </h2>+ </div>+ <GqlTypeDocumentation+ :type="currentNavItem.def"+ :readonly="currentNavItem.readonly"+ />+ </template>+ <template v-else-if="currentNavItem.def">+ <GqlFieldDocumentation+ :field="currentNavItem.def"+ :readonly="currentNavItem.readonly"+ />+ </template>+ </div>+ </section>++ <HoppSmartPlaceholder+ v-else+ :src="`/images/states/${colorMode.value}/pack.svg`"+ :alt="t('empty.documentation')"+ :text="t('empty.documentation')"+ >+ </HoppSmartPlaceholder>+</template>++<script setup lang="ts">+import { isType } from "graphql"+import { useExplorer } from "~/helpers/graphql/explorer"+import { useColorMode } from "~/composables/theming"+import { useI18n } from "~/composables/i18n"+import { useService } from "dioc/vue"+import { GQLTabConnectionService } from "~/services/gql-tab-connection.service"++const colorMode = useColorMode()+const t = useI18n()++const gqlTabConn = useService(GQLTabConnectionService)++const schema = gqlTabConn.activeTabSchema++// Key the section on the active tab ID so the entire subtree+// (SchemaDocumentation, SchemaSearch, etc.) is recreated on tab switch.+// This is necessary because child components store schema-derived values+// in non-reactive local variables at setup time.+const activeTabId = gqlTabConn.activeGQLTabId++const { navStack, currentNavItem, navigateToIndex } = useExplorer()+</script>++<style lang="scss">+.hopp-doc-explorer-field-name {+ color: var(--editor-name-color);+}+.hopp-doc-explorer-type-name {+ color: var(--editor-type-color);+ @apply text-sm font-normal transition hover:text-accent;+}+.hopp-doc-explorer-argument-name {+ color: var(--editor-keyword-color);+}+.hopp-doc-explorer-default-value {+ color: var(--editor-string-color);+ @apply text-sm;+}+</style>diff --git a/packages/hoppscotch-common/src/components/gql/EnumValues.vue b/packages/hoppscotch-common/src/components/gql/EnumValues.vuenew file mode 100644index 000000000..b2fdc6186--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/EnumValues.vue@@ -0,0 +1,95 @@+<template>+ <template v-if="isEnumType(type)">+ <GqlExplorerSection v-if="enumValues.values.length > 0" title="Enum Values">+ <div+ v-for="value in enumValues.values"+ :key="value.name"+ class="px-4 py-2"+ >+ <div class="text-sm font-medium text-secondaryDark">+ {{ value.name }}+ </div>+ <AppMarkdown+ v-if="value.description"+ type="description"+ class="text-tiny text-secondary leading-snug mt-1"+ >+ {{ value.description }}+ </AppMarkdown>+ </div>+ </GqlExplorerSection>++ <template v-if="enumValues.deprecatedValues.length > 0">+ <GqlExplorerSection+ v-if="showDeprecated || enumValues.values.length === 0"+ title="Deprecated Enum Values"+ >+ <div+ v-for="value in enumValues.deprecatedValues"+ :key="value.name"+ class="px-4 py-2"+ >+ <div class="text-sm font-medium text-secondaryDark line-through">+ {{ value.name }}+ </div>+ <AppMarkdown+ v-if="value.deprecationReason"+ type="deprecation"+ class="text-tiny text-secondary leading-snug mt-1"+ >+ {{ value.deprecationReason }}+ </AppMarkdown>+ </div>+ </GqlExplorerSection>++ <button+ v-else+ type="button"+ class="text-tiny font-semibold uppercase tracking-wide text-accent hover:underline px-4 py-2 text-left"+ @click="handleShowDeprecated"+ >+ {{ t("graphql.show_depricated_values") }}+ </button>+ </template>+ </template>+</template>++<script setup lang="ts">+import { ref, computed } from "vue"+import type { GraphQLNamedType, GraphQLEnumValue } from "graphql"+import { isEnumType } from "graphql"+import { useI18n } from "~/composables/i18n"++const t = useI18n()++interface EnumValuesProps {+ type: GraphQLNamedType+}++const props = defineProps<EnumValuesProps>()++const showDeprecated = ref(false)++const handleShowDeprecated = () => {+ showDeprecated.value = true+}++const enumValues = computed(() => {+ if (!isEnumType(props.type)) {+ return { values: [], deprecatedValues: [] }+ }++ const values: GraphQLEnumValue[] = []+ const deprecatedValues: GraphQLEnumValue[] = []++ for (const value of props.type.getValues()) {+ if (value.deprecationReason) {+ deprecatedValues.push(value)+ } else {+ values.push(value)+ }+ }++ return { values, deprecatedValues }+})+</script>diff --git a/packages/hoppscotch-common/src/components/gql/ExplorerSection.vue b/packages/hoppscotch-common/src/components/gql/ExplorerSection.vuenew file mode 100644index 000000000..c7b5a511f--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/ExplorerSection.vue@@ -0,0 +1,24 @@+<template>+ <section class="flex flex-col">+ <div+ class="sticky top-0 z-[5] flex items-center justify-between bg-primary px-4 py-2"+ >+ <h3+ class="text-tiny font-semibold uppercase tracking-wide text-secondaryLight"+ >+ {{ title }}+ </h3>+ </div>+ <div class="hopp-doc-explorer-section-content">+ <slot />+ </div>+ </section>+</template>++<script setup lang="ts">+defineProps<{+ // Plain string, not a title union — call sites pass i18n output+ // (e.g. t("graphql.fields")), which only types as `string`+ title: string+}>()+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Field.vue b/packages/hoppscotch-common/src/components/gql/Field.vuenew file mode 100644index 000000000..89a2561b8--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Field.vue@@ -0,0 +1,78 @@+<template>+ <div+ class="group flex items-start gap-1 px-4 py-2 transition hover:bg-primaryLight cursor-pointer"+ tabindex="0"+ @click="handleClick"+ @keydown="handleKeydown"+ >+ <div+ class="flex flex-1 min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1"+ :class="{ 'line-through opacity-60': field.deprecationReason }"+ >+ <GqlFieldLink+ :field="field"+ :show-add-field="showAddField"+ :is-added="queryBuilder.isFieldInOperation(field)"+ @add-field="insertQuery"+ />+ <template v-if="args.length > 0">+ <span class="text-secondaryLight">(...)</span>+ </template>+ <span class="text-secondaryLight">:</span>+ <GqlTypeLink :type="field.type" />+ <GqlDefaultValue :field="field" />+ </div>++ <span+ v-if="field.deprecationReason"+ v-tippy="{ theme: 'tooltip' }"+ class="flex flex-shrink-0 items-center justify-center text-yellow-500 mt-0.5"+ :title="field.deprecationReason"+ >+ <icon-lucide-triangle-alert class="svg-icons" />+ </span>+ </div>+</template>++<script setup lang="ts">+import { computed } from "vue"+import { ExplorerFieldDef, useExplorer } from "~/helpers/graphql/explorer"+import { useService } from "dioc/vue"+import { GQLQueryBuilderService } from "~/services/gql-query-builder.service"++const props = withDefaults(+ defineProps<{+ field: ExplorerFieldDef+ showAddField: boolean+ }>(),+ {+ showAddField: true,+ }+)++const { push } = useExplorer()+const queryBuilder = useService(GQLQueryBuilderService)++const handleClick = () => {+ push({ name: props.field.name, def: props.field })+}++// Keyboard activation parity with the click handler (mirrors Argument.vue)+const handleKeydown = (e: KeyboardEvent) => {+ if (e.target !== e.currentTarget) return+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault()+ handleClick()+ }+}++const insertQuery = () => {+ queryBuilder.handleAddField(props.field)+}++const args = computed(() =>+ "args" in props.field+ ? props.field.args.filter((arg) => !arg.deprecationReason)+ : []+)+</script>diff --git a/packages/hoppscotch-common/src/components/gql/FieldDocumentation.vue b/packages/hoppscotch-common/src/components/gql/FieldDocumentation.vuenew file mode 100644index 000000000..be9387758--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/FieldDocumentation.vue@@ -0,0 +1,61 @@+<template>+ <div class="flex flex-col">+ <div class="px-4 py-3">+ <div class="flex flex-wrap items-center gap-x-2 gap-y-1">+ <span class="text-lg font-semibold text-secondaryDark">+ {{ field.name }}+ </span>+ <span class="text-secondaryLight">:</span>+ <GqlTypeLink :type="field.type" :is-heading="true" />+ </div>+ <AppMarkdown+ v-if="hasDescription"+ type="description"+ class="text-tiny text-secondary leading-snug mt-2"+ >+ {{ description }}+ </AppMarkdown>+ </div>++ <div v-if="deprecationReason" class="bg-yellow-500/10 px-4 py-2">+ <p+ class="text-tiny font-semibold uppercase tracking-wide text-yellow-600"+ >+ {{ t("graphql.deprecated") }}+ </p>+ <AppMarkdown type="deprecation" class="text-tiny text-secondary mt-1">+ {{ deprecationReason }}+ </AppMarkdown>+ </div>++ <GqlArguments :field="field" :readonly="readonly" />+ <GqlFields :type="resolvedType" :show-add-field="!readonly" />+ <GqlDirectives :field="field" />+ </div>+</template>++<script setup lang="ts">+import { GraphQLOutputType, getNamedType } from "graphql"+import { computed } from "vue"+import { useI18n } from "~/composables/i18n"++interface Field {+ name: string+ description: string | null+ deprecationReason: string+ type: GraphQLOutputType+}++const props = defineProps<{+ field: Field+ readonly?: boolean+}>()++const t = useI18n()++const hasDescription = computed(() => props.field.description !== null)+const description = computed(() => props.field.description)+const deprecationReason = computed(() => props.field.deprecationReason)++const resolvedType = computed(() => getNamedType(props.field.type))+</script>diff --git a/packages/hoppscotch-common/src/components/gql/FieldLink.vue b/packages/hoppscotch-common/src/components/gql/FieldLink.vuenew file mode 100644index 000000000..2d96250a6--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/FieldLink.vue@@ -0,0 +1,62 @@+<template>+ <span class="inline-flex items-center gap-1.5">+ <button+ v-if="showAddField"+ class="flex items-center justify-center rounded transition hover:text-accent"+ :class="{ 'text-accent': isAdded, 'text-secondaryLight': !isAdded }"+ type="button"+ @click.stop="addField"+ >+ <icon-lucide-plus-circle v-if="!isAdded" class="svg-icons" />+ <icon-lucide-circle-check v-else class="svg-icons" />+ </button>+ <span+ class="hopp-doc-explorer-field-name text-sm font-medium"+ @click="clickable && handleClick($event)"+ >+ {{ field.name }}+ </span>+ </span>+</template>++<script setup lang="ts">+import { onBeforeUnmount } from "vue"+import { type ExplorerFieldDef, useExplorer } from "~/helpers/graphql/explorer"+import { debounce } from "lodash-es"++const props = withDefaults(+ defineProps<{+ field: ExplorerFieldDef+ clickable?: boolean+ showAddField: boolean+ isAdded?: boolean+ }>(),+ {+ clickable: true,+ showAddField: true,+ isAdded: false,+ }+)++const emit = defineEmits<{+ (event: "add-field", field: ExplorerFieldDef): void+}>()++const addField = debounce(() => {+ emit("add-field", props.field)+}, 50)++// Cancel pending debounced inserts on unmount so they can't write to the+// long-lived query-builder service after the component is gone (mirrors+// Argument.vue)+onBeforeUnmount(() => {+ addField.cancel()+})++const { push } = useExplorer()++const handleClick = (event: MouseEvent) => {+ event.preventDefault()+ push({ name: props.field.name, def: props.field })+}+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Fields.vue b/packages/hoppscotch-common/src/components/gql/Fields.vuenew file mode 100644index 000000000..6d2bc425f--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Fields.vue@@ -0,0 +1,49 @@+<template>+ <GqlExplorerSection v-if="fields.length > 0" :title="t('graphql.fields')">+ <GqlField+ v-for="field in fields"+ :key="field.name"+ :field="field"+ :show-add-field="showAddField"+ />+ </GqlExplorerSection>+</template>++<script setup lang="ts">+import {+ GraphQLNamedType,+ isInputObjectType,+ isInterfaceType,+ isObjectType,+} from "graphql"+import { computed } from "vue"+import { useI18n } from "~/composables/i18n"+import { ExplorerFieldDef } from "~/helpers/graphql/explorer"++const t = useI18n()++const props = withDefaults(+ defineProps<{+ type: GraphQLNamedType+ showAddField: boolean+ }>(),+ {+ showAddField: true,+ }+)++const fieldMap = computed(() => {+ if (+ !isObjectType(props.type) &&+ !isInterfaceType(props.type) &&+ !isInputObjectType(props.type)+ ) {+ return {}+ }+ return props.type.getFields()+})++const fields = computed(() => {+ return Object.values(fieldMap.value) as ExplorerFieldDef[]+})+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Headers.vue b/packages/hoppscotch-common/src/components/gql/Headers.vuenew file mode 100644index 000000000..025efe7cd--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Headers.vue@@ -0,0 +1,718 @@+<template>+ <div+ class="sticky top-sidebarPrimaryStickyFold z-10 flex items-center justify-between border-y border-dividerLight bg-primary pl-4"+ >+ <label class="font-semibold text-secondaryLight">+ {{ t("tab.headers") }}+ </label>+ <div class="flex">+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ to="https://docs.hoppscotch.io/documentation/features/graphql-api-testing"+ blank+ :title="t('app.wiki')"+ :icon="IconHelpCircle"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.clear_all')"+ :icon="IconTrash2"+ @click="clearContent()"+ />+ <HoppButtonSecondary+ v-if="bulkMode"+ v-tippy="{ theme: 'tooltip' }"+ :title="t('state.linewrap')"+ :class="{ '!text-accent': WRAP_LINES }"+ :icon="IconWrapText"+ @click.prevent="toggleNestedSetting('WRAP_LINES', 'graphqlHeaders')"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('state.bulk_mode')"+ :icon="IconEdit"+ :class="{ '!text-accent': bulkMode }"+ @click="bulkMode = !bulkMode"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('add.new')"+ :icon="IconPlus"+ :disabled="bulkMode"+ @click="addHeader"+ />+ </div>+ </div>+ <div v-if="bulkMode" class="h-full relative flex flex-col flex-1">+ <div ref="bulkEditor" class="absolute inset-0"></div>+ </div>+ <div v-else>+ <draggable+ v-model="workingHeaders"+ :item-key="(header: any) => `header-${header.id}`"+ animation="250"+ handle=".draggable-handle"+ draggable=".draggable-content"+ ghost-class="cursor-move"+ chosen-class="bg-primaryLight"+ drag-class="cursor-grabbing"+ :move="+ (event: DragDropEvent) =>+ isDragDropAllowed(event, workingHeaders.length)+ "+ >+ <template #item="{ element: header, index }">+ <HttpKeyValue+ v-model:name="header.key"+ v-model:value="header.value"+ v-model:description="header.description"+ :total="workingHeaders.length"+ :index="index"+ :entity-id="header.id"+ :entity-active="header.active"+ :envs="envs"+ :is-active="header.hasOwnProperty('active')"+ :inspection-key-result="getInspectorResult(headerKeyResults, index)"+ :inspection-value-result="+ getInspectorResult(headerValueResults, index)+ "+ :key-auto-complete-source="commonHeaders"+ @update-entity="updateHeader($event.index, $event.payload)"+ @delete-entity="deleteHeader($event)"+ />+ </template>+ </draggable>++ <draggable+ v-model="computedHeaders"+ item-key="id"+ animation="250"+ handle=".draggable-handle"+ draggable=".draggable-content"+ ghost-class="cursor-move"+ chosen-class="bg-primaryLight"+ drag-class="cursor-grabbing"+ >+ <template #item="{ element: header, index }">+ <div+ class="draggable-content group flex divide-x divide-dividerLight border-b border-dividerLight"+ >+ <span>+ <HoppButtonSecondary+ :icon="IconLock"+ class="cursor-auto bg-divider text-secondaryLight opacity-25"+ tabindex="-1"+ />+ </span>++ <SmartEnvInput+ v-model="header.header.key"+ :placeholder="`${t('count.value', { count: index + 1 })}`"+ :envs="envs"+ readonly+ />++ <SmartEnvInput+ :model-value="mask(header)"+ :placeholder="`${t('count.value', { count: index + 1 })}`"+ :envs="envs"+ readonly+ />++ <input+ :value="header.header.description"+ :placeholder="t('count.description')"+ class="flex flex-1 px-4 bg-transparent text-secondaryLight"+ type="text"+ readonly+ />++ <span>+ <HoppButtonSecondary+ v-if="header.source === 'auth'"+ v-tippy="{ theme: 'tooltip' }"+ :title="t(masking ? 'state.show' : 'state.hide')"+ :icon="masking ? IconEye : IconEyeOff"+ @click="toggleMask()"+ />+ <div v-else class="aspect-square w-8"></div>+ </span>++ <span>+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :icon="IconArrowUpRight"+ :title="t('request.go_to_authorization_tab')"+ @click="changeTab"+ />+ </span>+ </div>+ </template>+ </draggable>++ <draggable+ v-model="inheritedProperty"+ item-key="id"+ animation="250"+ handle=".draggable-handle"+ draggable=".draggable-content"+ ghost-class="cursor-move"+ chosen-class="bg-primaryLight"+ drag-class="cursor-grabbing"+ >+ <template #item="{ element: header, index }">+ <div+ class="draggable-content group flex divide-x divide-dividerLight border-b border-dividerLight"+ >+ <span>+ <HoppButtonSecondary+ :icon="IconLock"+ class="cursor-auto bg-divider text-secondaryLight opacity-25"+ tabindex="-1"+ />+ </span>++ <SmartEnvInput+ v-model="header.header.key"+ :placeholder="`${t('count.value', { count: index + 1 })}`"+ :envs="envs"+ readonly+ />++ <SmartEnvInput+ :model-value="+ header.source === 'auth' ? mask(header) : header.header.value+ "+ :placeholder="`${t('count.value', { count: index + 1 })}`"+ :envs="envs"+ readonly+ />+ <input+ :value="header.header.description"+ :placeholder="t('count.description')"+ class="flex flex-1 px-4 bg-transparent text-secondaryLight"+ type="text"+ readonly+ />++ <HoppButtonSecondary+ v-if="header.source === 'auth'"+ v-tippy="{ theme: 'tooltip' }"+ :title="t(masking ? 'state.show' : 'state.hide')"+ :icon="masking && header.source === 'auth' ? IconEye : IconEyeOff"+ @click="toggleMask()"+ />+ <span v-else class="aspect-square w-[2.05rem]"></span>+ <span>+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :icon="IconInfo"+ :title="`This header is inherited from Parent Collection ${+ header.inheritedFrom ?? ''+ }`"+ />+ </span>+ </div>+ </template>+ </draggable>++ <HoppSmartPlaceholder+ v-if="workingHeaders.length === 0"+ :src="`/images/states/${colorMode.value}/add_category.svg`"+ :alt="`${t('empty.headers')}`"+ :text="t('empty.headers')"+ >+ <template #body>+ <HoppButtonSecondary+ :label="`${t('add.new')}`"+ filled+ :icon="IconPlus"+ @click="addHeader"+ />+ </template>+ </HoppSmartPlaceholder>+ </div>+</template>++<script setup lang="ts">+import { useCodemirror } from "@composables/codemirror"+import { useI18n } from "@composables/i18n"+import { useColorMode } from "@composables/theming"+import { useToast } from "@composables/toast"+import { useReadonlyStream } from "@composables/stream"+import {+ Environment,+ GQLHeader,+ HoppGQLAuth,+ HoppGQLRequest,+ parseRawKeyValueEntriesE,+ rawKeyValueEntriesToString,+ RawKeyValueEntry,+} from "@hoppscotch/data"+import { useVModel } from "@vueuse/core"+import * as A from "fp-ts/Array"+import * as E from "fp-ts/Either"+import * as O from "fp-ts/Option"+import * as RA from "fp-ts/ReadonlyArray"+import { flow, pipe } from "fp-ts/function"+import { clone, cloneDeep, isEqual } from "lodash-es"+import { computed, reactive, Ref, ref, toRef, watch } from "vue"+import draggable from "vuedraggable-es"++import { useNestedSetting } from "~/composables/settings"+import { throwError } from "~/helpers/functional/error"+import { objRemoveKey } from "~/helpers/functional/object"+import { commonHeaders } from "~/helpers/headers"+import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"+import { isDragDropAllowed, DragDropEvent } from "~/helpers/dragDropValidation"+import { getComputedGQLAuthHeaders } from "~/helpers/utils/EffectiveURL"+import {+ filterNonEmptyEnvironmentVariables,+ getEffectiveVariablesForRequest,+} from "~/helpers/utils/environments"+import {+ AggregateEnvironment,+ aggregateEnvsWithCurrentValue$,+ getAggregateEnvsWithCurrentValue,+} from "~/newstore/environments"+import { toggleNestedSetting } from "~/newstore/settings"+import IconArrowUpRight from "~icons/lucide/arrow-up-right"+import IconEdit from "~icons/lucide/edit"+import IconEye from "~icons/lucide/eye"+import IconEyeOff from "~icons/lucide/eye-off"+import IconHelpCircle from "~icons/lucide/help-circle"+import IconInfo from "~icons/lucide/info"+import IconLock from "~icons/lucide/lock"+import IconPlus from "~icons/lucide/plus"+import IconTrash2 from "~icons/lucide/trash-2"+import IconWrapText from "~icons/lucide/wrap-text"+// `./RequestOptions.vue` only re-imports this type, it doesn't re-export it —+// pull it from the module that actually declares it (same as gql/RequestOptions.vue does).+import { GQLOptionTabs } from "~/components/graphql/RequestOptions.vue"+import { InspectionService, InspectorResult } from "~/services/inspection"+import { useService } from "dioc/vue"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"++const colorMode = useColorMode()+const t = useI18n()+const toast = useToast()++type GqlHeadersModel =+ HoppGQLRequest | { headers: GQLHeader[]; auth: HoppGQLAuth }++const props = defineProps<{+ modelValue: GqlHeadersModel+ inheritedProperties?: HoppInheritedProperty+ // Embed-only env scope; omit to use the global aggregate envs+ envs?: AggregateEnvironment[]+}>()++const emit = defineEmits<{+ (e: "update:modelValue", value: GqlHeadersModel): void+ (e: "change-tab", value: GQLOptionTabs): void+}>()++const request = useVModel(props, "modelValue", emit)++const idTicker = ref(0)++const WRAP_LINES = useNestedSetting("WRAP_LINES", "graphqlHeaders")+const bulkMode = ref(false)+const bulkHeaders = ref("")++const deletionToast = ref<{ goAway: (delay: number) => void } | null>(null)++const bulkEditor = ref<any | null>(null)++useCodemirror(+ bulkEditor,+ bulkHeaders,+ reactive({+ extendedEditorConfig: {+ mode: "text/x-yaml",+ placeholder: `${t("state.bulk_mode_placeholder")}`,+ lineWrapping: WRAP_LINES,+ },+ linter: null,+ completer: null,+ environmentHighlights: true,+ envs: computed(() => props.envs),+ predefinedVariablesHighlights: true,+ })+)++const workingHeaders = ref<Array<GQLHeader & { id: number }>>([+ {+ id: idTicker.value++,+ key: "",+ value: "",+ active: true,+ description: "",+ },+])++watch(workingHeaders, (headersList) => {+ if (+ headersList.length > 0 &&+ headersList[headersList.length - 1].key !== ""+ ) {+ workingHeaders.value.push({+ id: idTicker.value++,+ key: "",+ value: "",+ active: true,+ description: "",+ })+ }+})++watch(+ () => request.value.headers,+ (newHeadersList) => {+ const filteredWorkingHeaders = pipe(+ workingHeaders.value,+ A.filterMap(+ flow(+ O.fromPredicate((e) => e.key !== ""),+ O.map(objRemoveKey("id"))+ )+ )+ )++ const filteredBulkHeaders = pipe(+ parseRawKeyValueEntriesE(bulkHeaders.value),+ E.map(+ flow(+ RA.filter((e) => e.key !== ""),+ RA.toArray+ )+ ),+ E.getOrElse(() => [] as RawKeyValueEntry[])+ )++ if (!isEqual(newHeadersList, filteredWorkingHeaders)) {+ workingHeaders.value = pipe(+ newHeadersList,+ A.map((x) => ({ id: idTicker.value++, ...x }))+ )+ }++ const newHeadersListKeyValuePairs = newHeadersList.map(+ ({ key, value, active }) => ({+ key,+ value,+ active,+ })+ )++ if (!isEqual(newHeadersListKeyValuePairs, filteredBulkHeaders)) {+ bulkHeaders.value = rawKeyValueEntriesToString(+ newHeadersListKeyValuePairs+ )+ }+ },+ { immediate: true }+)++watch(workingHeaders, (newWorkingHeaders) => {+ const fixedHeaders = pipe(+ newWorkingHeaders,+ A.filterMap(+ flow(+ O.fromPredicate((e) => e.key !== ""),+ O.map(objRemoveKey("id"))+ )+ )+ )++ if (!isEqual(request.value.headers, fixedHeaders)) {+ request.value.headers = cloneDeep(fixedHeaders)+ }+})++watch(bulkHeaders, (newBulkHeaders) => {+ const filteredBulkHeaders = pipe(+ parseRawKeyValueEntriesE(newBulkHeaders),+ E.map(+ flow(+ RA.filter((e) => e.key !== ""),+ RA.toArray+ )+ ),+ E.getOrElse(() => [] as RawKeyValueEntry[])+ )++ const headers = toRef(request.value, "headers")++ const paramKeyValuePairs = headers.value.map(({ key, value, active }) => ({+ key,+ value,+ active,+ }))++ if (!isEqual(paramKeyValuePairs, filteredBulkHeaders)) {+ headers.value = filteredBulkHeaders.map((param, idx) => ({+ ...param,+ description: headers.value[idx]?.description ?? "",+ }))+ }+})++watch(workingHeaders, (newHeadersList) => {+ if (bulkMode.value) return++ try {+ const currentBulkHeaders = bulkHeaders.value.split("\n").map((item) => ({+ key: item.substring(0, item.indexOf(":")).trimStart().replace(/^#/, ""),+ value: item.substring(item.indexOf(":") + 1).trimStart(),+ active: !item.trim().startsWith("#"),+ }))++ const filteredHeaders = newHeadersList.filter((x) => x.key !== "")++ if (!isEqual(currentBulkHeaders, filteredHeaders)) {+ bulkHeaders.value = rawKeyValueEntriesToString(filteredHeaders)+ }+ } catch (e) {+ toast.error(`${t("error.something_went_wrong")}`)+ console.error(e)+ }+})++const addHeader = () => {+ workingHeaders.value.push({+ id: idTicker.value++,+ key: "",+ value: "",+ active: true,+ description: "",+ })+}++const updateHeader = (index: number, header: GQLHeader & { id: number }) => {+ workingHeaders.value = workingHeaders.value.map((h, i) =>+ i === index ? header : h+ )+}++const deleteHeader = (index: number) => {+ const headersBeforeDeletion = clone(workingHeaders.value)++ if (!(+ headersBeforeDeletion.length > 0 &&+ index === headersBeforeDeletion.length - 1+ )) {+ if (deletionToast.value) {+ deletionToast.value.goAway(0)+ deletionToast.value = null+ }++ deletionToast.value = toast.success(`${t("state.deleted")}`, {+ action: [+ {+ text: `${t("action.undo")}`,+ onClick: (_: any, toastObject: any) => {+ workingHeaders.value = headersBeforeDeletion+ toastObject.goAway(0)+ deletionToast.value = null+ },+ },+ ],++ onComplete: () => {+ deletionToast.value = null+ },+ })+ }++ workingHeaders.value = pipe(+ workingHeaders.value,+ A.deleteAt(index),+ O.getOrElseW(() => throwError("Working Headers Deletion Out of Bounds"))+ )+}++const clearContent = () => {+ workingHeaders.value = [+ {+ id: idTicker.value++,+ key: "",+ value: "",+ active: true,+ description: "",+ },+ ]++ bulkHeaders.value = ""+}++const aggregateEnvs = useReadonlyStream(+ aggregateEnvsWithCurrentValue$,+ getAggregateEnvsWithCurrentValue()+)++// Same precedence as the send path (gql-tab-connection.service): inherited+// collection variables outrank selected/global env vars. A scoped `envs`+// prop (embeds) replaces the global aggregate, mirroring http/Headers.+const resolvedEnvs = computed<Environment["variables"]>(() =>+ filterNonEmptyEnvironmentVariables(+ getEffectiveVariablesForRequest(+ undefined,+ props.inheritedProperties?.variables,+ props.envs ?? aggregateEnvs.value+ )+ )+)++const computedHeaders: Ref<+ {+ source: "auth"+ header: GQLHeader+ id: string+ }[]+> = ref([])++watch(+ [request, resolvedEnvs],+ async (_newVals, _oldVals, onCleanup) => {+ let isStale = false+ onCleanup(() => {+ isStale = true+ })++ const headers = await getComputedGQLAuthHeaders(+ resolvedEnvs.value,+ request.value+ )+ if (isStale) return++ computedHeaders.value = headers.map((header, index) => ({+ id: `header-${index}`,+ source: "auth",+ header,+ }))+ },+ { immediate: true, deep: true }+)++type InheritedHeader = {+ inheritedFrom: string+ source: "auth" | "headers"+ id: string+ header: GQLHeader+}++const inheritedProperty = ref<InheritedHeader[]>([])++watch(+ [() => props.inheritedProperties, request, resolvedEnvs],+ async (_newVals, _oldVals, onCleanup) => {+ let isStale = false+ onCleanup(() => {+ isStale = true+ })++ if (!props.inheritedProperties) {+ // Clear any previously-computed inherited rows so they don't linger when+ // the request switches to one without inherited collection settings.+ inheritedProperty.value = []+ return+ }++ const inheritedHeaders = props.inheritedProperties.headers.filter(+ (header) =>+ !request.value.headers.some(+ (requestHeader) =>+ requestHeader.key === header.inheritedHeader?.key &&+ requestHeader.active+ )+ )+ const headersList: InheritedHeader[] = inheritedHeaders.map(+ (header, index) => ({+ inheritedFrom: header.parentName!,+ source: "headers",+ id: `header-${index}`,+ header: header.inheritedHeader,+ })+ )++ if (+ props.inheritedProperties.auth &&+ request.value.auth.authType === "inherit" &&+ request.value.auth.authActive &&+ !request.value.headers.some(+ (requestHeader) =>+ requestHeader.key === "Authorization" && requestHeader.active+ )+ ) {+ try {+ const [computedAuthHeader] = await getComputedGQLAuthHeaders(+ resolvedEnvs.value,+ request.value,+ props.inheritedProperties.auth.inheritedAuth+ )+ if (isStale) return++ if (computedAuthHeader) {+ headersList.push({+ inheritedFrom: props.inheritedProperties.auth.parentName,+ source: "auth",+ id: `header-auth`,+ header: computedAuthHeader,+ })+ }+ } catch (e) {+ // A signing generator can throw (eg. aws-signature on an unresolvable+ // URL) — commit the headers collected so far without the auth row+ // rather than erasing every inherited header.+ if (isStale) return+ console.error(e)+ }+ }++ inheritedProperty.value = headersList+ },+ { immediate: true, deep: true }+)++const masking = ref(true)++const toggleMask = () => {+ masking.value = !masking.value+}++const mask = (header: any) => {+ if (header.source === "auth" && masking.value)+ return header.header.value.replace(/\S/gi, "*")+ return header.header.value+}++const changeTab = () => emit("change-tab", "authorization")++const inspectionService = useService(InspectionService)+const tabs = useService(WorkspaceTabsService)++const headerKeyResults = inspectionService.getResultViewFor(+ tabs.currentTabID.value,+ (result) =>+ result.locations.type === "header" && result.locations.position === "key"+)++const headerValueResults = inspectionService.getResultViewFor(+ tabs.currentTabID.value,+ (result) =>+ result.locations.type === "header" && result.locations.position === "value"+)++const getInspectorResult = (results: InspectorResult[], index: number) => {+ return results.filter((result) => {+ if (+ result.locations.type === "url" ||+ result.locations.type === "response" ||+ result.locations.type === "body-content-type-header"+ )+ return+ return result.locations.index === index+ })+}+</script>diff --git a/packages/hoppscotch-common/src/components/gql/ImplementsInterfaces.vue b/packages/hoppscotch-common/src/components/gql/ImplementsInterfaces.vuenew file mode 100644index 000000000..310a0c625--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/ImplementsInterfaces.vue@@ -0,0 +1,27 @@+<template>+ <GqlExplorerSection v-if="interfaces.length > 0" title="Implements">+ <div+ v-for="implementedInterface in interfaces"+ :key="implementedInterface.name"+ class="px-4 py-2 transition hover:bg-primaryLight"+ >+ <GqlTypeLink :type="implementedInterface" :clickable="true" />+ </div>+ </GqlExplorerSection>+</template>++<script setup lang="ts">+import { computed } from "vue"+import { isObjectType, GraphQLNamedType } from "graphql"++const props = defineProps<{+ type: GraphQLNamedType+}>()++const interfaces = computed(() => {+ if (!isObjectType(props.type)) {+ return []+ }+ return props.type.getInterfaces()+})+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Query.vue b/packages/hoppscotch-common/src/components/gql/Query.vuenew file mode 100644index 000000000..16268d4d6--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Query.vue@@ -0,0 +1,300 @@+<template>+ <div+ class="sticky top-upperSecondaryStickyFold z-10 flex items-center justify-between border-y border-dividerLight bg-primary pl-4"+ >+ <label class="font-semibold text-secondaryLight">+ {{ t("request.query") }}+ </label>+ <div class="flex">+ <HoppButtonSecondary+ v-if="showRunActions && subscriptionState === 'SUBSCRIBED'"+ v-tippy="{+ theme: 'tooltip',+ delay: [500, 20],+ allowHTML: true,+ }"+ :title="`${t('request.stop')}`"+ :label="`${t('request.stop')}`"+ :icon="IconStop"+ class="!hover:text-accentDark rounded-none !text-accent"+ @click="stopQuery()"+ />++ <HoppButtonSecondary+ v-if="showRunActions && subscriptionState !== 'SUBSCRIBED'"+ v-tippy="{+ theme: 'tooltip',+ delay: [500, 20],+ allowHTML: true,+ }"+ :title="`${t('request.run')} <kbd>${getSpecialKey()}</kbd><kbd>↩</kbd>`"+ :label="`${selectedOperation?.name?.value ?? t('request.run')}`"+ :icon="IconPlay"+ class="!hover:text-accentDark rounded-none !text-accent"+ @click="runQuery(selectedOperation)"+ />++ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip', delay: [500, 20], allowHTML: true }"+ :title="`${t(+ 'request.save'+ )} <kbd>${getSpecialKey()}</kbd><kbd>S</kbd>`"+ :label="`${t('request.save')}`"+ :icon="IconSave"+ class="rounded-none"+ @click="saveRequest"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('app.wiki')"+ to="https://docs.hoppscotch.io/documentation/features/graphql-api-testing"+ blank+ :icon="IconHelpCircle"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.clear_all')"+ :icon="IconTrash2"+ @click="clearGQLQuery()"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('state.linewrap')"+ :class="{ '!text-accent': WRAP_LINES }"+ :icon="IconWrapText"+ @click.prevent="toggleNestedSetting('WRAP_LINES', 'graphqlQuery')"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.prettify')"+ :icon="prettifyQueryIcon"+ @click="prettifyQuery"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.copy')"+ :icon="copyQueryIcon"+ @click="copyQuery"+ />+ </div>+ </div>+ <div class="h-full relative flex flex-col flex-1">+ <div ref="queryEditor" class="absolute inset-0"></div>+ </div>+</template>++<script setup lang="ts">+import IconPlay from "~icons/lucide/play"+import IconStop from "~icons/lucide/stop-circle"+import IconSave from "~icons/lucide/save"+import IconHelpCircle from "~icons/lucide/help-circle"+import IconTrash2 from "~icons/lucide/trash-2"+import IconCopy from "~icons/lucide/copy"+import IconCheck from "~icons/lucide/check"+import IconInfo from "~icons/lucide/info"+import IconWand from "~icons/lucide/wand"+import IconWrapText from "~icons/lucide/wrap-text"+import {+ onBeforeUnmount,+ onMounted,+ reactive,+ ref,+ markRaw,+ watch,+ nextTick,+ computed,+} from "vue"+import { copyToClipboard } from "@helpers/utils/clipboard"+import { useCodemirror } from "@composables/codemirror"+import { useI18n } from "@composables/i18n"+import { refAutoReset, useVModel } from "@vueuse/core"+import { useToast } from "~/composables/toast"+import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"+import { OperationDefinitionNode, parse, print } from "graphql"+import { createGQLQueryLinter } from "~/helpers/editor/linting/gqlQuery"+import queryCompleter from "~/helpers/editor/completion/gqlQuery"+import { selectedGQLOpHighlight } from "~/helpers/editor/gql/operation"+import { debounce } from "lodash-es"+import { ViewUpdate } from "@codemirror/view"+import { defineActionHandler } from "~/helpers/actions"+import { GQLTabConnectionService } from "~/services/gql-tab-connection.service"+import { useNestedSetting } from "~/composables/settings"+import { toggleNestedSetting } from "~/newstore/settings"+import { useService } from "dioc/vue"+import { GQLQueryBuilderService } from "~/services/gql-query-builder.service"+import type { SubscriptionState } from "~/helpers/graphql/connection"+import type { AggregateEnvironment } from "~/newstore/environments"++// Template refs+const queryEditor = ref<any | null>(null)++const t = useI18n()+const toast = useToast()++const props = withDefaults(+ defineProps<{+ modelValue: string+ showRunActions?: boolean+ subscriptionState?: SubscriptionState+ // Embed-only env scope for `<<var>>` highlights+ envs?: AggregateEnvironment[]+ }>(),+ { showRunActions: true, subscriptionState: undefined, envs: undefined }+)++const emit = defineEmits<{+ (e: "save-request"): void+ (e: "update:modelValue", val: string): void+ (e: "cursor-position", val: number): void+ (e: "run-query", definition: OperationDefinitionNode | null): void+ (e: "stop-query"): void+}>()++const copyQueryIcon = refAutoReset<typeof IconCopy | typeof IconCheck>(+ IconCopy,+ 1000+)+const prettifyQueryIcon = refAutoReset<+ typeof IconWand | typeof IconCheck | typeof IconInfo+>(IconWand, 1000)++const WRAP_LINES = useNestedSetting("WRAP_LINES", "graphqlQuery")++const selectedOperation = ref<OperationDefinitionNode | null>(null)++const gqlQueryString = useVModel(props, "modelValue", emit)++// Unified workspace's schema-explorer → editor insertion runs through+// `GQLQueryBuilderService` — not the legacy `useQuery()` composable that+// backs `graphql/Query.vue`. The service owns its own `updatedQuery`,+// `cursorPosition`, and `operations` refs.+const queryBuilder = useService(GQLQueryBuilderService)+const updatedQuery = queryBuilder.updatedQuery+const cursorPosition = queryBuilder.cursorPosition+const operationDefinitions = queryBuilder.operations++// Active tab's schema — not the legacy /graphql page singleton, which the+// unified workspace never writes.+const gqlTabConn = useService(GQLTabConnectionService)+const schema = gqlTabConn.activeTabSchema++const debouncedOnUpdateQueryState = debounce((update: ViewUpdate) => {+ const selectedPos = update.state.selection.main.head+ emit("cursor-position", selectedPos)+ selectedOperation.value = null+ const queryString = update.state.doc.toJSON().join(update.state.lineBreak)++ try {+ const ast = parse(queryString)++ operationDefinitions.value = ast.definitions.filter(+ (def) => def.kind === "OperationDefinition"+ ) as OperationDefinitionNode[]++ if (ast.definitions.length === 1) {+ selectedOperation.value = ast.definitions[0] as OperationDefinitionNode+ return+ }++ selectedOperation.value =+ (ast.definitions.find((def) => {+ if (def.kind !== "OperationDefinition") return false+ const { start, end } = def.loc!+ return selectedPos >= start && selectedPos <= end+ }) as OperationDefinitionNode) ?? null+ } catch (_error) {+ if (queryString.trim() === "") {+ operationDefinitions.value = []+ }+ }+}, 100)++// A pending update from a closing tab must not overwrite the shared+// query-builder service refs after another tab's Query.vue has mounted+// (mirrors Argument.vue's cancel-on-unmount)+onBeforeUnmount(() => {+ debouncedOnUpdateQueryState.cancel()+})++onMounted(() => {+ try {+ const ast = parse(gqlQueryString.value)++ operationDefinitions.value = ast.definitions.filter(+ (def) => def.kind === "OperationDefinition"+ ) as OperationDefinitionNode[]++ if (ast.definitions.length) {+ selectedOperation.value = ast.definitions[0] as OperationDefinitionNode+ return+ }+ } catch (_error) {}+})++const cmQueryEditor = useCodemirror(+ queryEditor,+ gqlQueryString,+ reactive({+ extendedEditorConfig: {+ mode: "graphql",+ placeholder: `${t("request.query")}`,+ lineWrapping: WRAP_LINES,+ },+ linter: createGQLQueryLinter(schema),+ completer: queryCompleter(schema),+ environmentHighlights: true,+ envs: computed(() => props.envs),+ predefinedVariablesHighlights: true,+ additionalExts: [markRaw(selectedGQLOpHighlight)],+ onUpdate: debouncedOnUpdateQueryState,+ })+)++watch(updatedQuery, async (newQuery) => {+ if (newQuery) {+ gqlQueryString.value = newQuery++ await nextTick()++ if (cursorPosition.value) {+ cmQueryEditor.cursor.value = cursorPosition.value+ }+ }+})++const prettifyQuery = () => {+ try {+ gqlQueryString.value = print(+ parse(gqlQueryString.value, {+ allowLegacyFragmentVariables: true,+ })+ )+ prettifyQueryIcon.value = IconCheck+ } catch (_e) {+ toast.error(`${t("error.gql_prettify_invalid_query")}`)+ prettifyQueryIcon.value = IconInfo+ }+}++const copyQuery = () => {+ copyToClipboard(gqlQueryString.value)+ copyQueryIcon.value = IconCheck+ toast.success(`${t("state.copied_to_clipboard")}`)+}++const clearGQLQuery = () => {+ gqlQueryString.value = ""+}++const runQuery = (definition: OperationDefinitionNode | null = null) => {+ emit("run-query", definition)+}+const stopQuery = () => {+ emit("stop-query")+}+const saveRequest = () => {+ emit("save-request")+}++defineActionHandler("editor.format", prettifyQuery)+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Request.vue b/packages/hoppscotch-common/src/components/gql/Request.vuenew file mode 100644index 000000000..6f793db9f--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Request.vue@@ -0,0 +1,297 @@+<template>+ <div+ class="sticky top-0 z-20 flex flex-shrink-0 space-x-2 overflow-x-auto bg-primary p-4"+ >+ <div class="inline-flex flex-1 space-x-2">+ <div+ class="flex flex-1 whitespace-nowrap rounded border border-divider bg-primaryLight"+ >+ <SmartEnvInput+ v-model="url"+ :placeholder="`${t('graphql.url_placeholder')}`"+ :auto-complete-env="true"+ :inspection-results="urlResults"+ :readonly="connected || connecting"+ @enter="runQuery"+ />+ </div>+ <HoppButtonPrimary+ id="connect"+ v-tippy="{ theme: 'tooltip' }"+ :title="!connected ? t('action.connect') : t('action.disconnect')"+ :label="!connected ? t('action.connect') : t('action.disconnect')"+ :loading="tabCtx?.state === 'CONNECTING'"+ filled+ outline+ @click="onConnectClick"+ />+ <span class="flex rounded border border-divider transition">+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip', delay: [500, 20], allowHTML: true }"+ :title="`${t(+ 'request.save'+ )} <kbd>${getSpecialKey()}</kbd><kbd>S</kbd>`"+ :label="COLUMN_LAYOUT ? `${t('request.save')}` : ''"+ filled+ :icon="IconSave"+ class="rounded rounded-r-none"+ @click="saveRequest()"+ />+ <span class="flex">+ <tippy+ interactive+ trigger="click"+ theme="popover"+ :on-shown="() => saveTippyActions.focus()"+ >+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('app.options')"+ :icon="IconChevronDown"+ filled+ class="rounded rounded-l-none"+ />+ <template #content="{ hide }">+ <div+ ref="saveTippyActions"+ class="flex flex-col focus:outline-none"+ tabindex="0"+ @keyup.escape="hide()"+ >+ <HoppSmartItem+ :label="`${t('request.save_as')}`"+ :icon="IconFolderPlus"+ @click="+ () => {+ showSaveRequestModal = true+ hide()+ }+ "+ />+ <hr />+ <HoppSmartItem+ :label="t('request.share_request')"+ :icon="IconShare2"+ @click="+ () => {+ shareRequest()+ hide()+ }+ "+ />+ </div>+ </template>+ </tippy>+ </span>+ </span>+ </div>+ </div>+ <CollectionsSaveRequest+ v-if="showSaveRequestModal"+ mode="workspace"+ :show="showSaveRequestModal"+ @hide-modal="showSaveRequestModal = false"+ />+</template>++<script setup lang="ts">+import { platform } from "~/platform"+import { useI18n } from "@composables/i18n"+import { useReadonlyStream } from "@composables/stream"+import { useToast } from "@composables/toast"+import { computed, ref } from "vue"+import { useVModel } from "@vueuse/core"+import * as E from "fp-ts/Either"+import { GQLTabConnectionService } from "~/services/gql-tab-connection.service"+import { KernelInterceptorService } from "~/services/kernel-interceptor.service"+import { InspectionService } from "~/services/inspection"+import { useService } from "dioc/vue"+import { defineActionHandler, invokeAction } from "~/helpers/actions"+import { HoppGQLAuth, HoppGQLRequest } from "@hoppscotch/data"+import { HoppTab } from "~/services/tab"+import { HoppGQLRequestDocument } from "~/helpers/tab/document"+import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"+import { editRESTRequest } from "~/newstore/collections"+import { updateTeamRequest } from "~/helpers/backend/mutations/TeamRequest"+import IconSave from "~icons/lucide/save"+import IconChevronDown from "~icons/lucide/chevron-down"+import IconFolderPlus from "~icons/lucide/folder-plus"+import IconShare2 from "~icons/lucide/share-2"+import { useSetting } from "~/composables/settings"++const t = useI18n()+const toast = useToast()++const interceptorService = useService(KernelInterceptorService)+const gqlTabConn = useService(GQLTabConnectionService)+const inspectionService = useService(InspectionService)+const COLUMN_LAYOUT = useSetting("COLUMN_LAYOUT")++const props = defineProps<{+ modelValue: HoppTab<HoppGQLRequestDocument>+}>()++const emit = defineEmits<{+ (e: "update:modelValue", val: HoppTab<HoppGQLRequestDocument>): void+}>()++const tab = useVModel(props, "modelValue", emit)++const showSaveRequestModal = ref(false)+const saveTippyActions = ref<HTMLDivElement | null>(null)++const tabCtx = computed(() => gqlTabConn.getTabConnectionState(tab.value.id))+const connected = computed(() => tabCtx.value.state === "CONNECTED")+// The URL field is locked once a connection is established or in flight — you+// disconnect to retarget the tab. Keeping it read-only here is why there's no+// "URL edited mid-connection" reconnect logic: that state isn't reachable.+const connecting = computed(() => tabCtx.value.state === "CONNECTING")++const url = computed({+ get: () => tab.value.document.request.url,+ set: (value) => {+ tab.value.document.request.url = value+ },+})++const urlResults = inspectionService.getResultViewFor(+ tab.value.id,+ (result) => result.locations.type === "url"+)++const onConnectClick = () => {+ if (!connected.value) {+ gqlConnect()+ } else {+ gqlTabConn.disconnectTab(tab.value.id)+ }+}++const runQuery = () => {+ invokeAction("request.send-cancel")+}++const saveRequest = () => {+ const saveCtx = tab.value.document.saveContext++ if (!saveCtx) {+ showSaveRequestModal.value = true+ return+ }++ if (saveCtx.originLocation === "user-collection") {+ const req = tab.value.document.request++ if (saveCtx.requestIndex === undefined) {+ showSaveRequestModal.value = true+ return+ }++ // Only the mutation is guarded — post-persist steps must not clear a+ // save context the store write already honored+ try {+ editRESTRequest(saveCtx.folderPath, saveCtx.requestIndex, req)+ } catch (e) {+ // Stale saveContext — drop it and reopen Save As, same as the REST flow+ console.error("Stale save context, reopening Save As", e)+ tab.value.document.saveContext = undefined+ saveRequest()+ return+ }++ // Ensure requestRefID is set in save context for active indicator+ if (!saveCtx.requestRefID && req._ref_id) {+ saveCtx.requestRefID = req._ref_id+ }++ tab.value.document.isDirty = false++ platform.analytics?.logEvent({+ type: "HOPP_SAVE_REQUEST",+ platform: "gql",+ createdNow: false,+ workspaceType: "personal",+ })++ toast.success(`${t("request.saved")}`)+ } else if (saveCtx.originLocation === "team-collection") {+ const req = tab.value.document.request++ platform.analytics?.logEvent({+ type: "HOPP_SAVE_REQUEST",+ platform: "gql",+ createdNow: false,+ workspaceType: "team",+ })++ updateTeamRequest(saveCtx.requestID, {+ request: JSON.stringify(req),+ title: req.name,+ })().then((result) => {+ if (E.isLeft(result)) {+ toast.error(`${t("profile.no_permission")}`)+ } else {+ tab.value.document.isDirty = false+ toast.success(`${t("request.saved")}`)+ }+ })+ } else {+ showSaveRequestModal.value = true+ }+}++const currentUser = useReadonlyStream(+ platform.auth.getCurrentUserStream(),+ platform.auth.getCurrentUser()+)++const shareRequest = () => {+ if (currentUser.value) {+ invokeAction("share.request", {+ request: tab.value.document.request,+ })+ } else {+ invokeAction("modals.login.toggle")+ }+}++const gqlConnect = () => {+ // Map each inherited entry to its header; `?? []` covers the no-inheritance+ // case. (Mirrors GqlRequestOptions. The previous `return []` for a missing+ // header inserted empty arrays into the header list.)+ const inheritedHeaders = (tab.value.document.inheritedProperties?.headers.map(+ (header) => header.inheritedHeader+ ) ?? []) as HoppGQLRequest["headers"]++ gqlTabConn.connectTab(tab.value.id, {+ url: url.value,+ request: tab.value.document.request,+ inheritedHeaders,+ inheritedAuth: tab.value.document.inheritedProperties?.auth+ .inheritedAuth as HoppGQLAuth,+ inheritedVariables: tab.value.document.inheritedProperties?.variables,+ })++ platform.analytics?.logEvent({+ type: "HOPP_REQUEST_RUN",+ platform: "graphql-schema",+ strategy: interceptorService.current.value!.id,+ })+}++defineActionHandler(+ "gql.connect",+ gqlConnect,+ computed(() => !connected.value)+)++defineActionHandler(+ "gql.disconnect",+ () => gqlTabConn.disconnectTab(tab.value.id),+ connected+)+defineActionHandler("request-response.save", saveRequest)+defineActionHandler("request.save-as", () => {+ showSaveRequestModal.value = true+})+</script>diff --git a/packages/hoppscotch-common/src/components/gql/RequestOptions.vue b/packages/hoppscotch-common/src/components/gql/RequestOptions.vuenew file mode 100644index 000000000..da05931e5--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/RequestOptions.vue@@ -0,0 +1,428 @@+<template>+ <HoppSmartTabs+ v-model="selectedOptionTab"+ styles="sticky overflow-x-auto flex-shrink-0 bg-primary top-upperPrimaryStickyFold z-10 border-b-0"+ :render-inactive-tabs="true"+ >+ <HoppSmartTab+ v-if="showTab('query')"+ :id="'query'"+ :label="`${t('tab.query')}`"+ :indicator="request.query && request.query.length > 0 ? true : false"+ >+ <GqlQuery+ v-model="request.query"+ :show-run-actions="showRunActions"+ :subscription-state="subscriptionState"+ :envs="envs"+ @run-query="runQuery"+ @stop-query="stopQuery"+ @save-request="() => invokeAction('request-response.save')"+ @cursor-position="updateCursorPos"+ />+ </HoppSmartTab>+ <HoppSmartTab+ v-if="showTab('variables')"+ :id="'variables'"+ :label="`${t('tab.variables')}`"+ :indicator="+ request.variables && request.variables.length > 0 ? true : false+ "+ >+ <GqlVariable+ v-model="request.variables"+ :show-run-actions="showRunActions"+ :subscription-state="subscriptionState"+ :envs="envs"+ @run-query="runQuery"+ @stop-query="stopQuery"+ @save-request="() => invokeAction('request-response.save')"+ />+ </HoppSmartTab>+ <HoppSmartTab+ v-if="showTab('headers')"+ :id="'headers'"+ :label="`${t('tab.headers')}`"+ :info="activeGQLHeadersCount === 0 ? null : `${activeGQLHeadersCount}`"+ >+ <GqlHeaders+ v-model="request"+ :inherited-properties="inheritedProperties"+ :envs="envs"+ @change-tab="changeOptionTab"+ />+ </HoppSmartTab>+ <HoppSmartTab+ v-if="showTab('authorization')"+ :id="'authorization'"+ :label="`${t('tab.authorization')}`"+ >+ <GqlAuthorization+ v-model="request.auth"+ :inherited-properties="inheritedProperties"+ :envs="envs"+ />+ </HoppSmartTab>+ <!-- Script tabs are guarded on the request SHAPE (not just the filter):+ saved-example originalRequest models never carry script fields -->+ <HoppSmartTab+ v-if="showTab('preRequestScript') && 'preRequestScript' in request"+ :id="'preRequestScript'"+ :label="`${t('tab.pre_request_script')}`"+ :indicator="+ hasActualScript(request.preRequestScript) ||+ hasInheritedPreRequestScripts+ "+ >+ <HttpPreRequestScript+ v-model="request.preRequestScript"+ :is-active="selectedOptionTab === 'preRequestScript'"+ :inherited-properties="inheritedProperties"+ />+ </HoppSmartTab>+ <HoppSmartTab+ v-if="showTab('tests') && 'testScript' in request"+ :id="'tests'"+ :label="`${t('tab.post_request_script')}`"+ :indicator="+ hasActualScript(request.testScript) || hasInheritedTestScripts+ "+ >+ <HttpTests+ v-model="request.testScript"+ :is-active="selectedOptionTab === 'tests'"+ :inherited-properties="inheritedProperties"+ />+ </HoppSmartTab>+ </HoppSmartTabs>+</template>++<script setup lang="ts">+import { useI18n } from "@composables/i18n"+import { useToast } from "@composables/toast"+import {+ HoppGQLAuth,+ HoppGQLRequest,+ HoppGQLResponseOriginalRequest,+} from "@hoppscotch/data"+import { useVModel } from "@vueuse/core"+import { hasActualScript } from "@hoppscotch/js-sandbox/scripting"+import * as gql from "graphql"+import { clone, cloneDeep } from "lodash-es"+import { computed, watch } from "vue"+import { defineActionHandler, invokeAction } from "~/helpers/actions"+import {+ GQLTabConnectionService,+ type GQLResponseEvent,+} from "~/services/gql-tab-connection.service"+import { HoppTestResult } from "~/helpers/types/HoppTestResult"+import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"+import { AggregateEnvironment } from "~/newstore/environments"+import { completePageProgress, startPageProgress } from "~/modules/loadingbar"+import { platform } from "~/platform"+import { KernelInterceptorService } from "~/services/kernel-interceptor.service"+import { useService } from "dioc/vue"+import { GQLOptionTabs } from "~/components/graphql/RequestOptions.vue"++type GqlRequestOptionsModel = HoppGQLRequest | HoppGQLResponseOriginalRequest++const interceptorService = useService(KernelInterceptorService)+const gqlTabConn = useService(GQLTabConnectionService)++const t = useI18n()+const toast = useToast()++const props = withDefaults(+ defineProps<{+ modelValue: GqlRequestOptionsModel+ response?: GQLResponseEvent[] | null+ optionTab?: GQLOptionTabs+ // Written via update:testResults only (v-model target) — declared so the+ // binding doesn't fall through as a stringified DOM attribute+ testResults?: HoppTestResult | null+ tabId?: string+ url?: string+ inheritedProperties?: HoppInheritedProperty+ showRunActions?: boolean+ /**+ * Filter which sub-tabs are visible. Used by the embed renderer to+ * honour the share-er's customize selections. `undefined` shows all+ * tabs (default for the live editor).+ */+ properties?: string[]+ // Embed-only env scope; `undefined` uses the global aggregate envs+ envs?: AggregateEnvironment[]+ }>(),+ {+ response: null,+ optionTab: "query",+ testResults: undefined,+ tabId: "",+ url: "",+ showRunActions: true,+ properties: undefined,+ envs: undefined,+ }+)++const emit = defineEmits<{+ (e: "update:modelValue", value: GqlRequestOptionsModel): void+ (e: "update:optionTab", value: GQLOptionTabs): void+ (e: "update:response", value: GQLResponseEvent[]): void+ (e: "update:testResults", value: HoppTestResult | null | undefined): void+ (e: "cursor-position", pos: number): void+}>()++const selectedOptionTab = useVModel(props, "optionTab", emit)+const request = useVModel(props, "modelValue", emit)++// Show a tab when `properties` is absent (live editor — all four) OR the tab+// is explicitly listed. An empty `properties` array would otherwise hide every+// tab — `.includes(...)` returns false for all queries, and the `?? true`+// short-circuit on the v-if only catches `undefined`/`null`. That edge case+// happens when the share-er disables every customize toggle.+const showTab = (id: GQLOptionTabs) => {+ if (props.properties === undefined) return true+ if (props.properties.length === 0) return true+ return props.properties.includes(id)+}++// Yellow indicator dots when a collection ancestor contributes scripts —+// mirrors http/RequestOptions.vue+const hasInheritedPreRequestScripts = computed(+ () =>+ props.inheritedProperties?.scripts?.some((script) =>+ hasActualScript(script.preRequestScript)+ ) ?? false+)++const hasInheritedTestScripts = computed(+ () =>+ props.inheritedProperties?.scripts?.some((script) =>+ hasActualScript(script.testScript)+ ) ?? false+)++const subscriptionState = computed(() =>+ props.tabId+ ? gqlTabConn.getTabSubscriptionState(props.tabId).value+ : undefined+)++const stopQuery = () => {+ if (!props.tabId) return+ gqlTabConn.unsubscribeTab(props.tabId)+}++const activeGQLHeadersCount = computed(+ () =>+ request.value.headers.filter(+ (x) => x.active && (x.key !== "" || x.value !== "")+ ).length+)++const runQuery = async (+ definition: gql.OperationDefinitionNode | null = null+) => {+ if (!props.tabId) return+ const startTime = Date.now()+ startPageProgress()+ // Hoisted so the catch can tell subscription runs apart — their+ // testResults must stay untouched on failure too+ let runDefinition: gql.OperationDefinitionNode | null = null+ try {+ const runURL = clone(props.url)+ const runQueryStr = clone(request.value.query)+ const runVariables = clone(request.value.variables)+ // Cursor-less invocations (ctrl-enter, unparseable-at-cursor) pass no+ // definition — derive it from the document being run, or the run would+ // execute and STAMP saved examples as operationType "query" regardless+ // of the actual operation+ runDefinition =+ definition ??+ (() => {+ try {+ return (+ gql+ .parse(runQueryStr)+ .definitions.find(+ (d): d is gql.OperationDefinitionNode =>+ d.kind === "OperationDefinition"+ ) ?? null+ )+ } catch (_e) {+ return null+ }+ })()+ // Deep-freeze the whole request at click time (like url/query/variables)+ // so edits during the run's awaits can't change what's sent — auth+ // editors mutate nested fields in place, so a shallow clone wouldn't hold+ const runRequest = cloneDeep(request.value) as HoppGQLRequest+ const runInheritedAuth = cloneDeep(+ props.inheritedProperties?.auth.inheritedAuth+ ) as HoppGQLAuth | undefined++ const inheritedHeaders = cloneDeep(+ props.inheritedProperties?.headers.map(+ (header) => header.inheritedHeader+ ) ?? []+ )+ const runInheritedVariables = cloneDeep(+ props.inheritedProperties?.variables+ )+ const runInheritedScripts = cloneDeep(props.inheritedProperties?.scripts)++ // `testResults` — including the in-flight `null` sentinel — is written by+ // GQLTabConnectionService (see `setTabTestResults`). It can't be emitted+ // from here: the response pane is gated behind `testResults !== null`, and+ // this component unmounts whenever its tab isn't the active one, so a run+ // finishing in the background would strand the sentinel and leave the+ // Results pane spinning until the next run.+ const runResult = await gqlTabConn.runTabGQLOperation(props.tabId, {+ name: runRequest.name,+ url: runURL,+ request: runRequest,+ inheritedHeaders,+ inheritedAuth: runInheritedAuth,+ inheritedVariables: runInheritedVariables,+ inheritedScripts: runInheritedScripts,+ query: runQueryStr,+ variables: runVariables,+ operationName: runDefinition?.name?.value,+ operationType: runDefinition?.operation ?? "query",+ // A scoped env list is only ever passed by embeds — isolate their+ // runs from the viewer's stored environments too+ isolatedEnvs: props.envs !== undefined,+ })++ const duration = Date.now() - startTime+ completePageProgress()+ if (runResult?.preScriptFailed) {+ // No request was sent — a success toast would contradict the script+ // error shown in the response panel (REST's script_fail behavior)+ toast.error(`${t("error.script_fail")}`)+ } else {+ // Subscriptions only just OPENED at this point (runTabGQLOperation+ // returns as soon as the socket is initiated) — "finished in Xms" would+ // be false; the response panel's subscribing/streaming states carry the+ // feedback instead+ if (runDefinition?.operation !== "subscription") {+ toast.success(`${t("state.finished_in", { duration })}`)+ }+ // `auth` is always truthy (authType "none" included) — only toast when+ // auth actually rode the connection_init payload (same snapshot the+ // operation received)+ const auth = runRequest.auth+ const effectiveAuth =+ auth.authType === "inherit" ? runInheritedAuth : auth+ if (+ runDefinition?.operation === "subscription" &&+ effectiveAuth &&+ effectiveAuth.authActive &&+ effectiveAuth.authType !== "none" &&+ effectiveAuth.authType !== "inherit"+ ) {+ toast.success(t("authorization.graphql_headers"))+ }+ }+ } catch (e: any) {+ completePageProgress()+ console.error(e)+ }+ platform.analytics?.logEvent({+ type: "HOPP_REQUEST_RUN",+ platform: "graphql-query",+ strategy: interceptorService.current.value!.id,+ })+}++if (props.tabId) {+ const tabMessageEvent = gqlTabConn.getTabMessageEvent(props.tabId)+ watch(+ () => tabMessageEvent.value,+ (event) => {+ if (event === "reset") {+ emit("update:response", [])+ return+ }++ if (!event) return++ try {+ // A subscription stream accumulates into the log; anything else —+ // query/mutation result or a run-level error — concludes a discrete+ // run and replaces the panel. Events carry the operationType of the+ // run they belong to, so a query failure replaces even while an+ // older subscription log is still on screen. Subscription events+ // append only when their log is actually rendered (the renderers+ // key off `response[0]`) and replace otherwise — errors stay+ // visible instead of hiding behind a stale result, and a stream+ // whose log was displaced (e.g. by a connection error) restores+ // itself on the next frame.+ const current = props.response ?? []+ const head = current[0]+ const logOnScreen =+ head?.type === "response" && head.operationType === "subscription"+ const appendsToLog =+ event.operationType === "subscription" && logOnScreen+ emit("update:response", appendsToLog ? [...current, event] : [event])+ } catch (error) {+ console.error(error)+ }+ },+ { deep: true }+ )++ watch(+ () => {+ const ctx = gqlTabConn.getTabConnectionState(props.tabId)+ return { error: ctx.error, state: ctx.state }+ },+ (newVal) => {+ if (+ newVal.error &&+ (newVal.state === "DISCONNECTED" || newVal.state === "ERROR")+ ) {+ const response = [+ {+ type: "error",+ error: {+ message: newVal.error.message(t),+ type: newVal.error.type,+ component: newVal.error.component,+ },+ },+ ]+ emit("update:response", response)+ }+ },+ { deep: true }+ )+}++const updateCursorPos = (pos: number) => {+ emit("cursor-position", pos)+}++const clearGQLQuery = () => {+ request.value.query = ""+}++const changeOptionTab = (e: GQLOptionTabs) => {+ selectedOptionTab.value = e+}++const runActionsActive = computed(() => props.showRunActions)+defineActionHandler("request.send-cancel", runQuery, runActionsActive)+defineActionHandler("request.reset", clearGQLQuery, runActionsActive)++defineActionHandler("request.open-tab", ({ tab }) => {+ selectedOptionTab.value = tab as GQLOptionTabs+})+</script>++<style lang="scss" scoped>+:deep(.cm-panels) {+ @apply top-upperPrimaryStickyFold #{!important};+}+</style>diff --git a/packages/hoppscotch-common/src/components/gql/RequestTab.vue b/packages/hoppscotch-common/src/components/gql/RequestTab.vuenew file mode 100644index 000000000..5f6d317dd--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/RequestTab.vue@@ -0,0 +1,57 @@+<template>+ <AppPaneLayout layout-id="gql-in-rest-primary">+ <template #primary>+ <GqlRequest v-model="tab" />+ <GqlRequestOptions+ v-model="tab.document.request"+ v-model:response="tab.document.response"+ v-model:test-results="tab.document.testResults"+ v-model:option-tab="tab.document.optionTabPreference"+ :inherited-properties="tab.document.inheritedProperties"+ :tab-id="tab.id"+ :url="tab.document.request.url"+ @cursor-position="(pos) => (tab.document.cursorPosition = pos)"+ />+ </template>+ <template #secondary>+ <GqlResponse+ v-model:document="tab.document"+ :response="tab.document.response"+ :tab-id="tab.id"+ />+ </template>+ </AppPaneLayout>+</template>++<script setup lang="ts">+import { useVModel } from "@vueuse/core"+import { cloneDeep } from "lodash-es"+import { watch } from "vue"+import { isEqualHoppGQLRequest } from "~/helpers/graphql"+import { HoppGQLRequestDocument } from "~/helpers/tab/document"+import { HoppTab } from "~/services/tab"++const props = defineProps<{ modelValue: HoppTab<HoppGQLRequestDocument> }>()++const emit = defineEmits<{+ (e: "update:modelValue", val: HoppTab<HoppGQLRequestDocument>): void+}>()++const tab = useVModel(props, "modelValue", emit)++// --- Dirty checking ---+let oldRequest = cloneDeep(tab.value.document.request)+watch(+ () => tab.value.document.request,+ (updatedValue) => {+ if (+ !tab.value.document.isDirty &&+ !isEqualHoppGQLRequest(oldRequest, updatedValue)+ ) {+ tab.value.document.isDirty = true+ }+ oldRequest = cloneDeep(updatedValue)+ },+ { deep: true }+)+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Response.vue b/packages/hoppscotch-common/src/components/gql/Response.vuenew file mode 100644index 000000000..3a92e707e--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Response.vue@@ -0,0 +1,498 @@+<template>+ <div class="flex flex-1 flex-col overflow-auto whitespace-nowrap">+ <GqlResponseMeta+ v-if="!isSubscriptionView"+ :response="response"+ :tab-id="tabId"+ :is-loading="isTestResultsLoading"+ />+ <HoppSmartTabs+ v-if="+ !isTestResultsLoading &&+ response &&+ response.length === 1 &&+ response[0].type === 'response' &&+ response[0].operationType !== 'subscription'+ "+ v-model="selectedResponseTab"+ styles="sticky overflow-x-auto flex-shrink-0 bg-primary top-lowerPrimaryStickyFold z-10"+ render-inactive-tabs+ >+ <HoppSmartTab :id="'response'" :label="`${t('response.title')}`">+ <div class="flex flex-1 flex-col">+ <div+ class="sticky top-lowerSecondaryStickyFold z-10 flex flex-shrink-0 items-center justify-between overflow-x-auto border-b border-dividerLight bg-primary pl-4"+ >+ <label class="truncate font-semibold text-secondaryLight">+ {{ t("response.body") }}+ </label>+ <div class="flex items-center">+ <HoppButtonSecondary+ v-if="document"+ v-tippy="{ theme: 'tooltip', allowHTML: true }"+ :title="+ isSavable+ ? `${t(+ 'response.save_as_example'+ )} <kbd>${getSpecialKey()}</kbd><kbd>E</kbd>`+ : t('response.please_save_request')+ "+ :icon="IconSave"+ :class="{+ 'opacity-75 cursor-not-allowed select-none': !isSavable,+ }"+ @click="isSavable ? onSaveAsExampleClick() : null"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('state.linewrap')"+ :class="{ '!text-accent': WRAP_LINES }"+ :icon="IconWrapText"+ @click.prevent="+ toggleNestedSetting('WRAP_LINES', 'graphqlResponseBody')+ "+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip', allowHTML: true }"+ :title="`${t(+ 'action.download_file'+ )} <kbd>${getSpecialKey()}</kbd><kbd>J</kbd>`"+ :icon="downloadIcon"+ @click="downloadResponse"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip', allowHTML: true }"+ :title="`${t(+ 'action.copy'+ )} <kbd>${getSpecialKey()}</kbd><kbd>.</kbd>`"+ :icon="copyIcon"+ @click="copyResponse"+ />+ <tippy+ interactive+ trigger="click"+ theme="popover"+ :on-shown="() => copyInterfaceTippyActions.focus()"+ >+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.more')"+ :icon="IconMore"+ />+ <template #content="{ hide }">+ <div+ ref="copyInterfaceTippyActions"+ class="flex flex-col focus:outline-none"+ tabindex="0"+ @keyup.escape="hide()"+ >+ <HoppSmartItem+ :label="t('response.generate_data_schema')"+ :icon="IconNetwork"+ @click="+ () => {+ invokeAction('response.schema.toggle')+ hide()+ }+ "+ />+ </div>+ </template>+ </tippy>+ </div>+ </div>+ <div class="h-full relative overflow-auto flex flex-col flex-1">+ <div ref="schemaEditor" class="absolute inset-0 h-full"></div>+ </div>+ </div>+ </HoppSmartTab>+ <HoppSmartTab+ v-if="document !== undefined"+ :id="'results'"+ :label="`${t('test.results')}`"+ :indicator="testResultsIndicator"+ >+ <HttpTestResult+ v-model="testResultsModel"+ :is-loading="isTestResultsLoading"+ />+ </HoppSmartTab>+ <HoppSmartTab+ v-if="showConsoleTab"+ id="console"+ label="Console"+ class="flex flex-1 flex-col"+ >+ <ConsolePanel :messages="consoleEntries" />+ </HoppSmartTab>+ </HoppSmartTabs>+ <div+ v-else-if="+ response &&+ response.length > 0 &&+ response[0].type === 'response' &&+ response[0].operationType === 'subscription'+ "+ class="flex flex-1 flex-col"+ >+ <GqlSubscriptionLog :log="response" @delete="clearSubscriptionLog" />+ </div>+ <div+ v-else-if="subscriptionPending"+ class="flex flex-1 flex-col items-center justify-center gap-3 p-6 text-secondaryLight"+ >+ <HoppSmartSpinner />+ <span>{{ subscriptionPendingLabel }}</span>+ </div>+ </div>+ <HttpSaveResponseName+ v-model:response-name="responseName"+ :has-same-name-response="hasSameNameResponse"+ :show="showSaveResponseName"+ @submit="onSaveAsExample"+ @hide-modal="showSaveResponseName = false"+ />+</template>++<script setup lang="ts">+import IconWrapText from "~icons/lucide/wrap-text"+import IconNetwork from "~icons/lucide/network"+import IconMore from "~icons/lucide/more-horizontal"+import IconSave from "~icons/lucide/save"+import { computed, reactive, ref, watch } from "vue"+import { useVModel } from "@vueuse/core"+import { useService } from "dioc/vue"+import {+ HoppGQLRequestResponse,+ HoppGQLResponseOriginalRequest,+ makeHoppGQLResponseOriginalRequest,+} from "@hoppscotch/data"+import { useCodemirror } from "@composables/codemirror"+import { useI18n } from "@composables/i18n"+import { useToast } from "@composables/toast"+import { defineActionHandler, invokeAction } from "~/helpers/actions"+import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"+import {+ GQLResponseEvent,+ GQLTabConnectionService,+} from "~/services/gql-tab-connection.service"+import { useNestedSetting, useSetting } from "~/composables/settings"+import { toggleNestedSetting } from "~/newstore/settings"+import {+ useCopyResponse,+ useDownloadResponse,+} from "~/composables/lens-actions"+import { editRESTRequest } from "~/newstore/collections"+import { HoppGQLRequestDocument } from "~/helpers/tab/document"+import { runMutation } from "~/helpers/backend/GQLClient"+import { UpdateRequestDocument } from "~/helpers/backend/graphql"+import * as E from "fp-ts/Either"++const t = useI18n()+const toast = useToast()++const props = withDefaults(+ defineProps<{+ response: GQLResponseEvent[] | null+ tabId?: string+ document?: HoppGQLRequestDocument+ }>(),+ {+ response: null,+ tabId: undefined,+ document: undefined,+ }+)++const emit = defineEmits<{+ (e: "update:document", val: HoppGQLRequestDocument): void+}>()++const doc = useVModel(props, "document", emit)++const gqlTabConn = useService(GQLTabConnectionService)++// --- Test results tab ---++const selectedResponseTab = ref<string>(+ props.document?.responseTabPreference ?? "response"+)+watch(selectedResponseTab, (tab) => {+ if (doc.value) doc.value.responseTabPreference = tab+})++const testResultsModel = computed({+ get: () => doc.value?.testResults,+ // `null` is reserved for "run in flight" — the clear button's null write+ // maps to undefined so it shows the empty state, not an eternal spinner+ set: (val) => {+ if (doc.value) doc.value.testResults = val === null ? undefined : val+ },+})++const isTestResultsLoading = computed(() => doc.value?.testResults === null)++// Save-as-example needs a persisted request to write into — mirror the REST+// renderer's disabled affordance for unsaved requests+const isSavable = computed(() => !!doc.value?.saveContext)++const EXPERIMENTAL_SCRIPTING_SANDBOX = useSetting(+ "EXPERIMENTAL_SCRIPTING_SANDBOX"+)++const showConsoleTab = computed(() => {+ const entries = doc.value?.testResults?.consoleEntries+ return !!entries && entries.length > 0 && EXPERIMENTAL_SCRIPTING_SANDBOX.value+})++const consoleEntries = computed(() => {+ const entries = doc.value?.testResults?.consoleEntries ?? []+ return entries.filter(({ type }) =>+ ["log", "warn", "debug", "error", "info"].includes(type)+ )+})++// The Console tab unmounts when a run produces no console output — a stale+// "console" selection (in-session or restored via responseTabPreference)+// would leave the panel blank+watch(+ showConsoleTab,+ (visible) => {+ if (!visible && selectedResponseTab.value === "console") {+ selectedResponseTab.value = "response"+ }+ },+ { immediate: true }+)++const testResultsIndicator = computed(() => {+ const results = doc.value?.testResults+ if (!results) return false+ return Boolean(+ results.expectResults.length ||+ results.tests.length ||+ results.envDiff.selected.additions.length ||+ results.envDiff.selected.updations.length ||+ results.envDiff.global.updations.length+ )+})++// `subscriptionPending` is true when a subscription has been initiated and+// the server hasn't pushed any data yet — covers both the SUBSCRIBING window+// (waiting for connection_ack) and the post-ack idle window (subscribed but+// no events yet). Used to render a loading state instead of a blank panel.+const subscriptionPending = computed(() => {+ if (!props.tabId) return false+ const state = gqlTabConn.getTabSubscriptionState(props.tabId).value+ if (state !== "SUBSCRIBING" && state !== "SUBSCRIBED") return false+ // Already have data → let the subscription log render.+ if (props.response && props.response.length > 0) return false+ return true+})++const subscriptionPendingLabel = computed(() => {+ const state = props.tabId+ ? gqlTabConn.getTabSubscriptionState(props.tabId).value+ : undefined+ return state === "SUBSCRIBING"+ ? t("graphql.subscribing")+ : t("graphql.waiting_for_events")+})++// True whenever the response panel is in any subscription-specific state —+// loading, waiting for events, or rendering the subscription log. Used to+// hide the REST/query-style response meta header bar that doesn't apply.+const isSubscriptionView = computed(() => {+ if (subscriptionPending.value) return true+ const first = props.response?.[0]+ return (+ !!first &&+ first.type === "response" &&+ first.operationType === "subscription"+ )+})++const clearSubscriptionLog = () => {+ if (!doc.value) return+ // Empty array (not null) keeps the loading/waiting branch active when the+ // subscription is still live — a fresh `[]` lets the post-ack idle state+ // render "Waiting for events…" instead of dropping to a blank panel.+ doc.value.response = []+}++const responseString = computed(() => {+ const response = props.response+ if (!response || response.length === 0) return ""+ if (response[0].type === "error") return ""+ if (+ response.length === 1 &&+ response[0].type === "response" &&+ response[0].data+ ) {+ // The payload is server-controlled, so it is not guaranteed to be JSON+ // (error pages, truncated bodies, non-JSON content types). Throwing here+ // would take down the whole response panel, so fall back to the raw text.+ try {+ return JSON.stringify(JSON.parse(response[0].data), null, 2)+ } catch {+ return response[0].data+ }+ }+ return ""+})++const schemaEditor = ref<any | null>(null)+const WRAP_LINES = useNestedSetting("WRAP_LINES", "graphqlResponseBody")+const copyInterfaceTippyActions = ref<any | null>(null)++useCodemirror(+ schemaEditor,+ responseString,+ reactive({+ extendedEditorConfig: {+ mode: "application/ld+json",+ readOnly: true,+ lineWrapping: WRAP_LINES,+ },+ linter: null,+ completer: null,+ environmentHighlights: false,+ })+)++const { copyIcon, copyResponse } = useCopyResponse(responseString)+const { downloadIcon, downloadResponse } = useDownloadResponse(+ "application/json",+ responseString,+ t("filename.graphql_response")+)++defineActionHandler(+ "response.file.download",+ () => downloadResponse(),+ computed(() => !!props.response && props.response.length > 0)+)+defineActionHandler(+ "response.copy",+ () => copyResponse(),+ computed(() => !!props.response && props.response.length > 0)+)+defineActionHandler(+ "response.save-as-example",+ () => onSaveAsExampleClick(),+ computed(() => !!doc.value && !!responseString.value && isSavable.value)+)++const responseName = ref("")+const showSaveResponseName = ref(false)++const hasSameNameResponse = computed(() => {+ if (!responseName.value || !doc.value) return false+ return responseName.value in doc.value.request.responses+})++const onSaveAsExampleClick = () => {+ if (!doc.value) return+ showSaveResponseName.value = true+ responseName.value = doc.value.request.name+}++const onSaveAsExample = () => {+ if (!doc.value || !props.response || props.response.length !== 1) return++ const event = props.response[0]+ if (event.type !== "response") return++ const req = doc.value.request++ const originalRequest: HoppGQLResponseOriginalRequest =+ makeHoppGQLResponseOriginalRequest({+ name: req.name,+ url: req.url,+ query: req.query,+ variables: req.variables,+ headers: req.headers,+ auth: req.auth,+ })++ const resName = responseName.value.trim()++ const responseObj: HoppGQLRequestResponse = {+ name: resName,+ originalRequest,+ status: event.document?.statusText ?? "",+ code: event.document?.statusCode ?? null,+ // GQL response transport headers are not currently surfaced by the+ // tab-connection service; persist an empty list. If the service later+ // exposes them, this is where they'd land.+ headers: [],+ body: event.data,+ // Operation identity for the mock server's GraphQL matcher — the+ // DB trigger projects these into `mockExamples`+ operationName: event.operationName,+ operationType: event.operationType,+ }++ doc.value.request.responses = {+ ...doc.value.request.responses,+ [resName]: responseObj,+ }++ showSaveResponseName.value = false++ const saveCtx = doc.value.saveContext+ if (!saveCtx) {+ responseName.value = ""+ return+ }++ // Unified workspace: GQL request bodies are stored in REST collection rows,+ // so personal-workspace saves go through the REST store / REST mutation+ // (mirrors `editRequest` in the personal sync layer).+ if (saveCtx.originLocation === "user-collection") {+ // `requestIndex` is optional on the save-context union (example tabs+ // omit it). Without it there is no collection row to write to — treat+ // it like a missing saveContext: the example still lives on the open+ // tab's request, it just isn't persisted to the collection.+ if (saveCtx.requestIndex === undefined) {+ responseName.value = ""+ return+ }+ try {+ editRESTRequest(+ saveCtx.folderPath,+ saveCtx.requestIndex,+ doc.value.request+ )+ toast.success(`${t("response.saved")}`)+ } catch (e) {+ console.error(e)+ }+ responseName.value = ""+ return+ }++ if (saveCtx.originLocation === "team-collection") {+ runMutation(UpdateRequestDocument, {+ requestID: saveCtx.requestID,+ data: {+ title: doc.value.request.name,+ request: JSON.stringify(doc.value.request),+ },+ })().then((result) => {+ if (E.isLeft(result)) {+ toast.error(`${t("profile.no_permission")}`)+ } else {+ // The example is persisted — clear the dirty flag like the REST+ // sibling (http/Response.vue) does+ if (doc.value) doc.value.isDirty = false+ toast.success(`${t("response.saved")}`)+ }+ responseName.value = ""+ })+ return+ }++ responseName.value = ""+}+</script>diff --git a/packages/hoppscotch-common/src/components/gql/ResponseMeta.vue b/packages/hoppscotch-common/src/components/gql/ResponseMeta.vuenew file mode 100644index 000000000..dcd140d8a--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/ResponseMeta.vue@@ -0,0 +1,182 @@+<template>+ <div+ class="sticky top-0 z-10 flex flex-shrink-0 items-center justify-center overflow-auto overflow-x-auto whitespace-nowrap bg-primary p-4"+ >+ <div+ v-if="isLoading"+ class="flex flex-1 flex-col items-center justify-center"+ >+ <HoppSmartSpinner class="my-4" />+ <span class="text-secondaryLight">{{ t("state.loading") }}</span>+ </div>++ <AppShortcutsPrompt+ v-else-if="(response == null || response.length === 0) && !isEmbed"+ class="flex-1"+ documentation-url="https://docs.hoppscotch.io/documentation/features/graphql-api-testing"+ />++ <div v-else-if="response == null || response.length === 0">+ <HoppButtonSecondary+ :label="`${t('app.documentation')}`"+ to="https://docs.hoppscotch.io/documentation/features/graphql-api-testing"+ :icon="IconExternalLink"+ blank+ outline+ reverse+ />+ </div>++ <div v-else class="flex flex-1 flex-col">+ <HoppSmartPlaceholder+ v-if="errorResponse?.error?.component"+ :src="`/images/states/${colorMode.value}/upload_error.svg`"+ :alt="t('error.network_fail')"+ :heading="t('error.network_fail')"+ :text="errorResponse.error.message || t('helpers.network_fail')"+ >+ <template #body>+ <AppKernelInterceptor+ class="rounded border border-dividerLight p-2"+ />+ </template>+ </HoppSmartPlaceholder>++ <HoppSmartPlaceholder+ v-if="errorResponse && !errorResponse.error.component"+ :src="`/images/states/${colorMode.value}/upload_error.svg`"+ :alt="errorResponse.error.message || t('error.network_fail')"+ :heading="errorResponse.error.message || t('error.network_fail')"+ :text="errorResponse.error.message || t('error.network_fail')"+ >+ <template #body>+ <AppKernelInterceptor+ class="rounded border border-dividerLight p-2"+ />+ </template>+ </HoppSmartPlaceholder>++ <div+ v-if="successResponse"+ class="flex items-center text-tiny font-semibold"+ >+ <div+ :class="statusCategory.className"+ class="inline-flex flex-1 space-x-4"+ >+ <span v-if="successResponse.document?.statusCode">+ <span class="text-secondary"> {{ t("response.status") }}: </span>+ {{ `${successResponse.document.statusCode}\xA0 • \xA0`+ }}{{+ getStatusCodeReasonPhrase(+ successResponse.document.statusCode,+ successResponse.document.statusText+ )+ }}+ </span>+ <span v-if="successResponse.document?.meta?.responseDuration">+ <span class="text-secondary"> {{ t("response.time") }}: </span>+ {{ `${successResponse.document.meta.responseDuration} ms` }}+ </span>+ <span+ v-if="successResponse.document?.meta?.responseSize"+ v-tippy="+ readableResponseSize+ ? { theme: 'tooltip' }+ : { onShow: () => false }+ "+ :title="`${successResponse.document.meta.responseSize} B`"+ >+ <span class="text-secondary"> {{ t("response.size") }}: </span>+ {{+ readableResponseSize+ ? readableResponseSize+ : `${successResponse.document.meta.responseSize} B`+ }}+ </span>+ </div>+ </div>+ </div>+ <AppInspection+ v-if="!isLoading"+ :inspection-results="tabResults"+ :class="[+ !response || response.length === 0 || errorResponse+ ? 'absolute right-2 top-2'+ : '-m-2 ml-2',+ ]"+ />+ </div>+</template>++<script setup lang="ts">+import { computed } from "vue"+import findStatusGroup from "@helpers/findStatusGroup"+import type { GQLResponseEvent } from "~/services/gql-tab-connection.service"+import { useI18n } from "@composables/i18n"+import { useColorMode } from "@composables/theming"+import { getStatusCodeReasonPhrase } from "~/helpers/utils/statusCodes"+import { useService } from "dioc/vue"+import { InspectionService } from "~/services/inspection"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"+import IconExternalLink from "~icons/lucide/external-link"++const t = useI18n()+const colorMode = useColorMode()+const tabs = useService(WorkspaceTabsService)++const props = defineProps<{+ response: GQLResponseEvent[] | null | undefined+ isEmbed?: boolean+ tabId?: string+ // Driven by the run-in-flight signal (doc.testResults === null) — the+ // response prop keeps the PREVIOUS run's data during a re-run+ isLoading?: boolean+}>()++const successResponse = computed(() => {+ if (!props.response || props.response.length === 0) return null+ const responses = props.response.filter((r) => r.type === "response")+ if (responses.length === 0) return null+ return responses[responses.length - 1]+})++const errorResponse = computed(() => {+ if (!props.response || props.response.length === 0) return null+ const firstResponse = props.response[0]+ return firstResponse?.type === "error" ? firstResponse : null+})++const readableResponseSize = computed(() => {+ if (!successResponse.value?.document?.meta?.responseSize) return undefined++ const size = successResponse.value.document.meta.responseSize++ if (size >= 100000) return (size / 1000000).toFixed(2) + " MB"+ if (size >= 1000) return (size / 1000).toFixed(2) + " KB"++ return undefined+})++const statusCategory = computed(() => {+ if (!successResponse.value?.document?.statusCode) {+ return {+ name: "error",+ className: "text-red-500",+ }+ }+ return findStatusGroup(successResponse.value.document.statusCode)+})++const inspectionService = useService(InspectionService)++// Re-derived per tab change — a setup-time capture of `currentTabID` would+// pin inspection results to whichever tab was active at mount+const tabResults = computed(+ () =>+ inspectionService.getResultViewFor(+ props.tabId ?? tabs.currentTabID.value,+ (result) => result.locations.type === "response"+ ).value+)+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Schema.vue b/packages/hoppscotch-common/src/components/gql/Schema.vuenew file mode 100644index 000000000..f61b6f15a--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Schema.vue@@ -0,0 +1,135 @@+<template>+ <div+ v-if="schemaString"+ class="sticky top-0 z-10 flex flex-shrink-0 items-center justify-between overflow-x-auto border-b border-dividerLight bg-primary pl-4"+ >+ <label class="truncate font-semibold text-secondaryLight">+ {{ t("graphql.schema") }}+ </label>+ <div class="flex">+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ to="https://docs.hoppscotch.io/documentation/protocols/graphql"+ blank+ :title="t('app.wiki')"+ :icon="IconHelpCircle"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('state.linewrap')"+ :class="{ '!text-accent': WRAP_LINES }"+ :icon="IconWrapText"+ @click.prevent="toggleNestedSetting('WRAP_LINES', 'graphqlSchema')"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.download_file')"+ :icon="downloadSchemaIcon"+ @click="downloadSchema"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.copy')"+ :icon="copySchemaIcon"+ @click="copySchema"+ />+ </div>+ </div>+ <div v-if="schemaString" class="h-full relative w-full">+ <div ref="schemaEditor" class="absolute inset-0"></div>+ </div>+ <HoppSmartPlaceholder+ v-else+ :src="`/images/states/${colorMode.value}/blockchain.svg`"+ :alt="`${t('empty.schema')}`"+ :text="t('empty.schema')"+ >+ </HoppSmartPlaceholder>+</template>++<script setup lang="ts">+import { reactive, ref } from "vue"+import { refAutoReset } from "@vueuse/core"+import { useCodemirror } from "@composables/codemirror"+import { useI18n } from "@composables/i18n"+import { useColorMode } from "@composables/theming"+import { useToast } from "@composables/toast"+import { copyToClipboard } from "@helpers/utils/clipboard"+import { useService } from "dioc/vue"+import IconCheck from "~icons/lucide/check"+import IconCopy from "~icons/lucide/copy"+import IconDownload from "~icons/lucide/download"+import IconHelpCircle from "~icons/lucide/help-circle"+import IconWrapText from "~icons/lucide/wrap-text"+import { useNestedSetting } from "~/composables/settings"+import { toggleNestedSetting } from "~/newstore/settings"+import { platform } from "~/platform"+import { GQLTabConnectionService } from "~/services/gql-tab-connection.service"++const t = useI18n()+const toast = useToast()+const colorMode = useColorMode()++const gqlTabConn = useService(GQLTabConnectionService)++const schemaString = gqlTabConn.activeTabSchemaString++const downloadSchemaIcon = refAutoReset<typeof IconDownload | typeof IconCheck>(+ IconDownload,+ 1000+)+const copySchemaIcon = refAutoReset<typeof IconCopy | typeof IconCheck>(+ IconCopy,+ 1000+)++const schemaEditor = ref<any | null>(null)+const WRAP_LINES = useNestedSetting("WRAP_LINES", "graphqlSchema")++useCodemirror(+ schemaEditor,+ schemaString,+ reactive({+ extendedEditorConfig: {+ mode: "graphql",+ readOnly: true,+ lineWrapping: WRAP_LINES,+ },+ linter: null,+ completer: null,+ environmentHighlights: false,+ })+)++const downloadSchema = async () => {+ const result = await platform.kernelIO.saveFileWithDialog({+ data: schemaString.value,+ contentType: "application/graphql",+ suggestedFilename: "schema.graphql",+ filters: [+ {+ name: "GraphQL Schema File",+ extensions: ["graphql"],+ },+ ],+ })++ if (result.type === "unknown" || result.type === "saved") {+ downloadSchemaIcon.value = IconCheck+ toast.success(`${t("state.download_started")}`)+ }+}++const copySchema = () => {+ if (!schemaString.value) return++ copyToClipboard(schemaString.value)+ copySchemaIcon.value = IconCheck+}+</script>++<style lang="scss" scoped>+:deep(.cm-panels) {+ @apply top-sidebarPrimaryStickyFold #{!important};+}+</style>diff --git a/packages/hoppscotch-common/src/components/gql/SchemaDocumentation.vue b/packages/hoppscotch-common/src/components/gql/SchemaDocumentation.vuenew file mode 100644index 000000000..ba3b42cf8--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/SchemaDocumentation.vue@@ -0,0 +1,106 @@+<template>+ <div class="flex flex-col">+ <AppMarkdown+ v-if="schemaDescription"+ type="description"+ class="text-secondary leading-relaxed px-4 py-3"+ >+ {{ schemaDescription }}+ </AppMarkdown>++ <GqlExplorerSection title="Root Types">+ <div+ v-if="queryType"+ class="group flex items-center gap-2 cursor-pointer px-4 py-2 transition hover:bg-primaryLight"+ @click="handleTypeClick(queryType)"+ >+ <span class="text-sm font-medium text-accent">+ {{ t("graphql.query") }}+ </span>+ <span class="text-secondaryLight">:</span>+ <GqlTypeLink :type="queryType" />+ </div>+ <div+ v-if="mutationType"+ class="group flex items-center gap-2 cursor-pointer px-4 py-2 transition hover:bg-primaryLight"+ @click="handleTypeClick(mutationType)"+ >+ <span class="text-sm font-medium text-accent">+ {{ t("graphql.mutation") }}+ </span>+ <span class="text-secondaryLight">:</span>+ <GqlTypeLink :type="mutationType" />+ </div>+ <div+ v-if="subscriptionType"+ class="group flex items-center gap-2 cursor-pointer px-4 py-2 transition hover:bg-primaryLight"+ @click="handleTypeClick(subscriptionType)"+ >+ <span class="text-sm font-medium text-accent">+ {{ t("graphql.subscription") }}+ </span>+ <span class="text-secondaryLight">:</span>+ <GqlTypeLink :type="subscriptionType" />+ </div>+ </GqlExplorerSection>++ <GqlExplorerSection title="All Schema Types">+ <div+ v-for="type in filteredTypes"+ :key="type.name"+ class="px-4 py-2 transition hover:bg-primaryLight"+ >+ <GqlTypeLink :type="type" :clickable="true" :readonly="true" />+ </div>+ </GqlExplorerSection>+ </div>+</template>++<script setup lang="ts">+import { computed } from "vue"+import type { GraphQLNamedType, GraphQLSchema } from "graphql"+import { useExplorer } from "~/helpers/graphql/explorer"+import { useI18n } from "~/composables/i18n"++const props = defineProps<{+ schema: GraphQLSchema+}>()++const t = useI18n()++// Derive schema-shape via `computed` so this view tracks `props.schema`+// changes — e.g. when the parent tab's schema is refreshed by polling, or+// the user switches between connected GQL tabs faster than the parent's+// `:key` remount can settle. Capturing these once at setup left the UI+// pinned to the first schema we ever saw.+const queryType = computed(() => props.schema.getQueryType() ?? null)+const mutationType = computed(() => props.schema.getMutationType?.() ?? null)+const subscriptionType = computed(+ () => props.schema.getSubscriptionType?.() ?? null+)+const typeMap = computed(() => props.schema.getTypeMap())++const schemaDescription = computed(() => props.schema.description ?? "")++const { push } = useExplorer()++const handleTypeClick = (namedType: GraphQLNamedType) => {+ push({ name: namedType.name, def: namedType })+}++const ignoreTypesInAllSchema = computed(() => [+ queryType.value?.name,+ mutationType.value?.name,+ subscriptionType.value?.name,+])++const filteredTypes = computed(() => {+ if (!typeMap.value) return []++ return Object.values(typeMap.value).filter(+ (type) =>+ !ignoreTypesInAllSchema.value.includes(type.name) &&+ !type.name.startsWith("__")+ )+})+</script>diff --git a/packages/hoppscotch-common/src/components/gql/SchemaSearch.vue b/packages/hoppscotch-common/src/components/gql/SchemaSearch.vuenew file mode 100644index 000000000..7169a0d2c--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/SchemaSearch.vue@@ -0,0 +1,374 @@+<template>+ <div class="border-b border-dividerLight autocomplete-wrapper">+ <div ref="searchWrapper" class="no-scrollbar inset-0 flex flex-1">+ <input+ v-model="searchText"+ type="search"+ autocomplete="off"+ class="flex w-full bg-transparent px-3 py-2 h-8"+ :placeholder="t('action.search')"+ @keydown="handleSearchKeystroke"+ @focusin="showSearchResults = true"+ />+ </div>+ <ul+ v-if="showSearchResults && filteredResults.length > 0"+ ref="resultsMenu"+ class="suggestions"+ >+ <li+ v-for="(result, index) in filteredResults"+ :key="`result-${index}`"+ :class="{ active: currentResultIndex === index }"+ @click="selectSearchResult(result)"+ >+ <span class="truncate py-0.5">+ {{ result.name }}+ <span class="text-secondaryLight">- {{ result.type }}</span>+ </span>+ </li>+ </ul>+ </div>+</template>++<script setup lang="ts">+import type {+ GraphQLArgument,+ GraphQLField,+ GraphQLInputField,+ GraphQLNamedType,+} from "graphql"+import { isInputObjectType, isInterfaceType, isObjectType } from "graphql"+import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue"+import { useI18n } from "~/composables/i18n"+import { useService } from "dioc/vue"+import { GQLTabConnectionService } from "~/services/gql-tab-connection.service"+import { ExplorerNavStackItem, useExplorer } from "~/helpers/graphql/explorer"++// Types+type SearchResult = {+ name: string+ type: string+ def:+ | GraphQLNamedType+ | GraphQLField<unknown, unknown>+ | GraphQLInputField+ | GraphQLArgument+ // Set on "Argument in …" results — the label alone can't be resolved back+ // to a navigation path+ parentField?: GraphQLField<unknown, unknown>+ parentTypeName?: string+}++// Composables+const t = useI18n()+const { navStack, push, pop } = useExplorer()+const gqlTabConn = useService(GQLTabConnectionService)++// Read schema from the per-tab connection service+const schema = gqlTabConn.activeTabSchema++// Refs+const searchText = ref("")+const showSearchResults = ref(false)+const currentResultIndex = ref(-1)+const searchWrapper = ref<HTMLElement | null>(null)+const resultsMenu = ref<HTMLElement | null>(null)++// Search Results Generation+const generateSearchResults = () => {+ const results: SearchResult[] = []++ if (!schema.value) return results++ const typeMap = schema.value.getTypeMap()+ const typeNames = Object.keys(typeMap).filter(+ (name) => !name.startsWith("__")+ ) // Filter out __ types++ for (const typeName of typeNames) {+ if (results.length >= 100) break++ const type = typeMap[typeName]++ // Add type match+ if (typeName.toLowerCase().includes(searchText.value.toLowerCase())) {+ results.push({+ name: typeName,+ type: "Type",+ def: type,+ })+ }++ // Skip if not an object, interface, or input object type+ if (+ !isObjectType(type) &&+ !isInterfaceType(type) &&+ !isInputObjectType(type)+ ) {+ continue+ }++ // Search fields+ const fields = type.getFields()+ for (const fieldName in fields) {+ // Skip fields starting with __+ if (fieldName.startsWith("__")) continue++ const field = fields[fieldName]++ // Field name match+ if (fieldName.toLowerCase().includes(searchText.value.toLowerCase())) {+ results.push({+ name: fieldName,+ type: `Field in ${typeName}`,+ def: field,+ })+ }++ // Search arguments if applicable+ if ("args" in field) {+ field.args.forEach((arg) => {+ if (arg.name.toLowerCase().includes(searchText.value.toLowerCase())) {+ results.push({+ name: arg.name,+ type: `Argument in ${fieldName}`,+ def: arg,+ parentField: field,+ parentTypeName: typeName,+ })+ }+ })+ }+ }+ }++ return results+}++// Computed+const filteredResults = computed(() =>+ searchText.value.trim() ? generateSearchResults() : []+)++// Methods+const buildNavigationPath = (result: SearchResult): ExplorerNavStackItem[] => {+ const path: ExplorerNavStackItem[] = []++ if (result.type === "Type") {+ // For type results, traverse through schema to build proper path+ const type = result.def as GraphQLNamedType+ const rootTypes = {+ query: schema.value?.getQueryType(),+ mutation: schema.value?.getMutationType(),+ subscription: schema.value?.getSubscriptionType(),+ }++ // Check if the type is directly accessible from root types+ const rootEntry = Object.entries(rootTypes).find(+ ([, rootType]) => rootType?.name === type.name+ )++ if (rootEntry) {+ path.push({+ name: rootEntry[0].charAt(0).toUpperCase() + rootEntry[0].slice(1),+ def: type,+ })+ } else {+ // If not a root type, try to find the path through fields+ const parentType = Object.values(rootTypes).find((rootType) => {+ if (!rootType || !isObjectType(rootType)) return false+ const fields = rootType.getFields()+ return Object.values(fields).some((field) =>+ field.type.toString().includes(type.name)+ )+ })++ if (parentType) {+ path.push({+ name: parentType.name,+ def: parentType,+ })++ // Find the field that leads to our type+ const field = Object.values(parentType.getFields()).find((field) =>+ field.type.toString().includes(type.name)+ )++ if (field) {+ path.push({+ name: field.name,+ def: field,+ })+ }+ }++ path.push({+ name: type.name,+ def: type,+ })+ }+ } else if (result.type.startsWith("Field in")) {+ // For fields, ensure we have the complete path from root+ const parentTypeName = result.type.replace("Field in ", "")+ const parentType = schema.value?.getType(parentTypeName)++ if (parentType) {+ // First find path to parent type+ const parentPath = buildNavigationPath({+ name: parentType.name,+ type: "Type",+ def: parentType,+ })++ path.push(...parentPath)+ path.push({+ name: result.name,+ def: result.def,+ })+ }+ } else if (+ result.type.startsWith("Argument in") &&+ result.parentField &&+ result.parentTypeName+ ) {+ // Arguments render on their containing field's documentation page+ return buildNavigationPath({+ name: result.parentField.name,+ type: `Field in ${result.parentTypeName}`,+ def: result.parentField,+ })+ }++ return path+}++const selectSearchResult = (result: SearchResult) => {+ const navigationPath = buildNavigationPath(result)++ // Reset to root+ while (navStack.value.length > 1) {+ pop()+ }++ // Push each item in the path sequentially+ navigationPath.forEach((item) => push(item))++ showSearchResults.value = false+ searchText.value = ""+ currentResultIndex.value = -1+}++const scrollActiveResultIntoView = async () => {+ await nextTick()+ if (resultsMenu.value && currentResultIndex.value > -1) {+ const activeElement = resultsMenu.value.children[+ currentResultIndex.value+ ] as HTMLElement+ activeElement?.scrollIntoView({ block: "nearest" })+ }+}++const handleSearchKeystroke = (ev: KeyboardEvent) => {+ if (["ArrowDown", "ArrowUp", "Enter", "Escape"].includes(ev.key)) {+ ev.preventDefault()+ }++ if (["Escape", "Tab"].includes(ev.key)) {+ showSearchResults.value = false+ }++ // ArrowUp clamps the index to 0 even with no matches — guard the lookup+ if (+ ev.key === "Enter" &&+ currentResultIndex.value > -1 &&+ filteredResults.value[currentResultIndex.value]+ ) {+ selectSearchResult(filteredResults.value[currentResultIndex.value])+ }++ if (ev.key === "ArrowDown") {+ currentResultIndex.value =+ currentResultIndex.value < filteredResults.value.length - 1+ ? currentResultIndex.value + 1+ : filteredResults.value.length - 1+ scrollActiveResultIntoView()+ }++ if (ev.key === "ArrowUp") {+ currentResultIndex.value =+ currentResultIndex.value > 0 ? currentResultIndex.value - 1 : 0+ scrollActiveResultIntoView()+ }+}++// Click outside handling+const handleClickOutside = (event: MouseEvent) => {+ if (+ searchWrapper.value &&+ !searchWrapper.value.contains(event.target as Node)+ ) {+ showSearchResults.value = false+ }+}++// Add watch for searchText+watch(searchText, () => {+ currentResultIndex.value = -1+ if (searchText.value.trim()) {+ showSearchResults.value = true+ }+})++// Lifecycle+onMounted(() => {+ document.addEventListener("click", handleClickOutside)+})++onUnmounted(() => {+ document.removeEventListener("click", handleClickOutside)+})+</script>++<style lang="scss" scoped>+.autocomplete-wrapper {+ @apply relative;+ @apply whitespace-nowrap;++ .suggestions {+ @apply absolute;+ @apply bg-popover;+ @apply z-50;+ @apply shadow-lg;+ @apply max-h-46;+ @apply border-x border-b border-divider;+ @apply overflow-y-auto;+ @apply -left-[1px];+ @apply -right-[1px];++ top: calc(100% + 1px);+ border-radius: 0 0 8px 8px;++ li {+ @apply flex;+ @apply items-center;+ @apply justify-between;+ @apply w-full;+ @apply px-4 py-2;+ @apply text-secondary;+ @apply cursor-pointer;++ &:last-child {+ border-radius: 0 0 0 8px;+ }++ &:hover,+ &.active {+ @apply bg-primaryDark;+ @apply text-secondaryDark;+ @apply cursor-pointer;+ }+ }+ }+}+</style>diff --git a/packages/hoppscotch-common/src/components/gql/SubscriptionLog.vue b/packages/hoppscotch-common/src/components/gql/SubscriptionLog.vuenew file mode 100644index 000000000..a9f14852f--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/SubscriptionLog.vue@@ -0,0 +1,133 @@+<template>+ <div ref="container" class="flex flex-1 flex-col">+ <div+ class="sticky top-0 z-10 flex flex-none items-center justify-between border-b border-dividerLight bg-primary pl-4"+ >+ <label for="log" class="py-2 font-semibold text-secondaryLight">+ {{ t("graphql.subscription_log") }}+ </label>+ <div>+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.delete')"+ :icon="IconTrash"+ @click="emit('delete')"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.scroll_to_top')"+ :icon="IconArrowUp"+ @click="scrollTo('top')"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.scroll_to_bottom')"+ :icon="IconArrowDown"+ @click="scrollTo('bottom')"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.autoscroll')"+ :icon="IconChevronsDown"+ :class="toggleAutoscrollColor"+ @click="toggleAutoscroll()"+ />+ </div>+ </div>+ <div+ v-if="log.length !== 0"+ ref="logs"+ class="flex-1 min-h-0 overflow-y-auto border-b border-dividerLight"+ >+ <div+ class="flex h-auto h-full flex-col divide-y divide-dividerLight border-r border-dividerLight"+ >+ <RealtimeLogEntry+ v-for="(entry, index) in log"+ :key="+ entry.type === 'response'+ ? `entry-${entry.time}-${index}`+ : `error-${index}`+ "+ :entry="+ entry.type === 'response'+ ? { ts: entry.time, source: 'info', payload: entry.data }+ : {+ ts: undefined,+ source: 'disconnected',+ event: 'error',+ payload: entry.error.message,+ }+ "+ />+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { ref, PropType, computed, watch } from "vue"+import IconTrash from "~icons/lucide/trash"+import IconArrowUp from "~icons/lucide/arrow-up"+import IconArrowDown from "~icons/lucide/arrow-down"+import IconChevronsDown from "~icons/lucide/chevron-down"+import { useThrottleFn, useScroll } from "@vueuse/core"+import { useI18n } from "@composables/i18n"+import { GQLResponseEvent } from "~/services/gql-tab-connection.service"++const props = defineProps({+ log: { type: Array as PropType<GQLResponseEvent[]>, default: () => [] },+ title: {+ type: String,+ default: "",+ },+})++const emit = defineEmits<{+ (e: "delete"): void+}>()++const t = useI18n()++const container = ref<HTMLElement | null>(null)+const logs = ref<HTMLElement | null>(null)++const autoScrollEnabled = ref(true)++const logListScroll = useScroll(logs)++watch(logListScroll.isScrolling, (isScrolling) => {+ if (isScrolling && logListScroll.directions.top)+ autoScrollEnabled.value = false+})++const scrollTo = (position: "top" | "bottom") => {+ if (position === "top") {+ logs.value?.scroll({+ behavior: "smooth",+ top: 0,+ })+ } else if (position === "bottom") {+ logs.value?.scroll({+ behavior: "smooth",+ top: logs.value?.scrollHeight,+ })+ }+}++watch(+ () => props.log,+ useThrottleFn(() => {+ if (autoScrollEnabled.value) scrollTo("bottom")+ }, 200),+ { flush: "post" }+)++const toggleAutoscroll = () => {+ autoScrollEnabled.value = !autoScrollEnabled.value+}++const toggleAutoscrollColor = computed(() =>+ autoScrollEnabled.value ? "text-green-500" : "text-red-500"+)+</script>diff --git a/packages/hoppscotch-common/src/components/gql/TabHead.vue b/packages/hoppscotch-common/src/components/gql/TabHead.vuenew file mode 100644index 000000000..585a8e0b6--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/TabHead.vue@@ -0,0 +1,164 @@+<template>+ <div+ v-tippy="{ theme: 'tooltip', delay: [500, 20] }"+ :title="tabName"+ class="flex items-center truncate px-2"+ @dblclick="emit('open-rename-modal')"+ @contextmenu.prevent="options?.tippy?.show()"+ @click.middle="emit('close-tab')"+ >+ <component+ :is="IconGraphql"+ class="mr-2 h-4 w-4 text-accent"+ :class="{+ 'border border-dashed border-primaryDark grayscale p-0.5 rounded-sm':+ isResponseExample,+ }"+ />+ <tippy+ ref="options"+ trigger="manual"+ interactive+ theme="popover"+ :on-shown="() => tippyActions!.focus()"+ >+ <span class="truncate">+ {{ tabName }}+ </span>+ <template #content="{ hide }">+ <div+ ref="tippyActions"+ class="flex flex-col focus:outline-none"+ tabindex="0"+ @keyup.r="renameAction?.$el.click()"+ @keyup.d="duplicateAction?.$el.click()"+ @keyup.s="shareRequestAction?.$el.click()"+ @keyup.w="closeAction?.$el.click()"+ @keyup.x="closeOthersAction?.$el.click()"+ @keyup.escape="hide()"+ >+ <HoppSmartItem+ v-if="!isResponseExample"+ ref="renameAction"+ :icon="IconFileEdit"+ :label="t('request.rename')"+ :shortcut="['R']"+ @click="+ () => {+ emit('open-rename-modal')+ hide()+ }+ "+ />+ <HoppSmartItem+ v-if="!isResponseExample"+ ref="duplicateAction"+ :icon="IconCopy"+ :label="t('tab.duplicate')"+ :shortcut="['D']"+ @click="+ () => {+ emit('duplicate-tab')+ hide()+ }+ "+ />+ <HoppSmartItem+ v-if="!isResponseExample"+ ref="shareRequestAction"+ :icon="IconShare2"+ :label="t('tab.share_tab_request')"+ :shortcut="['S']"+ @click="+ () => {+ emit('share-tab-request')+ hide()+ }+ "+ />+ <HoppSmartItem+ v-if="isRemovable"+ ref="closeAction"+ :icon="IconXCircle"+ :label="t('tab.close')"+ :shortcut="['W']"+ @click="+ () => {+ emit('close-tab')+ hide()+ }+ "+ />+ <HoppSmartItem+ v-if="isRemovable"+ ref="closeOthersAction"+ :icon="IconXSquare"+ :label="t('tab.close_others')"+ :shortcut="['X']"+ @click="+ () => {+ emit('close-other-tabs')+ hide()+ }+ "+ />+ </div>+ </template>+ </tippy>+ </div>+</template>++<script setup lang="ts">+import { computed, ref } from "vue"+import { TippyComponent } from "vue-tippy"+import { useI18n } from "~/composables/i18n"+import IconGraphql from "~icons/hopp/graphql"+import IconXCircle from "~icons/lucide/x-circle"+import IconXSquare from "~icons/lucide/x-square"+import IconFileEdit from "~icons/lucide/file-edit"+import IconCopy from "~icons/lucide/copy"+import IconShare2 from "~icons/lucide/share-2"+import { HoppTab } from "~/services/tab"+import {+ HoppGQLRequestDocument,+ HoppSavedGQLExampleDocument,+} from "~/helpers/tab/document"++const t = useI18n()++const props = defineProps<{+ tab: HoppTab<HoppGQLRequestDocument | HoppSavedGQLExampleDocument>+ isRemovable: boolean+}>()++const isResponseExample = computed(+ () => props.tab.document.type === "gql-example-response"+)++const tabName = computed(() => {+ if (props.tab.document.type === "gql-example-response") {+ return props.tab.document.response?.name ?? "Untitled"+ }+ if (props.tab.document.type === "gql-request") {+ return props.tab.document.request?.name ?? "Untitled"+ }+ return "Untitled"+})++const emit = defineEmits<{+ (event: "open-rename-modal"): void+ (event: "close-tab"): void+ (event: "close-other-tabs"): void+ (event: "duplicate-tab"): void+ (event: "share-tab-request"): void+}>()++const tippyActions = ref<TippyComponent | null>(null)+const options = ref<TippyComponent | null>(null)++const renameAction = ref<HTMLButtonElement | null>(null)+const shareRequestAction = ref<HTMLButtonElement | null>(null)+const closeAction = ref<HTMLButtonElement | null>(null)+const closeOthersAction = ref<HTMLButtonElement | null>(null)+const duplicateAction = ref<HTMLButtonElement | null>(null)+</script>diff --git a/packages/hoppscotch-common/src/components/gql/TypeDocumentation.vue b/packages/hoppscotch-common/src/components/gql/TypeDocumentation.vuenew file mode 100644index 000000000..6b1ed1e2e--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/TypeDocumentation.vue@@ -0,0 +1,23 @@+<template>+ <div v-if="isNamedType(type)" class="flex flex-col">+ <AppMarkdown+ v-if="type.description"+ type="description"+ class="text-secondary leading-relaxed px-4 py-3"+ >+ {{ type.description }}+ </AppMarkdown>+ <GqlImplementsInterfaces :type="type" />+ <GqlFields :type="type" :show-add-field="!readonly" />+ <GqlEnumValues :type="type" />+ </div>+</template>++<script setup lang="ts">+import { GraphQLNamedType, isNamedType } from "graphql"++defineProps<{+ type: GraphQLNamedType+ readonly?: boolean+}>()+</script>diff --git a/packages/hoppscotch-common/src/components/gql/TypeLink.vue b/packages/hoppscotch-common/src/components/gql/TypeLink.vuenew file mode 100644index 000000000..7a14bec0a--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/TypeLink.vue@@ -0,0 +1,45 @@+<template>+ <template v-if="type">+ <component :is="renderedComponent" />+ </template>+</template>++<script setup lang="ts">+import { GraphQLNamedType, GraphQLType } from "graphql"+import { computed, h } from "vue"+import { renderType, useExplorer } from "~/helpers/graphql/explorer"++const props = defineProps<{+ type: GraphQLType+ clickable?: boolean+ readonly?: boolean+ isHeading?: boolean+}>()++const { push } = useExplorer()++const handleTypeClick = (event: MouseEvent, namedType: GraphQLNamedType) => {+ event.preventDefault()+ push({ name: namedType.name, def: namedType, readonly: props.readonly })+}++const renderedComponent = computed(() => {+ if (!props.type) return ""++ return renderType(props.type, (namedType: GraphQLNamedType) => {+ return h(+ "span",+ {+ class: `hopp-doc-explorer-type-name ${+ props.isHeading ? "!text-lg !font-bold" : ""+ }+ ${props.clickable ? "cursor-pointer hover:underline" : ""}+ `,+ onClick: (event: MouseEvent) =>+ props.clickable ? handleTypeClick(event, namedType) : undefined,+ },+ namedType.name+ )+ })+})+</script>diff --git a/packages/hoppscotch-common/src/components/gql/Variable.vue b/packages/hoppscotch-common/src/components/gql/Variable.vuenew file mode 100644index 000000000..e85aa80ce--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/Variable.vue@@ -0,0 +1,180 @@+<template>+ <div+ class="sticky top-upperSecondaryStickyFold z-10 flex items-center justify-between border-y border-dividerLight bg-primary pl-4"+ >+ <label class="font-semibold text-secondaryLight">+ {{ t("request.variables") }}+ </label>+ <div class="flex">+ <HoppButtonSecondary+ v-if="showRunActions && subscriptionState === 'SUBSCRIBED'"+ v-tippy="{+ theme: 'tooltip',+ delay: [500, 20],+ allowHTML: true,+ }"+ :title="`${t('request.stop')}`"+ :label="`${t('request.stop')}`"+ :icon="IconStop"+ class="!hover:text-accentDark rounded-none !text-accent"+ @click="stopQuery()"+ />+ <HoppButtonSecondary+ v-if="showRunActions && subscriptionState !== 'SUBSCRIBED'"+ v-tippy="{+ theme: 'tooltip',+ delay: [500, 20],+ allowHTML: true,+ }"+ :title="`${t('request.run')} <kbd>${getSpecialKey()}</kbd><kbd>↩</kbd>`"+ :label="`${t('request.run')}`"+ :icon="IconPlay"+ class="!hover:text-accentDark rounded-none !text-accent"+ @click="runQuery(null)"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ to="https://docs.hoppscotch.io/documentation/features/graphql-api-testing"+ blank+ :title="t('app.wiki')"+ :icon="IconHelpCircle"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.clear_all')"+ :icon="IconTrash2"+ @click="clearGQLVariables()"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('state.linewrap')"+ :class="{ '!text-accent': WRAP_LINES }"+ :icon="IconWrapText"+ @click.prevent="toggleNestedSetting('WRAP_LINES', 'graphqlVariables')"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.prettify')"+ :icon="prettifyVariablesIcon"+ @click="prettifyVariableString"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.copy')"+ :icon="copyVariablesIcon"+ @click="copyVariables"+ />+ </div>+ </div>+ <div class="h-full relative flex flex-col flex-1">+ <div ref="variableEditor" class="absolute inset-0"></div>+ </div>+</template>++<script setup lang="ts">+import IconPlay from "~icons/lucide/play"+import IconStop from "~icons/lucide/stop-circle"+import IconHelpCircle from "~icons/lucide/help-circle"+import IconTrash2 from "~icons/lucide/trash-2"+import IconCopy from "~icons/lucide/copy"+import IconCheck from "~icons/lucide/check"+import IconInfo from "~icons/lucide/info"+import IconWand from "~icons/lucide/wand"+import IconWrapText from "~icons/lucide/wrap-text"+import { computed, reactive, ref } from "vue"+import jsonLinter from "~/helpers/editor/linting/json"+import { copyToClipboard } from "@helpers/utils/clipboard"+import { useCodemirror } from "@composables/codemirror"+import * as gql from "graphql"+import { useI18n } from "@composables/i18n"+import { refAutoReset, useVModel } from "@vueuse/core"+import { useToast } from "~/composables/toast"+import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"+import type { SubscriptionState } from "~/helpers/graphql/connection"+import type { AggregateEnvironment } from "~/newstore/environments"+import { useNestedSetting } from "~/composables/settings"+import { toggleNestedSetting } from "~/newstore/settings"++const t = useI18n()+const toast = useToast()++const props = withDefaults(+ defineProps<{+ modelValue: string+ showRunActions?: boolean+ subscriptionState?: SubscriptionState+ // Embed-only env scope for `<<var>>` highlights+ envs?: AggregateEnvironment[]+ }>(),+ { showRunActions: true, subscriptionState: undefined, envs: undefined }+)++const emit = defineEmits<{+ (e: "save-request"): void+ (e: "update:modelValue", val: string): void+ (e: "run-query", definition: gql.OperationDefinitionNode | null): void+ (e: "stop-query"): void+}>()++const variableString = useVModel(props, "modelValue", emit)++const variableEditor = ref<any | null>(null)++const WRAP_LINES = useNestedSetting("WRAP_LINES", "graphqlVariables")++const copyVariablesIcon = refAutoReset<typeof IconCopy | typeof IconCheck>(+ IconCopy,+ 1000+)+const prettifyVariablesIcon = refAutoReset<+ typeof IconWand | typeof IconCheck | typeof IconInfo+>(IconWand, 1000)++useCodemirror(+ variableEditor,+ variableString,+ reactive({+ extendedEditorConfig: {+ mode: "application/ld+json",+ placeholder: `${t("request.variables")}`,+ lineWrapping: WRAP_LINES,+ },+ linter: computed(() =>+ variableString.value.length > 0 ? jsonLinter : null+ ),+ completer: null,+ environmentHighlights: true,+ envs: computed(() => props.envs),+ predefinedVariablesHighlights: true,+ })+)++const copyVariables = () => {+ copyToClipboard(variableString.value)+ copyVariablesIcon.value = IconCheck+ toast.success(`${t("state.copied_to_clipboard")}`)+}++const prettifyVariableString = () => {+ try {+ const jsonObj = JSON.parse(variableString.value)+ variableString.value = JSON.stringify(jsonObj, null, 2)+ prettifyVariablesIcon.value = IconCheck+ } catch (e) {+ console.error(e)+ prettifyVariablesIcon.value = IconInfo+ toast.error(`${t("error.json_prettify_invalid_body")}`)+ }+}++const clearGQLVariables = () => {+ variableString.value = ""+}++const runQuery = (definition: gql.OperationDefinitionNode | null = null) => {+ emit("run-query", definition)+}+const stopQuery = () => {+ emit("stop-query")+}+</script>diff --git a/packages/hoppscotch-common/src/components/gql/example/Response.vue b/packages/hoppscotch-common/src/components/gql/example/Response.vuenew file mode 100644index 000000000..9f00bc71a--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/example/Response.vue@@ -0,0 +1,164 @@+<template>+ <div class="flex flex-1 flex-col overflow-auto whitespace-nowrap">+ <div+ class="sticky top-0 z-50 flex-none flex-shrink-0 items-center justify-center whitespace-nowrap bg-primary p-4"+ >+ <div class="flex flex-1 flex-col">+ <div class="flex items-center text-tiny font-semibold">+ <div class="inline-flex flex-1 space-x-4">+ <div class="flex-1 flex items-center space-x-2">+ <span class="text-secondary">{{ t("response.status") }}:</span>+ <div class="flex-1 flex whitespace-nowrap max-w-xs">+ <SmartEnvInput+ v-model="statusText"+ :auto-complete-source="statusCodeOptions"+ class="flex-1 border border-divider"+ @update:model-value="setResponseStatusCode"+ />+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ <div class="flex flex-1 flex-col">+ <div+ class="sticky top-0 z-10 flex flex-shrink-0 items-center justify-between overflow-x-auto border-b border-dividerLight bg-primary pl-4"+ >+ <label class="truncate font-semibold text-secondaryLight">+ {{ t("response.body") }}+ </label>+ <div class="flex items-center">+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('state.linewrap')"+ :class="{ '!text-accent': WRAP_LINES }"+ :icon="IconWrapText"+ @click.prevent="+ toggleNestedSetting('WRAP_LINES', 'graphqlResponseBody')+ "+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="t('action.prettify')"+ :icon="prettifyIcon"+ @click="prettifyBody"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip', allowHTML: true }"+ :title="`${t('action.download_file')} <kbd>${getSpecialKey()}</kbd><kbd>J</kbd>`"+ :icon="downloadIcon"+ @click="downloadResponse"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip', allowHTML: true }"+ :title="`${t('action.copy')} <kbd>${getSpecialKey()}</kbd><kbd>.</kbd>`"+ :icon="copyIcon"+ @click="copyResponse"+ />+ </div>+ </div>+ <div class="h-full relative overflow-auto flex flex-col flex-1">+ <div ref="bodyEditor" class="absolute inset-0 h-full"></div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import IconWrapText from "~icons/lucide/wrap-text"+import IconWand from "~icons/lucide/wand"+import IconCheck from "~icons/lucide/check"+import IconInfo from "~icons/lucide/info"+import { computed, reactive, ref } from "vue"+import { refAutoReset, useVModel } from "@vueuse/core"+import { useCodemirror } from "@composables/codemirror"+import { useI18n } from "@composables/i18n"+import { useToast } from "@composables/toast"+import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"+import { useNestedSetting } from "~/composables/settings"+import { toggleNestedSetting } from "~/newstore/settings"+import {+ useCopyResponse,+ useDownloadResponse,+} from "~/composables/lens-actions"+import {+ getFullStatusCodePhrase,+ getStatusCodePhrase,+ getStatusAndCode,+ isValidStatusCode,+} from "~/helpers/utils/statusCodes"+import jsonLinter from "~/helpers/editor/linting/json"+import { HoppSavedGQLExampleDocument } from "~/helpers/tab/document"++const t = useI18n()+const toast = useToast()++const props = defineProps<{ document: HoppSavedGQLExampleDocument }>()++const emit = defineEmits<{+ (e: "update:document", val: HoppSavedGQLExampleDocument): void+}>()++const doc = useVModel(props, "document", emit)++const bodyEditor = ref<any | null>(null)+const WRAP_LINES = useNestedSetting("WRAP_LINES", "graphqlResponseBody")++const bodyString = computed({+ get: () => doc.value.response.body,+ set: (val) => {+ doc.value.response.body = val+ },+})++useCodemirror(+ bodyEditor,+ bodyString,+ reactive({+ extendedEditorConfig: {+ mode: "application/ld+json",+ lineWrapping: WRAP_LINES,+ },+ linter: computed(() => (bodyString.value.length > 0 ? jsonLinter : null)),+ completer: null,+ environmentHighlights: false,+ })+)++const statusText = ref(+ getStatusCodePhrase(doc.value.response.code, doc.value.response.status)+)+const statusCodeOptions = computed(() => getFullStatusCodePhrase())++const setResponseStatusCode = (val: string) => {+ if (!isValidStatusCode(val)) {+ doc.value.response.status = val+ doc.value.response.code = null+ return+ }+ doc.value.response.code = getStatusAndCode(val).code+ doc.value.response.status = getStatusAndCode(val).status+}++const prettifyIcon = refAutoReset<+ typeof IconWand | typeof IconCheck | typeof IconInfo+>(IconWand, 1000)++const prettifyBody = () => {+ try {+ bodyString.value = JSON.stringify(JSON.parse(bodyString.value), null, 2)+ prettifyIcon.value = IconCheck+ } catch {+ prettifyIcon.value = IconInfo+ toast.error(`${t("error.json_prettify_invalid_body")}`)+ }+}++const { copyIcon, copyResponse } = useCopyResponse(bodyString)+const { downloadIcon, downloadResponse } = useDownloadResponse(+ "application/json",+ bodyString,+ t("filename.graphql_response")+)+</script>diff --git a/packages/hoppscotch-common/src/components/gql/example/ResponseRequest.vue b/packages/hoppscotch-common/src/components/gql/example/ResponseRequest.vuenew file mode 100644index 000000000..12b74019b--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/example/ResponseRequest.vue@@ -0,0 +1,174 @@+<template>+ <div+ class="sticky top-0 z-20 flex-none flex-shrink-0 bg-primary p-4 sm:flex sm:flex-shrink-0 sm:space-x-2"+ >+ <div+ class="min-w-[12rem] flex flex-1 whitespace-nowrap rounded border border-divider"+ >+ <div+ class="flex cursor-default items-center rounded-l bg-primaryLight px-4 py-2"+ >+ <IconGraphql class="svg-icons h-4 w-4 text-accent" />+ </div>+ <div+ class="flex flex-1 whitespace-nowrap rounded-r border-l border-divider bg-primaryLight transition"+ >+ <SmartEnvInput+ v-model="tab.document.response.originalRequest.url"+ :placeholder="`${t('graphql.url_placeholder')}`"+ :auto-complete-env="true"+ />+ </div>+ </div>+ <div class="mt-2 flex sm:mt-0 items-stretch space-x-2">+ <HoppButtonPrimary+ v-tippy="{ theme: 'tooltip', delay: [500, 20], allowHTML: true }"+ :title="t('request.try')"+ :label="t('request.try')"+ class="min-w-[5rem] flex-1"+ @click="tryExampleResponse"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip', delay: [500, 20], allowHTML: true }"+ :title="`${t(+ 'request.save'+ )} <kbd>${getSpecialKey()}</kbd><kbd>S</kbd>`"+ :label="t('action.save')"+ filled+ :icon="IconSave"+ class="flex-1 rounded"+ @click="saveExample"+ />+ </div>+ </div>+</template>++<script setup lang="ts">+import { useI18n } from "@composables/i18n"+import { useVModel } from "@vueuse/core"+import { useService } from "dioc/vue"+import { cloneDeep } from "lodash-es"+import IconGraphql from "~icons/hopp/graphql"+import IconSave from "~icons/lucide/save"+import * as E from "fp-ts/Either"++import {+ HoppGQLRequest,+ HoppGQLRequestResponse,+ getDefaultGQLRequest,+} from "@hoppscotch/data"++import { HoppTab } from "~/services/tab"+import { HoppSavedGQLExampleDocument } from "~/helpers/tab/document"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"+import { getPlatformSpecialKey as getSpecialKey } from "~/helpers/platformutils"+import { editRESTRequest, restCollections$ } from "~/newstore/collections"+import { useReadonlyStream } from "~/composables/stream"+import { getRequestsByPath } from "~/helpers/collection/request"+import { useToast } from "@composables/toast"+import { defineActionHandler } from "~/helpers/actions"+import { runMutation } from "~/helpers/backend/GQLClient"+import { UpdateRequestDocument } from "~/helpers/backend/graphql"+import { getSingleRequest } from "~/helpers/teams/TeamRequest"++const t = useI18n()+const toast = useToast()+const tabs = useService(WorkspaceTabsService)+const myCollections = useReadonlyStream(restCollections$, [], "deep")++const props = defineProps<{+ modelValue: HoppTab<HoppSavedGQLExampleDocument>+}>()+const emit = defineEmits(["update:modelValue"])+const tab = useVModel(props, "modelValue", emit)++// "Try" opens the captured original request as a brand-new GQL tab so the user+// can run it again without mutating the example. Mirrors the REST flow.+const tryExampleResponse = () => {+ const orig = tab.value.document.response.originalRequest+ tabs.createNewTab({+ isDirty: false,+ type: "gql-request",+ request: {+ ...getDefaultGQLRequest(),+ name: orig.name,+ url: orig.url,+ query: orig.query,+ variables: orig.variables,+ headers: orig.headers,+ auth: orig.auth,+ },+ cursorPosition: 0,+ inheritedProperties: tab.value.document.inheritedProperties,+ })+}++const saveExample = async () => {+ const saveCtx = tab.value.document.saveContext+ if (!saveCtx) return++ const response: HoppGQLRequestResponse = cloneDeep(+ tab.value.document.response+ )++ if (saveCtx.originLocation === "user-collection") {+ // Unified workspace: GQL requests live in REST collection rows on the+ // backend, so the local store path is the REST collection store too.+ const request = cloneDeep(+ getRequestsByPath(myCollections.value, saveCtx.folderPath)[+ saveCtx.requestIndex!+ ] as unknown as HoppGQLRequest+ )++ if (!request) return++ request.responses = {+ ...(request.responses ?? {}),+ [response.name]: response,+ }++ try {+ editRESTRequest(saveCtx.folderPath, saveCtx.requestIndex!, request)+ tab.value.document.isDirty = false+ toast.success(`${t("response.saved")}`)+ } catch (e) {+ console.error(e)+ }+ return+ }++ if (saveCtx.originLocation === "team-collection") {+ const request = await getSingleRequest(saveCtx.requestID)++ if (E.isLeft(request) || !request.right.request) {+ toast.error(`${t("error.something_went_wrong")}`)+ return+ }++ const parsedRequest: HoppGQLRequest = JSON.parse(+ request.right.request.request+ )+ parsedRequest.responses = {+ ...(parsedRequest.responses ?? {}),+ [response.name]: response,+ }++ runMutation(UpdateRequestDocument, {+ requestID: saveCtx.requestID,+ data: {+ title: parsedRequest.name,+ request: JSON.stringify(parsedRequest),+ },+ })().then((result) => {+ if (E.isLeft(result)) {+ toast.error(`${t("profile.no_permission")}`)+ } else {+ tab.value.document.isDirty = false+ toast.success(`${t("response.saved")}`)+ }+ })+ }+}++defineActionHandler("request-response.save", saveExample)+</script>diff --git a/packages/hoppscotch-common/src/components/gql/example/ResponseTab.vue b/packages/hoppscotch-common/src/components/gql/example/ResponseTab.vuenew file mode 100644index 000000000..0dbb394e0--- /dev/null+++ b/packages/hoppscotch-common/src/components/gql/example/ResponseTab.vue@@ -0,0 +1,48 @@+<template>+ <AppPaneLayout layout-id="gql-example-primary">+ <template #primary>+ <GqlExampleResponseRequest v-model="tab" />+ <GqlRequestOptions+ v-model="tab.document.response.originalRequest"+ v-model:option-tab="optionTab"+ :inherited-properties="tab.document.inheritedProperties"+ :show-run-actions="false"+ />+ </template>+ <template #secondary>+ <GqlExampleResponse v-model:document="tab.document" />+ </template>+ </AppPaneLayout>+</template>++<script setup lang="ts">+import { useVModel } from "@vueuse/core"+import { cloneDeep, isEqual } from "lodash-es"+import { ref, watch } from "vue"+import { HoppTab } from "~/services/tab"+import { HoppSavedGQLExampleDocument } from "~/helpers/tab/document"+import type { GQLOptionTabs } from "~/components/graphql/RequestOptions.vue"++const props = defineProps<{+ modelValue: HoppTab<HoppSavedGQLExampleDocument>+}>()++const emit = defineEmits<{+ (e: "update:modelValue", val: HoppTab<HoppSavedGQLExampleDocument>): void+}>()++const tab = useVModel(props, "modelValue", emit)+const optionTab = ref<GQLOptionTabs>("query")++let oldResponse = cloneDeep(tab.value.document.response)+watch(+ () => tab.value.document.response,+ (updatedValue) => {+ if (!tab.value.document.isDirty && !isEqual(oldResponse, updatedValue)) {+ tab.value.document.isDirty = true+ }+ oldResponse = cloneDeep(updatedValue)+ },+ { deep: true }+)+</script>diff --git a/packages/hoppscotch-common/src/components/graphql/Authorization.vue b/packages/hoppscotch-common/src/components/graphql/Authorization.vueindex a19ff787e..bab059beb 100644--- a/packages/hoppscotch-common/src/components/graphql/Authorization.vue+++ b/packages/hoppscotch-common/src/components/graphql/Authorization.vue@@ -238,8 +238,7 @@ const selectOAuth2AuthType = () => {// @ts-expect-error - the existing grantTypeInfo might be in the auth object, typescript doesnt know thatconst existingGrantTypeInfo = auth.value.grantTypeInfo as- | HoppGQLAuthOAuth2["grantTypeInfo"]- | undefined+ HoppGQLAuthOAuth2["grantTypeInfo"] | undefinedconst grantTypeInfo = existingGrantTypeInfo? existingGrantTypeInfodiff --git a/packages/hoppscotch-common/src/components/graphql/Headers.vue b/packages/hoppscotch-common/src/components/graphql/Headers.vueindex fc16f3d0e..f673e53ab 100644--- a/packages/hoppscotch-common/src/components/graphql/Headers.vue+++ b/packages/hoppscotch-common/src/components/graphql/Headers.vue@@ -478,12 +478,10 @@ const updateHeader = (index: number, header: GQLHeader & { id: number }) => {const deleteHeader = (index: number) => {const headersBeforeDeletion = clone(workingHeaders.value)- if (- !(- headersBeforeDeletion.length > 0 &&- index === headersBeforeDeletion.length - 1- )- ) {+ if (!(+ headersBeforeDeletion.length > 0 &&+ index === headersBeforeDeletion.length - 1+ )) {if (deletionToast.value) {deletionToast.value.goAway(0)deletionToast.value = null@@ -699,4 +697,9 @@ const mask = (header: any) => {}const changeTab = () => emit("change-tab", "authorization")++// No inspection wiring here: this component serves the legacy /graphql page,+// whose tabs live in GQLTabService — the InspectionService only inspects the+// unified workspace's tabs, so reading its results here would show warnings+// belonging to a different page's active tab.</script>diff --git a/packages/hoppscotch-common/src/components/graphql/Request.vue b/packages/hoppscotch-common/src/components/graphql/Request.vueindex ce06d5cf5..5993cdad4 100644--- a/packages/hoppscotch-common/src/components/graphql/Request.vue+++ b/packages/hoppscotch-common/src/components/graphql/Request.vue@@ -65,9 +65,7 @@import { platform } from "~/platform"import { useI18n } from "@composables/i18n"import { computed, ref, watch } from "vue"-import { connection } from "~/helpers/graphql/connection"-import { connect } from "~/helpers/graphql/connection"-import { disconnect } from "~/helpers/graphql/connection"+import { connection, connect, disconnect } from "~/helpers/graphql/connection"import { KernelInterceptorService } from "~/services/kernel-interceptor.service"import { useService } from "dioc/vue"import { defineActionHandler } from "~/helpers/actions"diff --git a/packages/hoppscotch-common/src/components/graphql/RequestOptions.vue b/packages/hoppscotch-common/src/components/graphql/RequestOptions.vueindex 991cc8f57..2266a0f74 100644--- a/packages/hoppscotch-common/src/components/graphql/RequestOptions.vue+++ b/packages/hoppscotch-common/src/components/graphql/RequestOptions.vue@@ -48,7 +48,7 @@</HoppSmartTab></HoppSmartTabs><CollectionsSaveRequest- mode="graphql"+ mode="legacy-graphql":show="showSaveRequestModal"@hide-modal="hideRequestModal"/>@@ -82,6 +82,10 @@ const _VALID_GQL_OPERATIONS = ["headers","variables","authorization",+ // Script tabs exist only on the unified workspace's gql/RequestOptions —+ // this legacy page doesn't render them, but it owns the GQLOptionTabs type+ "preRequestScript",+ "tests",] as constexport type GQLOptionTabs = (typeof _VALID_GQL_OPERATIONS)[number]diff --git a/packages/hoppscotch-common/src/components/graphql/Response.vue b/packages/hoppscotch-common/src/components/graphql/Response.vueindex a3be45c9a..bd5b2daac 100644--- a/packages/hoppscotch-common/src/components/graphql/Response.vue+++ b/packages/hoppscotch-common/src/components/graphql/Response.vue@@ -1,6 +1,6 @@<template><div class="flex flex-1 flex-col overflow-auto whitespace-nowrap">- <GraphqlResponseMeta :response="response" />+ <GraphqlResponseMeta :response="response" :tab-id="tabId" /><divv-if="response && response.length === 1 && response[0].type === 'response'@@ -114,9 +114,11 @@ const t = useI18n()const props = withDefaults(defineProps<{response: GQLResponseEvent[] | null+ tabId?: string}>(),{response: null,+ tabId: undefined,})diff --git a/packages/hoppscotch-common/src/components/graphql/ResponseMeta.vue b/packages/hoppscotch-common/src/components/graphql/ResponseMeta.vueindex a0f43e877..0812845af 100644--- a/packages/hoppscotch-common/src/components/graphql/ResponseMeta.vue+++ b/packages/hoppscotch-common/src/components/graphql/ResponseMeta.vue@@ -107,6 +107,7 @@ const tabs = useService(GQLTabService)const props = defineProps<{response: GQLResponseEvent[] | null | undefinedisEmbed?: boolean+ tabId?: string}>()const isLoading = computed(() => {@@ -156,8 +157,13 @@ const statusCategory = computed(() => {const inspectionService = useService(InspectionService)-const tabResults = inspectionService.getResultViewFor(- tabs.currentTabID.value,- (result) => result.locations.type === "response"+// Re-derived per tab change — a setup-time capture of `currentTabID` would+// pin inspection results to whichever tab was active at mount+const tabResults = computed(+ () =>+ inspectionService.getResultViewFor(+ props.tabId ?? tabs.currentTabID.value,+ (result) => result.locations.type === "response"+ ).value)</script>diff --git a/packages/hoppscotch-common/src/components/history/Personal.vue b/packages/hoppscotch-common/src/components/history/Personal.vueindex 82600e87b..95d130a49 100644--- a/packages/hoppscotch-common/src/components/history/Personal.vue+++ b/packages/hoppscotch-common/src/components/history/Personal.vue@@ -102,7 +102,7 @@/></summary><component- :is="page === 'rest' ? HistoryRestCard : HistoryGraphqlCard"+ :is="resolveCardComponent(entry.entry)"v-for="(entry, index) in filteredHistoryGroup":id="index":key="`entry-${index}`"@@ -164,11 +164,16 @@ 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 {+ HoppGQLRequest,+ HoppRESTRequest,+ makeGQLRequest,+} from "@hoppscotch/data"import { useTimeAgo } from "@vueuse/core"+import { combineLatest, map } from "rxjs"import * as A from "fp-ts/Array"import { pipe } from "fp-ts/function"-import { escapeRegExp, filter, groupBy } from "lodash-es"+import { escapeRegExp, filter, groupBy, isEqual } from "lodash-es"import { computed, ref, Ref, toRaw } from "vue"import {clearGraphqlHistory,@@ -190,8 +195,11 @@ import IconTrash2 from "~icons/lucide/trash-2"import { useService } from "dioc/vue"import { defineActionHandler, invokeAction } from "~/helpers/actions"import { sync } from "~/lib/sync/defs"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"+import { GQLTabService } from "~/services/tab/graphql"+import { isRESTRequest } from "~/helpers/request-type"import HistoryGraphqlCard from "./graphql/Card.vue"+import HistoryGraphqlMergedCard from "./graphql/MergedCard.vue"import HistoryRestCard from "./rest/Card.vue"type HistoryEntry = GQLHistoryEntry | RESTHistoryEntry@@ -202,7 +210,11 @@ type TimedHistoryEntry = {}const props = defineProps<{- page: "rest" | "graphql"+ // "rest" / "graphql" — single-protocol modes used by the standalone REST+ // and /graphql pages; behaviour is unchanged.+ // "unified-workspace" — unified workspace mode; interleaves both stores+ // sorted by `updatedOn`, routes each entry by shape.+ page: "rest" | "graphql" | "unified-workspace"}>()const toast = useToast()@@ -213,11 +225,27 @@ const filterText = ref("")const showMore = ref(false)const confirmRemove = ref(false)-const history = useReadonlyStream<RESTHistoryEntry[] | GQLHistoryEntry[]>(- props.page === "rest" ? restHistory$ : graphqlHistory$,- []+// Merged stream — combines both stores, sorts newest first. Built once and+// only subscribed to in "unified-workspace" mode so single-protocol pages+// don't pay the extra combineLatest subscription.+const mergedHistory$ = combineLatest([restHistory$, graphqlHistory$]).pipe(+ map(([rest, gql]) => {+ const merged = [...rest, ...gql] as HistoryEntry[]+ return merged.sort(+ (a, b) => (b.updatedOn?.getTime() ?? 0) - (a.updatedOn?.getTime() ?? 0)+ )+ }))+const historySource$ =+ props.page === "rest"+ ? restHistory$+ : props.page === "graphql"+ ? graphqlHistory$+ : mergedHistory$++const history = useReadonlyStream<HistoryEntry[]>(historySource$, [])+const { isHistoryStoreEnabled, isFetchingHistoryStoreStatus } =sync.history.requestHistoryStore@@ -256,12 +284,10 @@ const filteredHistory = computed(() =>)}),- A.map(- (entry): TimedHistoryEntry => ({- entry,- timeAgo: useTimeAgo(entry.updatedOn),- })- )+ A.map((entry): TimedHistoryEntry => ({+ entry,+ timeAgo: useTimeAgo(entry.updatedOn),+ }))))@@ -295,59 +321,184 @@ const filteredHistoryGroups = computed(() =>))-const getAppropriateURL = (entry: HistoryEntry) => {- if (props.page === "rest") {- return (entry.request as HoppRESTRequest).endpoint- } else if (props.page === "graphql") {- return (entry.request as HoppGQLRequest).url- }+// Picks the right card per entry. The unified-workspace view uses a GQL card+// variant styled with a left-side GraphQL icon chip (so REST and GQL rows+// align in the same list). The legacy /graphql page keeps the original card+// so its visual footprint stays identical to pre-merge.+const resolveCardComponent = (entry: HistoryEntry) => {+ if (isRESTRequest(entry.request)) return HistoryRestCard+ return props.page === "unified-workspace"+ ? HistoryGraphqlMergedCard+ : HistoryGraphqlCard}+const getAppropriateURL = (entry: HistoryEntry) =>+ isRESTRequest(entry.request)+ ? (entry.request as HoppRESTRequest).endpoint+ : (entry.request as HoppGQLRequest).url+const clearHistory = () => {- if (props.page === "rest") clearRESTHistory()- else clearGraphqlHistory()+ // Unified-workspace mode clears both stores; otherwise mirror the legacy+ // behaviour of the single-protocol pages so /graphql and REST-only flows+ // are unchanged.+ if (props.page === "unified-workspace") {+ clearRESTHistory()+ clearGraphqlHistory()+ } else if (props.page === "rest") {+ clearRESTHistory()+ } else {+ clearGraphqlHistory()+ }toast.success(`${t("state.history_deleted")}`)}-// NOTE: For GQL, the HistoryGraphqlCard component already implements useEntry-// (That is not a really good behaviour tho ¯\_(ツ)_/¯)-const tabs = useService(RESTTabService)+// Unified workspace tab service (used for REST tabs everywhere, and for GQL+// tabs in unified-workspace mode). The legacy /graphql page still uses its+// own GQLTabService — bound below so we can route GQL clicks correctly there+// without changing observable behaviour for that page.+const tabs = useService(WorkspaceTabsService)+const gqlTabs = useService(GQLTabService)-const useHistory = (entry: RESTHistoryEntry) => {- tabs.createNewTab({- type: "request",- request: entry.request,- isDirty: false,- })-}+// Compare the signature fields of two requests. We deliberately exclude:+// - `responses` — mutated whenever the tab re-runs the request+// - `v`, `_ref_id`, `id` — schema/version/persistence metadata, not user intent+// - `name`, `description` — cosmetic; renaming a tab shouldn't fork it+// Everything that affects the wire payload or runtime behaviour IS compared,+// so two history entries that differ only in (say) preRequestScript are+// recognised as distinct.+const restRequestsMatch = (a: HoppRESTRequest, b: HoppRESTRequest) =>+ a.endpoint === b.endpoint &&+ a.method === b.method &&+ a.preRequestScript === b.preRequestScript &&+ a.testScript === b.testScript &&+ isEqual(a.body, b.body) &&+ isEqual(a.headers, b.headers) &&+ isEqual(a.params, b.params) &&+ isEqual(a.auth, b.auth) &&+ isEqual(a.requestVariables, b.requestVariables)-const isRESTHistoryEntry = (- entries: TimedHistoryEntry[]-): entries is Array<TimedHistoryEntry & { entry: RESTHistoryEntry }> =>- // If the page is rest, then we can guarantee what we have is a RESTHistoryEnry- props.page === "rest"+const gqlRequestsMatch = (a: HoppGQLRequest, b: HoppGQLRequest) =>+ a.url === b.url &&+ a.query === b.query &&+ a.variables === b.variables &&+ a.preRequestScript === b.preRequestScript &&+ a.testScript === b.testScript &&+ isEqual(a.headers, b.headers) &&+ isEqual(a.auth, b.auth)-const deleteBatchHistoryEntry = (entries: TimedHistoryEntry[]) => {- if (isRESTHistoryEntry(entries)) {- entries.forEach((entry) => {- deleteRESTHistoryEntry(entry.entry)+const useHistory = (entry: HistoryEntry) => {+ if (isRESTRequest(entry.request)) {+ const restEntry = entry.request as HoppRESTRequest++ // Focus an already-open REST tab that still matches the entry's+ // signature — avoids opening duplicate tabs when the user re-clicks+ // the same history row. Only meaningful in unified-workspace mode (the+ // legacy /graphql page doesn't render REST entries).+ //+ // Deliberately skips tabs bound to a collection: history stores the same+ // fields `restRequestsMatch` compares, so an unedited run matches its own+ // originating tab. Focusing that tab would turn a later save into a silent+ // overwrite of the stored request instead of the Save-As the user expects.+ const existing = tabs+ .getTabs()+ .find(+ (t) =>+ t.document.type === "request" &&+ !t.document.saveContext &&+ restRequestsMatch(t.document.request, restEntry)+ )+ if (existing) {+ tabs.setActiveTab(existing.id)+ return+ }++ tabs.createNewTab({+ type: "request",+ request: restEntry,+ isDirty: false,+ })+ return+ }++ // GraphQL entry — normalize via makeGQLRequest so we get schema defaults+ // (responses: {}, version, etc.) regardless of how the entry was stored.+ const gqlEntryRequest = entry.request as HoppGQLRequest+ const gqlRequest = makeGQLRequest({+ name: gqlEntryRequest.name,+ url: gqlEntryRequest.url,+ headers: gqlEntryRequest.headers,+ query: gqlEntryRequest.query,+ variables: gqlEntryRequest.variables,+ auth: gqlEntryRequest.auth,+ description: gqlEntryRequest.description ?? null,+ responses: {},+ preRequestScript: gqlEntryRequest.preRequestScript ?? "",+ testScript: gqlEntryRequest.testScript ?? "",+ })++ if (props.page === "graphql") {+ // Legacy /graphql page — always open a fresh tab, matching what+ // HistoryGraphqlCard did before this moved up to the parent. Reusing a+ // matching tab would be wrong here: history stores exactly the fields+ // `gqlRequestsMatch` compares, so an unedited run matches its own+ // originating tab — and if that tab came from a collection it carries a+ // saveContext, turning a later save into a silent overwrite of the stored+ // request instead of the Save-As the user expects.+ gqlTabs.createNewTab({+ request: gqlRequest,+ isDirty: false,})} else {- entries.forEach((entry) => {- deleteGraphqlHistoryEntry(entry.entry as GQLHistoryEntry)+ // Unified-workspace mode — open the GQL entry as a gql-request tab in+ // the workspace tab strip. Collection-bound tabs are skipped for the same+ // reason as the REST branch above.+ const existing = tabs+ .getTabs()+ .find(+ (t) =>+ t.document.type === "gql-request" &&+ !t.document.saveContext &&+ gqlRequestsMatch(t.document.request, gqlEntryRequest)+ )+ if (existing) {+ tabs.setActiveTab(existing.id)+ return+ }++ tabs.createNewTab({+ type: "gql-request",+ request: gqlRequest,+ isDirty: false,+ cursorPosition: 0,})}+}++const deleteBatchHistoryEntry = (entries: TimedHistoryEntry[]) => {+ entries.forEach(({ entry }) => {+ if (isRESTRequest(entry.request)) {+ deleteRESTHistoryEntry(entry as RESTHistoryEntry)+ } else {+ deleteGraphqlHistoryEntry(entry as GQLHistoryEntry)+ }+ })toast.success(`${t("state.deleted")}`)}const deleteHistory = (entry: HistoryEntry) => {- if (props.page === "rest") deleteRESTHistoryEntry(entry as RESTHistoryEntry)- else deleteGraphqlHistoryEntry(entry as GQLHistoryEntry)+ if (isRESTRequest(entry.request)) {+ deleteRESTHistoryEntry(entry as RESTHistoryEntry)+ } else {+ deleteGraphqlHistoryEntry(entry as GQLHistoryEntry)+ }toast.success(`${t("state.deleted")}`)}const addToCollection = (entry: HistoryEntry) => {- if (props.page === "rest") {+ // Only REST entries support add-to-collection from history today — the GQL+ // card doesn't emit `add-to-collection`, so this is a no-op for GQL even+ // in unified-workspace mode. Wiring GQL save-as is its own follow-up.+ if (isRESTRequest(entry.request)) {invokeAction("request.save-as", {requestType: "rest",request: entry.request as HoppRESTRequest,@@ -356,10 +507,11 @@ const addToCollection = (entry: HistoryEntry) => {}const toggleStar = (entry: HistoryEntry) => {- // History entry type specified because function does not know the type- if (props.page === "rest")+ if (isRESTRequest(entry.request)) {toggleRESTHistoryEntryStar(entry as RESTHistoryEntry)- else toggleGraphqlHistoryEntryStar(entry as GQLHistoryEntry)+ } else {+ toggleGraphqlHistoryEntryStar(entry as GQLHistoryEntry)+ }}defineActionHandler("history.clear", () => {diff --git a/packages/hoppscotch-common/src/components/history/graphql/Card.vue b/packages/hoppscotch-common/src/components/history/graphql/Card.vueindex 077df133f..c18cc3ae1 100644--- a/packages/hoppscotch-common/src/components/history/graphql/Card.vue+++ b/packages/hoppscotch-common/src/components/history/graphql/Card.vue@@ -66,12 +66,8 @@ import IconMinimize2 from "~icons/lucide/minimize-2"import IconMaximize2 from "~icons/lucide/maximize-2"import { useI18n } from "@composables/i18n"-import { makeGQLRequest } from "@hoppscotch/data"-import { useService } from "dioc/vue"-import { GQLTabService } from "~/services/tab/graphql"const t = useI18n()-const tabs = useService(GQLTabService)const props = defineProps<{entry: GQLHistoryEntry@@ -81,6 +77,7 @@ const props = defineProps<{const emit = defineEmits<{(e: "delete-entry"): void(e: "toggle-star"): void+ (e: "use-entry"): void}>()const expand = ref(false)@@ -95,16 +92,9 @@ const query = computed(() =>)const useEntry = () => {- tabs.createNewTab({- request: makeGQLRequest({- name: props.entry.request.name,- url: props.entry.request.url,- headers: props.entry.request.headers,- query: props.entry.request.query,- variables: props.entry.request.variables,- auth: props.entry.request.auth,- }),- isDirty: false,- })+ // Tab creation is owned by the parent (HistoryPersonal) so the same card+ // works both on the legacy /graphql page (GQLTabService) and inside the+ // unified workspace (WorkspaceTabsService with type "gql-request").+ emit("use-entry")}</script>diff --git a/packages/hoppscotch-common/src/components/history/graphql/MergedCard.vue b/packages/hoppscotch-common/src/components/history/graphql/MergedCard.vuenew file mode 100644index 000000000..408f21f22--- /dev/null+++ b/packages/hoppscotch-common/src/components/history/graphql/MergedCard.vue@@ -0,0 +1,108 @@+<template>+ <div class="group flex flex-col">+ <div class="flex items-stretch">+ <span+ v-tippy="{ theme: 'tooltip', delay: [500, 20] }"+ class="flex w-16 cursor-pointer items-center justify-center px-2 text-accent"+ data-testid="restore_history_entry"+ :title="t('navigation.graphql')"+ @click="useEntry"+ >+ <component :is="IconGraphql" class="h-4 w-4" />+ </span>+ <span+ v-tippy="{+ theme: 'tooltip',+ delay: [500, 20],+ content: entry.updatedOn ? shortDateTime(entry.updatedOn) : null,+ }"+ class="flex min-w-0 flex-1 cursor-pointer py-2 pr-2 transition group-hover:text-secondaryDark"+ data-testid="restore_history_entry"+ @click="useEntry"+ >+ <span class="truncate">+ {{ entry.request.url }}+ </span>+ </span>+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :icon="IconTrash"+ color="red"+ :title="t('action.remove')"+ class="hidden group-hover:inline-flex"+ data-testid="delete_history_entry"+ @click="emit('delete-entry')"+ />+ <HoppButtonSecondary+ v-if="canExpand"+ v-tippy="{ theme: 'tooltip' }"+ :title="expand ? t('hide.more') : t('show.more')"+ :icon="expand ? IconMinimize2 : IconMaximize2"+ class="hidden group-hover:inline-flex"+ @click="expand = !expand"+ />+ <HoppButtonSecondary+ v-tippy="{ theme: 'tooltip' }"+ :title="!entry.star ? t('add.star') : t('remove.star')"+ :icon="entry.star ? IconStarOff : IconStar"+ color="yellow"+ :class="{ 'hidden group-hover:inline-flex': !entry.star }"+ data-testid="star_button"+ @click="emit('toggle-star')"+ />+ </div>+ <div class="flex flex-col pb-1 pl-16 pr-2 text-tiny">+ <span+ v-for="(line, index) in query"+ :key="`line-${index}`"+ class="cursor-pointer truncate whitespace-pre font-mono text-secondaryLight"+ data-testid="restore_history_entry"+ @click="useEntry"+ >{{ line }}</span+ >+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed, ref } from "vue"+import { GQLHistoryEntry } from "~/newstore/history"+import { shortDateTime } from "~/helpers/utils/date"++import IconGraphql from "~icons/hopp/graphql"+import IconStar from "~icons/lucide/star"+import IconStarOff from "~icons/hopp/star-off"+import IconTrash from "~icons/lucide/trash"+import IconMinimize2 from "~icons/lucide/minimize-2"+import IconMaximize2 from "~icons/lucide/maximize-2"++import { useI18n } from "@composables/i18n"++const t = useI18n()++const props = defineProps<{+ entry: GQLHistoryEntry+}>()++const emit = defineEmits<{+ (e: "delete-entry"): void+ (e: "toggle-star"): void+ (e: "use-entry"): void+}>()++const expand = ref(false)++const queryLines = computed(() => props.entry.request.query.split("\n"))++const canExpand = computed(() => queryLines.value.length > 2)++const query = computed(() =>+ expand.value || !canExpand.value+ ? queryLines.value+ : queryLines.value.slice(0, 2).concat(["..."])+)++const useEntry = () => {+ emit("use-entry")+}+</script>diff --git a/packages/hoppscotch-common/src/components/history/index.vue b/packages/hoppscotch-common/src/components/history/index.vueindex 6c5d3b225..c7ae3c351 100644--- a/packages/hoppscotch-common/src/components/history/index.vue+++ b/packages/hoppscotch-common/src/components/history/index.vue@@ -28,7 +28,7 @@ import { WorkspaceService } from "~/services/workspace.service"const t = useI18n()const props = defineProps<{- page: "rest" | "graphql"+ page: "rest" | "graphql" | "unified-workspace"selectedTab: string}>()diff --git a/packages/hoppscotch-common/src/components/http/Authorization.vue b/packages/hoppscotch-common/src/components/http/Authorization.vueindex 6c1af4547..1ac958a9b 100644--- a/packages/hoppscotch-common/src/components/http/Authorization.vue+++ b/packages/hoppscotch-common/src/components/http/Authorization.vue@@ -169,7 +169,11 @@<HttpAuthorizationDigest v-model="auth" :envs="envs" /></div><div v-if="auth.authType === 'jwt'">- <HttpAuthorizationJWT v-model="auth" :envs="envs" />+ <HttpAuthorizationJWT+ v-model="auth"+ :envs="envs"+ :scoped-envs="scopedEnvs"+ /></div></div><div@@ -226,11 +230,13 @@ const props = withDefaults(isRootCollection?: booleaninheritedProperties?: HoppInheritedPropertyenvs?: AggregateEnvironment[]+ scopedEnvs?: AggregateEnvironment[]source?: "REST" | "GraphQL"}>(),{source: "REST",envs: undefined,+ scopedEnvs: undefined,inheritedProperties: undefined,})@@ -389,8 +395,7 @@ function selectOAuth2AuthType() {// @ts-expect-error - the existing grantTypeInfo might be in the auth object, typescript doesnt know thatconst existingGrantTypeInfo = auth.value.grantTypeInfo as- | HoppRESTAuthOAuth2["grantTypeInfo"]- | undefined+ HoppRESTAuthOAuth2["grantTypeInfo"] | undefinedconst grantTypeInfo = existingGrantTypeInfo? existingGrantTypeInfodiff --git a/packages/hoppscotch-common/src/components/http/Body.vue b/packages/hoppscotch-common/src/components/http/Body.vueindex 91f82b8f6..adfa1ed63 100644--- a/packages/hoppscotch-common/src/components/http/Body.vue+++ b/packages/hoppscotch-common/src/components/http/Body.vue@@ -103,17 +103,23 @@v-if="body.contentType === 'multipart/form-data'"v-model="body":envs="envs"+ :scoped-envs="scopedEnvs"/><HttpURLEncodedParamsv-else-if="body.contentType === 'application/x-www-form-urlencoded'"v-model="body":envs="envs"+ :scoped-envs="scopedEnvs"/><HttpBodyBinaryv-else-if="body.contentType === 'application/octet-stream'"v-model="body"/>- <HttpRawBody v-else-if="body.contentType !== null" v-model="body" />+ <HttpRawBody+ v-else-if="body.contentType !== null"+ v-model="body"+ :scoped-envs="scopedEnvs"+ /><HoppSmartPlaceholderv-if="body.contentType == null":src="`/images/states/${colorMode.value}/upload_single_file.svg`"@@ -151,7 +157,7 @@ import IconRefreshCW from "~icons/lucide/refresh-cw"import { RESTOptionTabs } from "./RequestOptions.vue"import { AggregateEnvironment } from "~/newstore/environments"import { useService } from "dioc/vue"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { InspectionService } from "~/services/inspection"const colorMode = useColorMode()@@ -161,6 +167,8 @@ const props = defineProps<{body: HoppRESTReqBodyheaders: HoppRESTHeader[]envs?: AggregateEnvironment[]+ // Embed-only codemirror scope — `envs` alone must keep workspace editors live+ scopedEnvs?: AggregateEnvironment[]}>()const emit = defineEmits<{@@ -205,7 +213,7 @@ const isContentTypeAlreadyExist = () => {// Template refsconst tippyActions = ref<any | null>(null)-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const inspectionService = useService(InspectionService)const tabResults = inspectionService.getResultViewFor(diff --git a/packages/hoppscotch-common/src/components/http/BodyParameters.vue b/packages/hoppscotch-common/src/components/http/BodyParameters.vueindex 9ae10517c..5b0023bd0 100644--- a/packages/hoppscotch-common/src/components/http/BodyParameters.vue+++ b/packages/hoppscotch-common/src/components/http/BodyParameters.vue@@ -248,7 +248,7 @@ import IconCircle from "~icons/lucide/circle"import IconTrash from "~icons/lucide/trash"import IconBulkEdit from "~icons/lucide/edit"import IconWrapText from "~icons/lucide/wrap-text"-import { reactive, ref, watch } from "vue"+import { reactive, ref, watch, computed } from "vue"import { flow, pipe } from "fp-ts/function"import * as O from "fp-ts/Option"import * as A from "fp-ts/Array"@@ -277,6 +277,8 @@ type Body = HoppRESTReqBody & { contentType: "multipart/form-data" }const props = defineProps<{modelValue: Bodyenvs: AggregateEnvironment[]+ // Embed-only codemirror scope — `envs` alone must keep workspace editors live+ scopedEnvs?: AggregateEnvironment[]}>()const emit = defineEmits<{@@ -451,12 +453,9 @@ const updateBodyParam = (index: number, entry: FormDataKeyValue) => {const deleteBodyParam = (index: number) => {const paramsBeforeDeletion = clone(workingParams.value)- if (- !(- paramsBeforeDeletion.length > 0 &&- index === paramsBeforeDeletion.length - 1- )- ) {+ if (!(+ paramsBeforeDeletion.length > 0 && index === paramsBeforeDeletion.length - 1+ )) {if (deletionToast.value) {deletionToast.value.goAway(0)deletionToast.value = null@@ -565,6 +564,7 @@ useCodemirror(linter,completer: null,environmentHighlights: true,+ envs: computed(() => props.scopedEnvs),predefinedVariablesHighlights: true,}))diff --git a/packages/hoppscotch-common/src/components/http/Codegen.vue b/packages/hoppscotch-common/src/components/http/Codegen.vueindex 10f6424fe..bce2b3863 100644--- a/packages/hoppscotch-common/src/components/http/Codegen.vue+++ b/packages/hoppscotch-common/src/components/http/Codegen.vue@@ -143,7 +143,7 @@ import { onMounted } from "vue"import { useNestedSetting } from "~/composables/settings"import { toggleNestedSetting } from "~/newstore/settings"import { platform } from "~/platform"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import IconCheck from "~icons/lucide/check"import IconWrapText from "~icons/lucide/wrap-text"import { asyncComputed } from "@vueuse/core"@@ -151,7 +151,7 @@ import { getDefaultRESTRequest } from "~/helpers/rest/default"const t = useI18n()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)// Get the current active request if the current active tab is a request else get the original request from the response tabconst currentActiveRequest = computed(() => {diff --git a/packages/hoppscotch-common/src/components/http/Headers.vue b/packages/hoppscotch-common/src/components/http/Headers.vueindex 33cca6c6e..f882e9225 100644--- a/packages/hoppscotch-common/src/components/http/Headers.vue+++ b/packages/hoppscotch-common/src/components/http/Headers.vue@@ -291,7 +291,7 @@ import {} from "~/newstore/environments"import { toggleNestedSetting } from "~/newstore/settings"import { InspectionService, InspectorResult } from "~/services/inspection"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import IconArrowUpRight from "~icons/lucide/arrow-up-right"import IconEdit from "~icons/lucide/edit"import IconEye from "~icons/lucide/eye"@@ -309,7 +309,7 @@ import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"const t = useI18n()const toast = useToast()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const colorMode = useColorMode()@@ -335,6 +335,8 @@ const props = defineProps<{isCollectionProperty?: booleaninheritedProperties?: HoppInheritedPropertyenvs?: AggregateEnvironment[]+ // Embed-only codemirror scope — `envs` alone must keep workspace editors live+ scopedEnvs?: AggregateEnvironment[]}>()const emit = defineEmits<{@@ -356,6 +358,7 @@ useCodemirror(linter,completer: null,environmentHighlights: true,+ envs: computed(() => props.scopedEnvs),predefinedVariablesHighlights: true,}))@@ -506,12 +509,10 @@ const updateHeader = (const deleteHeader = (index: number) => {const headersBeforeDeletion = cloneDeep(workingHeaders.value)- if (- !(- headersBeforeDeletion.length > 0 &&- index === headersBeforeDeletion.length - 1- )- ) {+ if (!(+ headersBeforeDeletion.length > 0 &&+ index === headersBeforeDeletion.length - 1+ )) {if (deletionToast.value) {deletionToast.value.goAway(0)deletionToast.value = nulldiff --git a/packages/hoppscotch-common/src/components/http/ImportCurl.vue b/packages/hoppscotch-common/src/components/http/ImportCurl.vueindex 93057b313..ac4618489 100644--- a/packages/hoppscotch-common/src/components/http/ImportCurl.vue+++ b/packages/hoppscotch-common/src/components/http/ImportCurl.vue@@ -85,7 +85,7 @@ import IconClipboard from "~icons/lucide/clipboard"import IconCheck from "~icons/lucide/check"import IconTrash2 from "~icons/lucide/trash-2"import { platform } from "~/platform"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { useService } from "dioc/vue"import { useNestedSetting } from "~/composables/settings"import { toggleNestedSetting } from "~/newstore/settings"@@ -95,7 +95,7 @@ const t = useI18n()const toast = useToast()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const curl = ref("")diff --git a/packages/hoppscotch-common/src/components/http/KeyValue.vue b/packages/hoppscotch-common/src/components/http/KeyValue.vueindex 01285a224..80441c5a2 100644--- a/packages/hoppscotch-common/src/components/http/KeyValue.vue+++ b/packages/hoppscotch-common/src/components/http/KeyValue.vue@@ -158,7 +158,9 @@ withDefaults(description: "",inspectionKeyResult: () => [],inspectionValueResult: () => [],- envs: () => [],+ // `undefined` means "use global aggregate envs" in SmartEnvInput, while+ // an explicit [] scopes completions to nothing+ envs: undefined,autoCompleteEnv: true,keyAutoCompleteSource: () => [],}diff --git a/packages/hoppscotch-common/src/components/http/Parameters.vue b/packages/hoppscotch-common/src/components/http/Parameters.vueindex c26288085..18377c7ad 100644--- a/packages/hoppscotch-common/src/components/http/Parameters.vue+++ b/packages/hoppscotch-common/src/components/http/Parameters.vue@@ -109,7 +109,7 @@ import IconTrash2 from "~icons/lucide/trash-2"import IconEdit from "~icons/lucide/edit"import IconPlus from "~icons/lucide/plus"import IconWrapText from "~icons/lucide/wrap-text"-import { reactive, ref, watch } from "vue"+import { reactive, ref, watch, computed } from "vue"import { flow, pipe } from "fp-ts/function"import * as O from "fp-ts/Option"import * as A from "fp-ts/Array"@@ -134,7 +134,7 @@ import { objRemoveKey } from "@functional/object"import { useVModel } from "@vueuse/core"import { useService } from "dioc/vue"import { InspectionService, InspectorResult } from "~/services/inspection"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { useNestedSetting } from "~/composables/settings"import { toggleNestedSetting } from "~/newstore/settings"import { AggregateEnvironment } from "~/newstore/environments"@@ -143,7 +143,7 @@ const colorMode = useColorMode()const t = useI18n()const toast = useToast()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const idTicker = ref(0)@@ -154,6 +154,14 @@ const WRAP_LINES = useNestedSetting("WRAP_LINES", "httpParams")const deletionToast = ref<{ goAway: (delay: number) => void } | null>(null)+// Declared before `useCodemirror` — its options read props at setup+const props = defineProps<{+ modelValue: HoppRESTParam[]+ envs?: AggregateEnvironment[]+ // Embed-only codemirror scope — `envs` alone must keep workspace editors live+ scopedEnvs?: AggregateEnvironment[]+}>()+useCodemirror(bulkEditor,bulkParams,@@ -166,15 +174,11 @@ useCodemirror(linter,completer: null,environmentHighlights: true,+ envs: computed(() => props.scopedEnvs),predefinedVariablesHighlights: true,}))-const props = defineProps<{- modelValue: HoppRESTParam[]- envs?: AggregateEnvironment[]-}>()-const emit = defineEmits<{(e: "update:modelValue", value: Array<HoppRESTParam>): void}>()@@ -316,12 +320,9 @@ const updateParam = (index: number, param: HoppRESTParam & { id: number }) => {const deleteParam = (index: number) => {const paramsBeforeDeletion = cloneDeep(workingParams.value)- if (- !(- paramsBeforeDeletion.length > 0 &&- index === paramsBeforeDeletion.length - 1- )- ) {+ if (!(+ paramsBeforeDeletion.length > 0 && index === paramsBeforeDeletion.length - 1+ )) {if (deletionToast.value) {deletionToast.value.goAway(0)deletionToast.value = nulldiff --git a/packages/hoppscotch-common/src/components/http/PreRequestScript.vue b/packages/hoppscotch-common/src/components/http/PreRequestScript.vueindex 12fab90da..77849cf00 100644--- a/packages/hoppscotch-common/src/components/http/PreRequestScript.vue+++ b/packages/hoppscotch-common/src/components/http/PreRequestScript.vue@@ -128,7 +128,7 @@ import { hasActualScript } from "@hoppscotch/js-sandbox/scripting"import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"import { toggleNestedSetting } from "~/newstore/settings"import { platform } from "~/platform"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import IconFileSymlink from "~icons/lucide/file-symlink"import IconHelpCircle from "~icons/lucide/help-circle"import IconSparkles from "~icons/lucide/sparkles"@@ -188,7 +188,7 @@ const useSnippet = (script: string) => {const clearContent = () => {preRequestScript.value = ""}-const tabService = useService(RESTTabService)+const tabService = useService(WorkspaceTabsService)const currentRequest = computed(() =>tabService.currentActiveTab.value?.document.type === "request"diff --git a/packages/hoppscotch-common/src/components/http/ProtocolSwitcher.vue b/packages/hoppscotch-common/src/components/http/ProtocolSwitcher.vuenew file mode 100644index 000000000..49e5ab833--- /dev/null+++ b/packages/hoppscotch-common/src/components/http/ProtocolSwitcher.vue@@ -0,0 +1,278 @@+<template>+ <div+ class="sticky top-0 z-20 flex items-center border-b border-dividerLight bg-primary px-4 py-2"+ >+ <div>+ <tippy+ interactive+ trigger="click"+ theme="popover"+ :on-shown="() => protocolTippyActions?.focus()"+ >+ <HoppSmartSelectWrapper>+ <button+ v-tippy="{ theme: 'tooltip' }"+ :title="t('request.switch_protocol')"+ :aria-label="t('request.switch_protocol')"+ class="flex w-[7.2rem] items-center justify-between rounded bg-primaryLight px-3 py-1 text-tiny font-bold uppercase tracking-wide text-secondaryDark transition hover:bg-primaryDark"+ >+ <span class="flex items-center gap-1.5">+ <component :is="currentProtocolIcon" class="h-3.5 w-3.5" />+ {{ currentProtocolLabel }}+ </span>+ <component+ :is="IconChevronDown"+ class="h-3.5 w-3.5 text-secondaryLight"+ />+ </button>+ </HoppSmartSelectWrapper>+ <template #content="{ hide }">+ <div+ ref="protocolTippyActions"+ class="flex flex-col focus:outline-none"+ tabindex="0"+ @keyup.escape="hide()"+ >+ <HoppSmartItem+ label="REST"+ :icon="IconGlobe"+ :active="isREST"+ :info-icon="isREST ? IconCheck : undefined"+ :active-info-icon="isREST"+ @click="+ () => {+ switchToREST()+ hide()+ }+ "+ />+ <HoppSmartItem+ label="GraphQL"+ :icon="IconGraphql"+ :active="isGQL"+ :info-icon="isGQL ? IconCheck : undefined"+ :active-info-icon="isGQL"+ @click="+ () => {+ switchToGQL()+ hide()+ }+ "+ />+ </div>+ </template>+ </tippy>+ </div>++ <!-- Folder path + editable request name -->+ <div class="ml-4 flex min-w-0 items-center">+ <template v-if="displayFolderPath.length > 0">+ <template v-for="(segment, i) in displayFolderPath" :key="i">+ <span+ v-tippy="{ theme: 'tooltip' }"+ :title="segment.tooltip"+ class="max-w-[10rem] flex-shrink-0 cursor-default truncate text-tiny text-secondaryLight"+ >+ {{ segment.name }}+ </span>+ <component+ :is="IconChevronRight"+ class="mx-0.5 h-3 w-3 flex-shrink-0 text-secondaryLight opacity-50"+ />+ </template>+ </template>+ <HoppSmartInput+ v-model="requestName"+ :autofocus="false"+ styles=""+ input-styles="border border-transparent bg-transparent text-tiny text-secondaryDark focus:border-divider focus:bg-primaryLight rounded px-2 py-0.5 outline-none transition-colors"+ placeholder="Untitled"+ />+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed, ref } from "vue"+import { useService } from "dioc/vue"+import { useI18n } from "@composables/i18n"+import { useReadonlyStream } from "@composables/stream"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"+import { GQLTabConnectionService } from "~/services/gql-tab-connection.service"+import { ScrollService } from "~/services/scroll.service"+import {+ convertRESTToGQL,+ convertGQLToREST,+} from "~/helpers/tab/type-converter"+import {+ HoppRequestDocument,+ HoppGQLRequestDocument,+} from "~/helpers/tab/document"+import { restCollections$ } from "~/newstore/collections"+import IconChevronRight from "~icons/lucide/chevron-right"+import IconChevronDown from "~icons/lucide/chevron-down"+import IconCheck from "~icons/lucide/check"+import IconGlobe from "~icons/lucide/globe"+import IconGraphql from "~icons/hopp/graphql"++const t = useI18n()++const tabs = useService(WorkspaceTabsService)+const gqlTabConn = useService(GQLTabConnectionService)+const scrollService = useService(ScrollService)++const protocolTippyActions = ref<HTMLDivElement | null>(null)++const collections = useReadonlyStream(restCollections$, [])++const currentDoc = computed(() => tabs.currentActiveTab.value?.document)++const isREST = computed(() => currentDoc.value?.type === "request")+const isGQL = computed(() => currentDoc.value?.type === "gql-request")++const currentProtocolLabel = computed(() => (isGQL.value ? "GraphQL" : "REST"))++const currentProtocolIcon = computed(() =>+ isGQL.value ? IconGraphql : IconGlobe+)++const requestName = computed({+ get: () => {+ const doc = currentDoc.value+ if (!doc) return ""+ if (doc.type === "request") return doc.request.name+ if (doc.type === "gql-request") return doc.request.name+ return ""+ },+ set: (value: string) => {+ const doc = currentDoc.value+ if (!doc) return+ if (doc.type === "request" || doc.type === "gql-request") {+ doc.request.name = value+ }+ },+})++const folderPath = computed<string[]>(() => {+ const doc = currentDoc.value+ if (!doc) return []++ const saveContext =+ doc.type === "request" || doc.type === "gql-request"+ ? doc.saveContext+ : null++ if (+ !saveContext ||+ saveContext.originLocation !== "user-collection" ||+ !saveContext.folderPath+ ) {+ return []+ }++ const indexPath = saveContext.folderPath+ const indexes = indexPath.split("/").map((x) => parseInt(x))++ // Walk the collection tree collecting names+ const names: string[] = []+ const cols = collections.value++ if (indexes.length === 0 || !cols.length) return []++ // First index is the root collection+ let current = cols[indexes[0]]+ if (!current) return []+ names.push(current.name)++ // Subsequent indexes traverse into folders+ for (let i = 1; i < indexes.length; i++) {+ const folder = current.folders[indexes[i]]+ if (!folder) break+ names.push(folder.name)+ current = folder+ }++ return names+})++// Every segment is width-capped (ellipsized by CSS),+// and deep paths collapse to `root > … > parent` with the hidden+// segments in the tooltip+const displayFolderPath = computed<{ name: string; tooltip: string }[]>(() => {+ const path = folderPath.value+ if (path.length <= 3) {+ return path.map((name) => ({ name, tooltip: name }))+ }+ return [+ { name: path[0], tooltip: path[0] },+ {+ name: "…",+ tooltip: path.slice(1, -1).join(" > "),+ },+ { name: path[path.length - 1], tooltip: path[path.length - 1] },+ ]+})++const switchToGQL = () => {+ if (!isREST.value) return+ const tab = tabs.currentActiveTab.value+ if (!tab || tab.document.type !== "request") return++ // Snapshot the current REST request as the REST draft so a later switch back+ // restores edits the user made before this protocol switch.+ tabs.setProtocolDraft(+ tab.id,+ "rest",+ tab.document.request,+ tab.document.isDirty+ )++ // If the user previously had GQL data on this tab, restore it verbatim.+ // Otherwise let the converter seed a fresh GQL request from the REST one.+ const gqlDraft = tabs.getProtocolDraft(tab.id)?.gql++ // Cancel the in-flight REST run before the document type flips — the runner+ // writes into `tab.document` from a subscription, not a component, so a late+ // response would land a HoppRESTResponse in a field typed GQLResponseEvent[].+ tab.document.cancelFunction?.()++ // The REST document's scroll offsets don't map onto the GQL panes+ scrollService.cleanupScrollForTab(tab.id)++ const gqlDoc = convertRESTToGQL(tab.document as HoppRequestDocument, gqlDraft)+ tab.document = gqlDoc+ tabs.updateTab(tab)+}++const switchToREST = () => {+ if (!isGQL.value) return+ const tab = tabs.currentActiveTab.value+ if (!tab || tab.document.type !== "gql-request") return++ // Snapshot the current GQL request as the GQL draft for round-trip preservation.+ tabs.setProtocolDraft(+ tab.id,+ "gql",+ tab.document.request,+ tab.document.isDirty+ )++ // Restore the previously-snapshotted REST request if any; else seed from GQL.+ const restDraft = tabs.getProtocolDraft(tab.id)?.rest++ const restDoc = convertGQLToREST(+ tab.document as HoppGQLRequestDocument,+ restDraft+ )++ // Tear down the GQL connection (poll timer, subscription socket, context+ // maps) before the document type flips to "request" — the close paths in+ // index.vue skip a tab that is no longer `gql-request`, so the context and+ // its 7s poll loop would leak for the page's lifetime.+ gqlTabConn.cleanupTab(tab.id)+ scrollService.cleanupScrollForTab(tab.id)++ tab.document = restDoc+ tabs.updateTab(tab)+}+</script>diff --git a/packages/hoppscotch-common/src/components/http/RawBody.vue b/packages/hoppscotch-common/src/components/http/RawBody.vueindex 9cb5179aa..1dcedb6fa 100644--- a/packages/hoppscotch-common/src/components/http/RawBody.vue+++ b/packages/hoppscotch-common/src/components/http/RawBody.vue@@ -108,6 +108,7 @@ import { toggleNestedSetting } from "~/newstore/settings"import { useAIExperiments } from "~/composables/ai-experiments"import { prettifyJSONC } from "~/helpers/editor/linting/jsoncPretty"import { useReadonlyStream } from "~/composables/stream"+import type { AggregateEnvironment } from "~/newstore/environments"import { platform } from "~/platform"import { invokeAction } from "~/helpers/actions"@@ -120,6 +121,8 @@ type Body = HoppRESTReqBody & { contentType: PossibleContentTypes }const props = defineProps<{modelValue: Body+ // Embed-only codemirror scope — workspace omits it to stay on the live stream+ scopedEnvs?: AggregateEnvironment[]}>()const emit = defineEmits<{@@ -180,6 +183,7 @@ useCodemirror(linter: langLinter,completer: null,environmentHighlights: true,+ envs: computed(() => props.scopedEnvs),predefinedVariablesHighlights: true,}))diff --git a/packages/hoppscotch-common/src/components/http/Request.vue b/packages/hoppscotch-common/src/components/http/Request.vueindex fa19dceec..82882fbe8 100644--- a/packages/hoppscotch-common/src/components/http/Request.vue+++ b/packages/hoppscotch-common/src/components/http/Request.vue@@ -227,7 +227,7 @@/><CollectionsSaveRequestv-if="showSaveRequestModal"- mode="rest"+ mode="workspace":show="showSaveRequestModal":request="request"@hide-modal="showSaveRequestModal = false"@@ -264,8 +264,8 @@ import { HoppRESTRequest } from "@hoppscotch/data"import { useService } from "dioc/vue"import { InspectionService } from "~/services/inspection"import { HoppTab } from "~/services/tab"-import { HoppRequestDocument } from "~/helpers/rest/document"-import { RESTTabService } from "~/services/tab/rest"+import { HoppRequestDocument } from "~/helpers/tab/document"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { getMethodLabelColor } from "~/helpers/rest/labelColoring"import { WorkspaceService } from "~/services/workspace.service"import { KernelInterceptorService } from "~/services/kernel-interceptor.service"@@ -333,7 +333,7 @@ const userHistories = computed(() => {const inspectionService = useService(InspectionService)-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const workspaceService = useService(WorkspaceService)@@ -588,6 +588,10 @@ const saveRequest = async () => {showSaveRequestModal.value = truereturn}+ // Ensure requestRefID is set in save context for active indicator+ if (!saveCtx.requestRefID && req._ref_id) {+ saveCtx.requestRefID = req._ref_id+ }editRESTRequest(saveCtx.folderPath, saveCtx.requestIndex, req)tab.value.document.isDirty = falsediff --git a/packages/hoppscotch-common/src/components/http/RequestOptions.vue b/packages/hoppscotch-common/src/components/http/RequestOptions.vueindex 91db5289a..c43197653 100644--- a/packages/hoppscotch-common/src/components/http/RequestOptions.vue+++ b/packages/hoppscotch-common/src/components/http/RequestOptions.vue@@ -5,15 +5,19 @@render-inactive-tabs><HoppSmartTab- v-if="properties?.includes('params') ?? true"+ v-if="showTab('params')":id="'params'":label="`${t('tab.parameters')}`":info="`${newActiveParamsCount}`">- <HttpParameters v-model="request.params" :envs="envs" />+ <HttpParameters+ v-model="request.params"+ :envs="envs"+ :scoped-envs="scopedEnvs"+ /></HoppSmartTab><HoppSmartTab- v-if="properties?.includes('bodyParams') ?? true"+ v-if="showTab('bodyParams')":id="'bodyParams'":label="`${t('tab.body')}`":indicator="isBodyFilled"@@ -22,11 +26,12 @@v-model:headers="request.headers"v-model:body="request.body":envs="envs"+ :scoped-envs="scopedEnvs"@change-tab="changeOptionTab"/></HoppSmartTab><HoppSmartTab- v-if="properties?.includes('headers') ?? true"+ v-if="showTab('headers')":id="'headers'":label="`${t('tab.headers')}`":info="`${newActiveHeadersCount}`"@@ -35,11 +40,12 @@v-model="request":inherited-properties="inheritedProperties":envs="envs"+ :scoped-envs="scopedEnvs"@change-tab="changeOptionTab"/></HoppSmartTab><HoppSmartTab- v-if="properties?.includes('authorization') ?? true"+ v-if="showTab('authorization')":id="'authorization'":label="`${t('tab.authorization')}`">@@ -47,6 +53,7 @@v-model="request.auth":inherited-properties="inheritedProperties":envs="envs"+ :scoped-envs="scopedEnvs"/></HoppSmartTab><HoppSmartTab@@ -83,7 +90,7 @@/></HoppSmartTab><HoppSmartTab- v-if="properties?.includes('requestVariables') ?? true"+ v-if="showTab('requestVariables')":id="'requestVariables'":label="`${t('tab.variables')}`":info="`${newActiveRequestVariablesCount}`"@@ -130,9 +137,12 @@ const props = withDefaults(properties?: string[]inheritedProperties?: HoppInheritedPropertyenvs?: AggregateEnvironment[]+ // Embed-only codemirror scope — `envs` alone must keep workspace editors live+ scopedEnvs?: AggregateEnvironment[]}>(),{optionTab: "params",+ scopedEnvs: undefined,})@@ -144,15 +154,27 @@ const emit = defineEmits<{const request = useVModel(props, "modelValue", emit)const selectedOptionTab = useVModel(props, "optionTab", emit)+// Treat both `undefined` and `[]` as "no filter — show everything". The+// embed customize flow can persist an empty options array when the share-er+// disables all toggles; without this guard a `.includes()` returns false+// for every tab and the embed renders a blank options panel.+const hasPropertyFilter = computed(+ () => Array.isArray(props.properties) && props.properties.length > 0+)++const showTab = (id: RESTOptionTabs) => {+ if (!hasPropertyFilter.value) return true+ return props.properties!.includes(id)+}+const showPreRequestScriptTab = computed(() => {- return (- props.properties?.includes("preRequestScript") ??- "preRequestScript" in request.value- )+ if (!hasPropertyFilter.value) return "preRequestScript" in request.value+ return props.properties!.includes("preRequestScript")})const showTestsTab = computed(() => {- return props.properties?.includes("tests") ?? "testScript" in request.value+ if (!hasPropertyFilter.value) return "testScript" in request.value+ return props.properties!.includes("tests")})const changeOptionTab = (e: RESTOptionTabs) => {diff --git a/packages/hoppscotch-common/src/components/http/RequestTab.vue b/packages/hoppscotch-common/src/components/http/RequestTab.vueindex 8cf5acb38..2d43e03da 100644--- a/packages/hoppscotch-common/src/components/http/RequestTab.vue+++ b/packages/hoppscotch-common/src/components/http/RequestTab.vue@@ -25,7 +25,7 @@ import { useVModel } from "@vueuse/core"import { cloneDeep } from "lodash-es"import { isEqualHoppRESTRequest } from "@hoppscotch/data"import { HoppTab } from "~/services/tab"-import { HoppRequestDocument } from "~/helpers/rest/document"+import { HoppRequestDocument } from "~/helpers/tab/document"import { useReadonlyStream } from "@composables/stream"import {aggregateEnvsWithCurrentValue$,diff --git a/packages/hoppscotch-common/src/components/http/RequestVariables.vue b/packages/hoppscotch-common/src/components/http/RequestVariables.vueindex 6c90c0bc8..ab07f8e8c 100644--- a/packages/hoppscotch-common/src/components/http/RequestVariables.vue+++ b/packages/hoppscotch-common/src/components/http/RequestVariables.vue@@ -366,12 +366,10 @@ const deleteVariable = (index: number) => {workingRequestVariables.value)- if (- !(- requestVariablesBeforeDeletion.length > 0 &&- index === requestVariablesBeforeDeletion.length - 1- )- ) {+ if (!(+ requestVariablesBeforeDeletion.length > 0 &&+ index === requestVariablesBeforeDeletion.length - 1+ )) {if (deletionToast.value) {deletionToast.value.goAway(0)deletionToast.value = nulldiff --git a/packages/hoppscotch-common/src/components/http/Response.vue b/packages/hoppscotch-common/src/components/http/Response.vueindex 40cd0663e..9f732376a 100644--- a/packages/hoppscotch-common/src/components/http/Response.vue+++ b/packages/hoppscotch-common/src/components/http/Response.vue@@ -25,7 +25,7 @@<script setup lang="ts">import { useVModel } from "@vueuse/core"import { computed, ref } from "vue"-import { HoppRequestDocument } from "~/helpers/rest/document"+import { HoppRequestDocument } from "~/helpers/tab/document"import { useResponseBody } from "@composables/lens-actions"import { getStatusCodeReasonPhrase } from "~/helpers/utils/statusCodes"import {diff --git a/packages/hoppscotch-common/src/components/http/ResponseInterface.vue b/packages/hoppscotch-common/src/components/http/ResponseInterface.vueindex 732714c53..0f130aae2 100644--- a/packages/hoppscotch-common/src/components/http/ResponseInterface.vue+++ b/packages/hoppscotch-common/src/components/http/ResponseInterface.vue@@ -140,7 +140,7 @@ import {Language,} from "~/helpers/utils/interfaceLanguages"import { toggleNestedSetting } from "~/newstore/settings"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import IconCheck from "~icons/lucide/check"import IconWrapText from "~icons/lucide/wrap-text"import jsonToLanguage from "~/helpers/utils/json-to-language"@@ -159,7 +159,7 @@ const emit = defineEmits<{(e: "close"): void}>()-const restTabs = useService(RESTTabService)+const workspaceTabs = useService(WorkspaceTabsService)const gqlTabs = useService(GQLTabService)function getCurrentPageCategory(): "graphql" | "rest" | "other" {@@ -183,7 +183,7 @@ const response = computed(() => {const pageCategory = getCurrentPageCategory()if (pageCategory === "rest") {- const doc = restTabs.currentActiveTab.value.document+ const doc = workspaceTabs.currentActiveTab.value.documentif (doc.type === "request") {const res = doc.responseif (res?.type === "success" || res?.type === "fail") {diff --git a/packages/hoppscotch-common/src/components/http/ResponseMeta.vue b/packages/hoppscotch-common/src/components/http/ResponseMeta.vueindex 700c284cd..712a53df1 100644--- a/packages/hoppscotch-common/src/components/http/ResponseMeta.vue+++ b/packages/hoppscotch-common/src/components/http/ResponseMeta.vue@@ -143,12 +143,12 @@ import { useColorMode } from "@composables/theming"import { getStatusCodeReasonPhrase } from "~/helpers/utils/statusCodes"import { useService } from "dioc/vue"import { InspectionService } from "~/services/inspection"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import IconExternalLink from "~icons/lucide/external-link"const t = useI18n()const colorMode = useColorMode()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const props = withDefaults(defineProps<{diff --git a/packages/hoppscotch-common/src/components/http/Sidebar.vue b/packages/hoppscotch-common/src/components/http/Sidebar.vueindex 36ad55dd4..13a04d921 100644--- a/packages/hoppscotch-common/src/components/http/Sidebar.vue+++ b/packages/hoppscotch-common/src/components/http/Sidebar.vue@@ -5,6 +5,27 @@verticalrender-inactive-tabs>+ <!-- GQL-specific tabs: Docs and Schema (shown when GQL tab is active) -->+ <HoppSmartTab+ v-if="isGQLTab"+ :id="'docs'"+ :icon="IconBookOpen"+ :label="`${t('tab.documentation')}`"+ :order="-2"+ >+ <GqlDocExplorer :key="activeGQLTabId" />+ </HoppSmartTab>+ <HoppSmartTab+ v-if="isGQLTab"+ :id="'schema'"+ :icon="IconBox"+ :label="`${t('tab.schema')}`"+ :order="-1"+ >+ <GqlSchema :key="activeGQLTabId" />+ </HoppSmartTab>++ <!-- Standard REST sidebar tabs --><HoppSmartTab:id="'collections'":icon="IconFolder"@@ -24,9 +45,13 @@:icon="IconClock":label="`${t('tab.history')}`">- <History :page="'rest'" :selected-tab="selectedNavigationTab" />+ <History+ :page="isGqlWorkspaceEnabled ? 'unified-workspace' : 'rest'"+ :selected-tab="selectedNavigationTab"+ /></HoppSmartTab><HoppSmartTab+ v-if="isRequestBearingTab":id="'share-request'":icon="IconShare2":label="`${t('tab.shared_requests')}`"@@ -34,6 +59,7 @@<Share /></HoppSmartTab><HoppSmartTab+ v-if="!isGQLTab && isRequestBearingTab":id="'codegen'":icon="IconCode":label="`${t('tab.codegen')}`"@@ -65,26 +91,59 @@<MockServerDashboard v-if="selectedNavigationTab === 'mock-servers'" /></HoppSmartTab></HoppSmartTabs>+ <!-- Share hosts the app's only `share.request` action handler (and its+ modals). When its sidebar tab is hidden for non-request tabs, keep one+ hidden instance mounted so sharing a request tab from the collections+ tree / tab-head context menu still works (main kept it always mounted+ via render-inactive-tabs). -->+ <div v-if="!isRequestBearingTab" class="hidden">+ <Share />+ </div></template><script setup lang="ts">+import IconBookOpen from "~icons/lucide/book-open"+import IconBox from "~icons/lucide/box"import IconClock from "~icons/lucide/clock"import IconLayers from "~icons/lucide/layers"import IconFolder from "~icons/lucide/folder"import IconShare2 from "~icons/lucide/share-2"import IconCode from "~icons/lucide/code"import IconServer from "~icons/lucide/server"-import { ref } from "vue"+import { computed, ref, watch } from "vue"import { useI18n } from "@composables/i18n"+import { useService } from "dioc/vue"import MockServerDashboard from "~/components/mockServer/MockServerDashboard.vue"import { useMockServerWorkspaceSync } from "~/composables/mockServerWorkspace"import { useMockServerVisibility } from "~/composables/mockServerVisibility"+import { useGqlWorkspaceVisibility } from "~/composables/gqlWorkspaceVisibility"+import { GQLTabConnectionService } from "~/services/gql-tab-connection.service"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"const t = useI18n()+const tabs = useService(WorkspaceTabsService)+const gqlTabConn = useService(GQLTabConnectionService)++const activeGQLTabId = gqlTabConn.activeGQLTabId+const { isMockServerVisible } = useMockServerVisibility()+const { isGqlWorkspaceEnabled } = useGqlWorkspaceVisibility()++const activeDocType = computed(() => tabs.currentActiveTab.value?.document.type)++const isGQLTab = computed(() => activeDocType.value === "gql-request")++// Share and Codegen operate on the active tab's request — hide them for+// documents that carry no live request (test-runner, saved examples)+const isRequestBearingTab = computed(+ () =>+ activeDocType.value === "request" || activeDocType.value === "gql-request"+)type RequestOptionTabs =+ | "docs"+ | "schema"| "history"| "collections"| "env"@@ -94,6 +153,25 @@ type RequestOptionTabs =const selectedNavigationTab = ref<RequestOptionTabs>("collections")+// GQL-only, HTTP-only, and request-only sidebar tab IDs — used to reset when+// the active tab's document type changes+const gqlOnlyTabs: RequestOptionTabs[] = ["docs", "schema"]+const httpOnlyTabs: RequestOptionTabs[] = ["codegen"]+const requestOnlyTabs: RequestOptionTabs[] = ["share-request", "codegen"]++// When the active document type changes, reset sidebar selection if the+// current selection is no longer visible (preventing stale/invisible tab state)+watch([isGQLTab, isRequestBearingTab], ([nowGQL, requestBearing]) => {+ const selected = selectedNavigationTab.value+ if (+ (nowGQL && httpOnlyTabs.includes(selected)) ||+ (!nowGQL && gqlOnlyTabs.includes(selected)) ||+ (!requestBearing && requestOnlyTabs.includes(selected))+ ) {+ selectedNavigationTab.value = "collections"+ }+})+// Ensure mock servers are kept in sync with workspace changes globallyuseMockServerWorkspaceSync()</script>diff --git a/packages/hoppscotch-common/src/components/http/TabHead.vue b/packages/hoppscotch-common/src/components/http/TabHead.vueindex c986d1bfd..b1ddf3de5 100644--- a/packages/hoppscotch-common/src/components/http/TabHead.vue+++ b/packages/hoppscotch-common/src/components/http/TabHead.vue@@ -123,7 +123,7 @@ import { HoppTab } from "~/services/tab"import {HoppRequestDocument,HoppSavedExampleDocument,-} from "~/helpers/rest/document"+} from "~/helpers/tab/document"import { restCollectionStore } from "~/newstore/collections"const t = useI18n()@@ -141,10 +141,18 @@ const tabState = computed(() => {request: props.tab.document.request,}}+ if (props.tab.document.type === "example-response") {+ return {+ name: props.tab.document.response.name,+ method: props.tab.document.response.originalRequest.method,+ request: props.tab.document.response.originalRequest,+ }+ }+ // Fallback for transient states (e.g., during protocol switch)return {- name: props.tab.document.response.name,- method: props.tab.document.response.originalRequest.method,- request: props.tab.document.response.originalRequest,+ name: "Untitled",+ method: "GET",+ request: null,}})diff --git a/packages/hoppscotch-common/src/components/http/TestResultEntry.vue b/packages/hoppscotch-common/src/components/http/TestResultEntry.vueindex b4a829464..86cb2c6d3 100644--- a/packages/hoppscotch-common/src/components/http/TestResultEntry.vue+++ b/packages/hoppscotch-common/src/components/http/TestResultEntry.vue@@ -77,6 +77,14 @@ import {import IconCheck from "~icons/lucide/check"import IconClose from "~icons/lucide/x"+// The template renders `<HttpTestResultEntry>` recursively for nested test+// groups. Auto-imported component names are resolved per-file by+// unplugin-vue-components, which can't import a file into itself, so the+// recursive tag only resolves via Vue's self-name lookup — which needs the+// component's own `name` to match the tag. Without this, nested groups fail+// to resolve and silently render nothing.+defineOptions({ name: "HttpTestResultEntry" })+const t = useI18n()const props = withDefaults(diff --git a/packages/hoppscotch-common/src/components/http/Tests.vue b/packages/hoppscotch-common/src/components/http/Tests.vueindex 5ef7852e9..74241a795 100644--- a/packages/hoppscotch-common/src/components/http/Tests.vue+++ b/packages/hoppscotch-common/src/components/http/Tests.vue@@ -127,7 +127,7 @@ import testSnippets from "~/helpers/testSnippets"import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"import { toggleNestedSetting } from "~/newstore/settings"import { platform } from "~/platform"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import IconFileSymlink from "~icons/lucide/file-symlink"import IconHelpCircle from "~icons/lucide/help-circle"import IconSparkles from "~icons/lucide/sparkles"@@ -185,7 +185,7 @@ const useSnippet = (script: string) => {const clearContent = () => {testScript.value = ""}-const tabService = useService(RESTTabService)+const tabService = useService(WorkspaceTabsService)const currentRequest = computed(() =>tabService.currentActiveTab.value?.document.type === "request"diff --git a/packages/hoppscotch-common/src/components/http/URLEncodedParams.vue b/packages/hoppscotch-common/src/components/http/URLEncodedParams.vueindex e2ab3ab2c..f11abc10e 100644--- a/packages/hoppscotch-common/src/components/http/URLEncodedParams.vue+++ b/packages/hoppscotch-common/src/components/http/URLEncodedParams.vue@@ -222,6 +222,8 @@ type Body = HoppRESTReqBody & {const props = defineProps<{modelValue: Bodyenvs: AggregateEnvironment[]+ // Embed-only codemirror scope — `envs` alone must keep workspace editors live+ scopedEnvs?: AggregateEnvironment[]}>()const emit = defineEmits<{@@ -340,12 +342,10 @@ const deleteUrlEncodedParam = (index: number) => {workingUrlEncodedParams.value)- if (- !(- urlEncodedParamsBeforeDeletion.length > 0 &&- index === urlEncodedParamsBeforeDeletion.length - 1- )- ) {+ if (!(+ urlEncodedParamsBeforeDeletion.length > 0 &&+ index === urlEncodedParamsBeforeDeletion.length - 1+ )) {if (deletionToast.value) {deletionToast.value.goAway(0)deletionToast.value = null@@ -440,6 +440,7 @@ useCodemirror(linter,completer: null,environmentHighlights: true,+ envs: computed(() => props.scopedEnvs),predefinedVariablesHighlights: true,}))diff --git a/packages/hoppscotch-common/src/components/http/authorization/ASAP.vue b/packages/hoppscotch-common/src/components/http/authorization/ASAP.vueindex 971053c30..936ef4839 100644--- a/packages/hoppscotch-common/src/components/http/authorization/ASAP.vue+++ b/packages/hoppscotch-common/src/components/http/authorization/ASAP.vue@@ -143,7 +143,7 @@ import IconCircleDot from "~icons/lucide/circle-dot"import { useI18n } from "@composables/i18n"import { HoppRESTAuthASAP } from "@hoppscotch/data"import { useVModel } from "@vueuse/core"-import { ref } from "vue"+import { ref, computed } from "vue"import { AggregateEnvironment } from "~/newstore/environments"import { useCodemirror } from "~/composables/codemirror"import { reactive } from "vue"@@ -156,6 +156,7 @@ const t = useI18n()const props = defineProps<{modelValue: HoppRESTAuthASAPenvs?: AggregateEnvironment[]+ scopedEnvs?: AggregateEnvironment[]}>()const emit = defineEmits<{@@ -181,6 +182,7 @@ useCodemirror(linter: JSONLinter,completer: null,environmentHighlights: true,+ envs: computed(() => props.scopedEnvs),}))diff --git a/packages/hoppscotch-common/src/components/http/authorization/JWT.vue b/packages/hoppscotch-common/src/components/http/authorization/JWT.vueindex 1cf9988e9..2e05e72c9 100644--- a/packages/hoppscotch-common/src/components/http/authorization/JWT.vue+++ b/packages/hoppscotch-common/src/components/http/authorization/JWT.vue@@ -193,9 +193,11 @@ const props = withDefaults(defineProps<{modelValue: HoppRESTAuthJWTenvs?: AggregateEnvironment[]+ scopedEnvs?: AggregateEnvironment[]}>(),{envs: undefined,+ scopedEnvs: undefined,})@@ -253,6 +255,7 @@ useCodemirror(linter: null,completer: null,environmentHighlights: true,+ envs: computed(() => props.scopedEnvs),}))@@ -269,6 +272,7 @@ useCodemirror(linter: null,completer: null,environmentHighlights: true,+ envs: computed(() => props.scopedEnvs),}))@@ -287,6 +291,7 @@ Your private key herelinter: null,completer: null,environmentHighlights: true,+ envs: computed(() => props.scopedEnvs),}))diff --git a/packages/hoppscotch-common/src/components/http/authorization/OAuth2.vue b/packages/hoppscotch-common/src/components/http/authorization/OAuth2.vueindex f9b0f73dc..492caf3ff 100644--- a/packages/hoppscotch-common/src/components/http/authorization/OAuth2.vue+++ b/packages/hoppscotch-common/src/components/http/authorization/OAuth2.vue@@ -563,7 +563,7 @@ import {import * as E from "fp-ts/Either"import { PersistenceService } from "~/services/persistence"import { GQLTabService } from "~/services/tab/graphql"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import IconChevronDown from "~icons/lucide/chevron-down"import IconChevronUp from "~icons/lucide/chevron-up"import IconCircle from "~icons/lucide/circle"@@ -670,7 +670,7 @@ const passBy = computed(() => {})const gqlTabsService = useService(GQLTabService)-const restTabsService = useService(RESTTabService)+const workspaceTabsService = useService(WorkspaceTabsService)const persistenceService = useService(PersistenceService)const setAccessTokenInActiveContext = (@@ -699,24 +699,25 @@ const setAccessTokenInActiveContext = (}if (props.source === "REST") {- const restTab = restTabsService.currentActiveTab.value+ const workspaceTab = workspaceTabsService.currentActiveTab.valueif (- "request" in restTab.document &&- restTab.document.request &&- restTab.document.request.auth.authType === "oauth-2" &&+ "request" in workspaceTab.document &&+ workspaceTab.document.request &&+ workspaceTab.document.request.auth.authType === "oauth-2" &&accessToken) {- restTab.document.request.auth.grantTypeInfo.token = accessToken+ workspaceTab.document.request.auth.grantTypeInfo.token = accessToken}if (refreshToken &&- "request" in restTab.document &&- restTab.document.request &&- restTab.document.request.auth.authType === "oauth-2"+ "request" in workspaceTab.document &&+ workspaceTab.document.request &&+ workspaceTab.document.request.auth.authType === "oauth-2") {// @ts-expect-error - TODO: narrow the grantType to only supporting refresh tokens- restTab.document.request.auth.grantTypeInfo.refreshToken = refreshToken+ workspaceTab.document.request.auth.grantTypeInfo.refreshToken =+ refreshToken}} else {const gqlTab = gqlTabsService.currentActiveTab.valuediff --git a/packages/hoppscotch-common/src/components/http/example/LenseBodyRenderer.vue b/packages/hoppscotch-common/src/components/http/example/LenseBodyRenderer.vueindex 4cc0bef33..97dae810e 100644--- a/packages/hoppscotch-common/src/components/http/example/LenseBodyRenderer.vue+++ b/packages/hoppscotch-common/src/components/http/example/LenseBodyRenderer.vue@@ -15,6 +15,7 @@v-model:response="doc.response":is-savable="false":is-editable="true"+ :tab-id="tabId"@save-as-example="$emit('save-as-example')"/></HoppSmartTab>@@ -45,10 +46,11 @@ import { useVModel } from "@vueuse/core"import {HoppRequestDocument,HoppSavedExampleDocument,-} from "~/helpers/rest/document"+} from "~/helpers/tab/document"const props = defineProps<{document: HoppSavedExampleDocument+ tabId: string}>()const emit = defineEmits<{diff --git a/packages/hoppscotch-common/src/components/http/example/Response.vue b/packages/hoppscotch-common/src/components/http/example/Response.vueindex b99dfcf90..e43d71647 100644--- a/packages/hoppscotch-common/src/components/http/example/Response.vue+++ b/packages/hoppscotch-common/src/components/http/example/Response.vue@@ -1,6 +1,6 @@<template><HttpExampleResponseMeta v-model:response="doc.response" />- <HttpExampleLenseBodyRenderer v-model:document="doc" />+ <HttpExampleLenseBodyRenderer v-model:document="doc" :tab-id="tabId" /></template><script setup lang="ts">@@ -8,11 +8,12 @@ import { useVModel } from "@vueuse/core"import {HoppRequestDocument,HoppSavedExampleDocument,-} from "~/helpers/rest/document"+} from "~/helpers/tab/document"const props = defineProps<{document: HoppSavedExampleDocumentisEmbed: boolean+ tabId: string}>()const emit = defineEmits<{diff --git a/packages/hoppscotch-common/src/components/http/example/ResponseRequest.vue b/packages/hoppscotch-common/src/components/http/example/ResponseRequest.vueindex 4dba1dd32..20fe457e0 100644--- a/packages/hoppscotch-common/src/components/http/example/ResponseRequest.vue+++ b/packages/hoppscotch-common/src/components/http/example/ResponseRequest.vue@@ -93,8 +93,8 @@ import { getDefaultRESTRequest } from "~/helpers/rest/default"import { useService } from "dioc/vue"import { InspectionService } from "~/services/inspection"import { HoppTab } from "~/services/tab"-import { HoppSavedExampleDocument } from "~/helpers/rest/document"-import { RESTTabService } from "~/services/tab/rest"+import { HoppSavedExampleDocument } from "~/helpers/tab/document"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { getMethodLabelColor } from "~/helpers/rest/labelColoring"import IconSave from "~icons/lucide/save"import { editRESTRequest, restCollections$ } from "~/newstore/collections"@@ -129,7 +129,7 @@ const toast = useToast()const props = defineProps<{ modelValue: HoppTab<HoppSavedExampleDocument> }>()const emit = defineEmits(["update:modelValue"])-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const tab = useVModel(props, "modelValue", emit)diff --git a/packages/hoppscotch-common/src/components/http/example/ResponseTab.vue b/packages/hoppscotch-common/src/components/http/example/ResponseTab.vueindex d619ee011..b5d5b6f33 100644--- a/packages/hoppscotch-common/src/components/http/example/ResponseTab.vue+++ b/packages/hoppscotch-common/src/components/http/example/ResponseTab.vue@@ -10,7 +10,11 @@/></template><template #secondary>- <HttpExampleResponse v-model:document="tab.document" :is-embed="false" />+ <HttpExampleResponse+ v-model:document="tab.document"+ :is-embed="false"+ :tab-id="tab.id"+ /></template></AppPaneLayout></template>@@ -20,7 +24,7 @@ import { watch, ref, computed } from "vue"import { useVModel } from "@vueuse/core"import { cloneDeep, isEqual } from "lodash-es"import { HoppTab } from "~/services/tab"-import { HoppSavedExampleDocument } from "~/helpers/rest/document"+import { HoppSavedExampleDocument } from "~/helpers/tab/document"import { RESTOptionTabs } from "../RequestOptions.vue"import { useReadonlyStream } from "@composables/stream"import {diff --git a/packages/hoppscotch-common/src/components/http/test/Response.vue b/packages/hoppscotch-common/src/components/http/test/Response.vueindex dc7a7ece0..03fda638f 100644--- a/packages/hoppscotch-common/src/components/http/test/Response.vue+++ b/packages/hoppscotch-common/src/components/http/test/Response.vue@@ -46,7 +46,7 @@ import { useVModel } from "@vueuse/core"import { computed } from "vue"import { useI18n } from "~/composables/i18n"import { useColorMode } from "~/composables/theming"-import { HoppRequestDocument } from "~/helpers/rest/document"+import { HoppRequestDocument } from "~/helpers/tab/document"import { TestRunnerRequest } from "~/services/test-runner/test-runner.service"const t = useI18n()diff --git a/packages/hoppscotch-common/src/components/http/test/ResultRequest.vue b/packages/hoppscotch-common/src/components/http/test/ResultRequest.vueindex 9ddb69762..6b7ff9839 100644--- a/packages/hoppscotch-common/src/components/http/test/ResultRequest.vue+++ b/packages/hoppscotch-common/src/components/http/test/ResultRequest.vue@@ -19,13 +19,20 @@</template></span><span+ v-if="requestChip.kind === 'rest'"class="flex items-center justify-center truncate pointer-events-none":style="{ color: requestLabelColor }"><span class="font-bold truncate">- {{ request.method }}+ {{ requestChip.method }}</span></span>+ <span+ v-else+ class="flex items-center justify-center pointer-events-none text-accent"+ >+ <component :is="IconGraphql" class="h-4 w-4" />+ </span><span class="truncate text-sm text-secondaryDark">{{ request.name }}</span>@@ -61,7 +68,7 @@</div><p class="text-left text-secondaryLight text-sm">- {{ request.endpoint }}+ {{ requestTarget }}</p></button>@@ -87,8 +94,10 @@import { computed } from "vue"import findStatusGroup from "~/helpers/findStatusGroup"import { getMethodLabelColorClassOf } from "~/helpers/rest/labelColoring"+import { isRESTRequest } from "~/helpers/request-type"import { getStatusCodePhrase } from "~/helpers/utils/statusCodes"import { TestRunnerRequest } from "~/services/test-runner/test-runner.service"+import IconGraphql from "~icons/hopp/graphql"import IconChevronRight from "~icons/lucide/chevron-right"import IconFolder from "~icons/lucide/folder"@@ -160,8 +169,22 @@ const emit = defineEmits<{(event: "select-request"): void}>()+// Per-entry protocol discrimination — unified collections mix REST and+// GraphQL requests in the same run.+const requestChip = computed(() =>+ isRESTRequest(props.request)+ ? { kind: "rest" as const, method: props.request.method }+ : { kind: "gql" as const }+)++const requestTarget = computed(() =>+ isRESTRequest(props.request) ? props.request.endpoint : props.request.url+)+const requestLabelColor = computed(() =>- getMethodLabelColorClassOf(props.request.method)+ requestChip.value.kind === "rest"+ ? getMethodLabelColorClassOf(requestChip.value.method)+ : "")const selectRequest = () => {diff --git a/packages/hoppscotch-common/src/components/http/test/Runner.vue b/packages/hoppscotch-common/src/components/http/test/Runner.vueindex 65ff47407..73ec32f50 100644--- a/packages/hoppscotch-common/src/components/http/test/Runner.vue+++ b/packages/hoppscotch-common/src/components/http/test/Runner.vue@@ -181,6 +181,23 @@</template></HoppSmartPlaceholder>+ <!-- Selected row without a response — restored runner tabs lose+ response bodies (ArrayBuffers don't survive the JSON round-trip),+ so a row click after refresh lands here instead of a blank pane. -->+ <HoppSmartPlaceholder+ v-else-if="selectedRequest && !selectedRequest.response"+ :src="`/images/states/${colorMode.value}/pack.svg`"+ :alt="`${t('collection_runner.response_body_lost_rerun')}`"+ :text="`${t('collection_runner.response_body_lost_rerun')}`"+ >+ <template #body>+ <HoppButtonPrimary+ :label="t('test.new_run')"+ @click="showCollectionsRunnerModal = true"+ />+ </template>+ </HoppSmartPlaceholder>+<HoppSmartPlaceholderv-else-if="!selectedRequest":src="`/images/states/${colorMode.value}/pack.svg`"@@ -234,7 +251,7 @@ import {import {HoppTestRunnerDocument,TestRunnerIterationResult,-} from "~/helpers/rest/document"+} from "~/helpers/tab/document"import {CollectionNode,TestRunnerCollectionsAdapter,@@ -252,7 +269,7 @@ import {getSelectedEnvironmentType,} from "~/newstore/environments"import { HoppTab } from "~/services/tab"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { TeamCollectionsService } from "~/services/team-collection.service"import {TestRunnerRequest,@@ -281,7 +298,7 @@ const emit = defineEmits<{(e: "update:modelValue", val: HoppTab<HoppTestRunnerDocument>): void}>()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const tab = useVModel(props, "modelValue", emit)// The sticky run header spans two rows of variable-height content (longdiff --git a/packages/hoppscotch-common/src/components/http/test/RunnerModal.vue b/packages/hoppscotch-common/src/components/http/test/RunnerModal.vueindex 6e0a7318f..b1f9d080e 100644--- a/packages/hoppscotch-common/src/components/http/test/RunnerModal.vue+++ b/packages/hoppscotch-common/src/components/http/test/RunnerModal.vue@@ -466,11 +466,11 @@ import { useI18n } from "~/composables/i18n"import { HoppCollection } from "@hoppscotch/data"import { useService } from "dioc/vue"import { useToast } from "~/composables/toast"-import { TestRunnerConfig } from "~/helpers/rest/document"+import { TestRunnerConfig } from "~/helpers/tab/document"import { parseDatasetFile } from "~/helpers/runner/dataset"import { collectRequestIDs } from "~/helpers/runner/selection"import { copyToClipboard } from "~/helpers/utils/clipboard"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import IconCheck from "~icons/lucide/check"import IconCopy from "~icons/lucide/copy"import IconEye from "~icons/lucide/eye"@@ -493,7 +493,7 @@ import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"const t = useI18n()const toast = useToast()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const loadingCollection = ref(false)diff --git a/packages/hoppscotch-common/src/components/http/test/RunnerRequestSelector.vue b/packages/hoppscotch-common/src/components/http/test/RunnerRequestSelector.vueindex b86a35807..2fd23c75c 100644--- a/packages/hoppscotch-common/src/components/http/test/RunnerRequestSelector.vue+++ b/packages/hoppscotch-common/src/components/http/test/RunnerRequestSelector.vue@@ -50,11 +50,15 @@</span><span+ v-if="entry.kind === 'rest'"class="font-bold text-tiny flex-shrink-0":style="{ color: entry.methodColor }">{{ entry.method }}</span>+ <span v-else class="flex flex-shrink-0 items-center text-accent">+ <component :is="IconGraphql" class="h-4 w-4" />+ </span><span class="truncate">{{ entry.name }}</span></label></template>@@ -66,12 +70,14 @@</template><script setup lang="ts">-import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data"+import { HoppCollection } from "@hoppscotch/data"import { computed } from "vue"import draggable from "vuedraggable-es"import { useI18n } from "~/composables/i18n"+import { isRESTRequest } from "~/helpers/request-type"import { getMethodLabelColorClassOf } from "~/helpers/rest/labelColoring"import { getRequestSelectionID } from "~/helpers/runner/selection"+import IconGraphql from "~icons/hopp/graphql"import IconChevronRight from "~icons/lucide/chevron-right"import IconFolder from "~icons/lucide/folder"import IconGripVertical from "~icons/lucide/grip-vertical"@@ -97,6 +103,8 @@ const emit = defineEmits<{type Entry = {id: stringname: string+ kind: "rest" | "gql"+ /** Filter text for GQL rows is the literal "GQL". */method: stringmethodColor: string/** Folder names from the collection root down to the request's parent. */@@ -125,15 +133,16 @@ const flatten = (),...collection.requests.map((request, index): Entry => {const path = [...parentPath, index]+ // Unified collections hold both protocols; GQL requests have no `method`+ const rest = isRESTRequest(request)return {- id: getRequestSelectionID(request as HoppRESTRequest, path),+ id: getRequestSelectionID(request, path),name: request.name,- method: request.method,- methodColor: getMethodLabelColorClassOf(request.method),+ kind: rest ? "rest" : "gql",+ method: rest ? request.method : "GQL",+ methodColor: rest ? getMethodLabelColorClassOf(request.method) : "",path: folderNames,- selected: props.selectedIDs.has(- getRequestSelectionID(request as HoppRESTRequest, path)- ),+ selected: props.selectedIDs.has(getRequestSelectionID(request, path)),}}),]diff --git a/packages/hoppscotch-common/src/components/http/test/RunnerResult.vue b/packages/hoppscotch-common/src/components/http/test/RunnerResult.vueindex f1c4f2651..344f130e0 100644--- a/packages/hoppscotch-common/src/components/http/test/RunnerResult.vue+++ b/packages/hoppscotch-common/src/components/http/test/RunnerResult.vue@@ -115,7 +115,7 @@ import { SmartTreeAdapter } from "@hoppscotch/ui"import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"import { useI18n } from "~/composables/i18n"import { useColorMode } from "~/composables/theming"-import { HoppTestRunnerDocument } from "~/helpers/rest/document"+import { HoppTestRunnerDocument } from "~/helpers/tab/document"import { HoppTab } from "~/services/tab"import { TestRunnerRequest } from "~/services/test-runner/test-runner.service"diff --git a/packages/hoppscotch-common/src/components/importExport/ImportExportSteps/AllCollectionImport.vue b/packages/hoppscotch-common/src/components/importExport/ImportExportSteps/AllCollectionImport.vueindex bbf8adf95..36106a767 100644--- a/packages/hoppscotch-common/src/components/importExport/ImportExportSteps/AllCollectionImport.vue+++ b/packages/hoppscotch-common/src/components/importExport/ImportExportSteps/AllCollectionImport.vue@@ -99,7 +99,7 @@ import { useReadonlyStream } from "~/composables/stream"import { runGQLQuery } from "~/helpers/backend/GQLClient"import { RootCollectionsOfTeamDocument } from "~/helpers/backend/graphql"import { getTeamCollectionObject } from "~/helpers/backend/helpers"-import { TEAMS_BACKEND_PAGE_SIZE } from "~/helpers/teams/TeamCollectionAdapter"+import { TEAMS_BACKEND_PAGE_SIZE } from "~/services/team-collection.service"import { getRESTCollection, restCollections$ } from "~/newstore/collections"import { WorkspaceService } from "~/services/workspace.service"import * as E from "fp-ts/Either"diff --git a/packages/hoppscotch-common/src/components/importExport/ImportExportSteps/ImportSummary.vue b/packages/hoppscotch-common/src/components/importExport/ImportExportSteps/ImportSummary.vueindex 72966e97c..13b072115 100644--- a/packages/hoppscotch-common/src/components/importExport/ImportExportSteps/ImportSummary.vue+++ b/packages/hoppscotch-common/src/components/importExport/ImportExportSteps/ImportSummary.vue@@ -125,11 +125,7 @@ import { SupportedImportFormat } from "./../types"const t = useI18n()type Feature =- | "collections"- | "requests"- | "responses"- | "preRequestScripts"- | "testScripts"+ "collections" | "requests" | "responses" | "preRequestScripts" | "testScripts"type FeatureStatus =| "SUPPORTED"diff --git a/packages/hoppscotch-common/src/components/importExport/types.ts b/packages/hoppscotch-common/src/components/importExport/types.tsindex a5aed5896..52d93f830 100644--- a/packages/hoppscotch-common/src/components/importExport/types.ts+++ b/packages/hoppscotch-common/src/components/importExport/types.ts@@ -3,11 +3,7 @@ import { Component, Ref } from "vue"import { defineStep } from "~/composables/step-components"export type SupportedImportFormat =- | "hoppscotch"- | "postman"- | "insomnia"- | "openapi"- | "har"+ "hoppscotch" | "postman" | "insomnia" | "openapi" | "har"// TODO: move the metadata except disabled and isLoading to importers.tsexport type ImporterOrExporter = {diff --git a/packages/hoppscotch-common/src/components/lenses/ResponseBodyRenderer.vue b/packages/hoppscotch-common/src/components/lenses/ResponseBodyRenderer.vueindex 1918396a1..884640465 100644--- a/packages/hoppscotch-common/src/components/lenses/ResponseBodyRenderer.vue+++ b/packages/hoppscotch-common/src/components/lenses/ResponseBodyRenderer.vue@@ -75,7 +75,7 @@ import {getSuitableLenses,Lens,} from "~/helpers/lenses/lenses"-import { HoppRequestDocument } from "~/helpers/rest/document"+import { HoppRequestDocument } from "~/helpers/tab/document"import { ConsoleEntry } from "../console/Panel.vue"const props = defineProps<{@@ -96,6 +96,9 @@ const EXPERIMENTAL_SCRIPTING_SANDBOX = useSetting("EXPERIMENTAL_SCRIPTING_SANDBOX")+// Boolean() wrap — `saveContext` is undefined for documents that never came+// from a collection (e.g. test-runner result rows), and `"success" &&+// undefined` would leak `undefined` into the lens renderers' Boolean prop.const isSavable = computed(() =>Boolean(doc.value.response?.type === "success" && doc.value.saveContext))diff --git a/packages/hoppscotch-common/src/components/lenses/renderers/HTMLLensRenderer.vue b/packages/hoppscotch-common/src/components/lenses/renderers/HTMLLensRenderer.vueindex 6d5d8ec95..49108f3f5 100644--- a/packages/hoppscotch-common/src/components/lenses/renderers/HTMLLensRenderer.vue+++ b/packages/hoppscotch-common/src/components/lenses/renderers/HTMLLensRenderer.vue@@ -138,8 +138,7 @@ const persistenceService = useService(PersistenceService)const props = defineProps<{response:- | (HoppRESTResponse & { type: "success" | "fail" })- | HoppRESTRequestResponse+ (HoppRESTResponse & { type: "success" | "fail" }) | HoppRESTRequestResponseisSavable: booleanisEditable: booleantabId: stringdiff --git a/packages/hoppscotch-common/src/components/lenses/renderers/JSONLensRenderer.vue b/packages/hoppscotch-common/src/components/lenses/renderers/JSONLensRenderer.vueindex 9a21ec801..8773cda66 100644--- a/packages/hoppscotch-common/src/components/lenses/renderers/JSONLensRenderer.vue+++ b/packages/hoppscotch-common/src/components/lenses/renderers/JSONLensRenderer.vue@@ -354,8 +354,7 @@ const filterQueryText = ref("")const debouncedFilterQuery = refDebounced(filterQueryText, 300)type BodyParseError =- | { type: "JSON_PARSE_FAILED" }- | { type: "JSON_QUERY_FAILED"; error: Error }+ { type: "JSON_PARSE_FAILED" } | { type: "JSON_QUERY_FAILED"; error: Error }const responseJsonObject = computed(() => {if (isHttpResponse.value) {@@ -365,10 +364,9 @@ const responseJsonObject = computed(() => {return pipe(responseBodyText.value,- E.tryCatchK(- LJSON.parse,- (): BodyParseError => ({ type: "JSON_PARSE_FAILED" })- )+ E.tryCatchK(LJSON.parse, (): BodyParseError => ({+ type: "JSON_PARSE_FAILED",+ })))}diff --git a/packages/hoppscotch-common/src/components/lenses/renderers/RawLensRenderer.vue b/packages/hoppscotch-common/src/components/lenses/renderers/RawLensRenderer.vueindex 8ce7530f2..5bef92960 100644--- a/packages/hoppscotch-common/src/components/lenses/renderers/RawLensRenderer.vue+++ b/packages/hoppscotch-common/src/components/lenses/renderers/RawLensRenderer.vue@@ -118,8 +118,7 @@ const t = useI18n()const props = defineProps<{response:- | (HoppRESTResponse & { type: "success" | "fail" })- | HoppRESTRequestResponse+ (HoppRESTResponse & { type: "success" | "fail" }) | HoppRESTRequestResponseisEditable: booleanisSavable: booleantabId: stringdiff --git a/packages/hoppscotch-common/src/components/lenses/renderers/XMLLensRenderer.vue b/packages/hoppscotch-common/src/components/lenses/renderers/XMLLensRenderer.vueindex bbcebbdf3..b0681c43d 100644--- a/packages/hoppscotch-common/src/components/lenses/renderers/XMLLensRenderer.vue+++ b/packages/hoppscotch-common/src/components/lenses/renderers/XMLLensRenderer.vue@@ -115,8 +115,7 @@ const t = useI18n()const props = defineProps<{response:- | (HoppRESTResponse & { type: "success" | "fail" })- | HoppRESTRequestResponse+ (HoppRESTResponse & { type: "success" | "fail" }) | HoppRESTRequestResponseisEditable: booleanisSavable: booleantabId: stringdiff --git a/packages/hoppscotch-common/src/components/mockServer/LogSection.vue b/packages/hoppscotch-common/src/components/mockServer/LogSection.vueindex 29f446582..e40736bbe 100644--- a/packages/hoppscotch-common/src/components/mockServer/LogSection.vue+++ b/packages/hoppscotch-common/src/components/mockServer/LogSection.vue@@ -35,8 +35,7 @@<preclass="relative whitespace-pre-wrap cursor-text select-text break-words bg-primaryLight border border-dividerLight rounded-sm p-4 max-h-96 overflow-y-auto":class="[isValidJSON ? 'text-accent' : 'text-secondaryLight']"- >{{ formattedContent }}</pre- >+ >{{ formattedContent }}</pre></div><divdiff --git a/packages/hoppscotch-common/src/components/share/CreateModal.vue b/packages/hoppscotch-common/src/components/share/CreateModal.vueindex ee24486f4..0378c3512 100644--- a/packages/hoppscotch-common/src/components/share/CreateModal.vue+++ b/packages/hoppscotch-common/src/components/share/CreateModal.vue@@ -35,12 +35,19 @@{{ t("shared_requests.preview") }}</span><div class="w-full">- <ShareTemplatesEmbeds- v-if="selectedWidget.value === 'embed'"- :endpoint="request?.endpoint"- :method="request?.method"- :model-value="embedOption"- />+ <template v-if="selectedWidget.value === 'embed'">+ <ShareTemplatesEmbedsGQL+ v-if="request && !isRESTRequest(request)"+ :url="(request as HoppGQLRequest).url"+ :model-value="gqlEmbedOption"+ />+ <ShareTemplatesEmbeds+ v-else+ :endpoint="(request as HoppRESTRequest | null)?.endpoint"+ :method="(request as HoppRESTRequest | null)?.method"+ :model-value="embedOption"+ />+ </template><ShareTemplatesButtonv-else-if="selectedWidget.value === 'button'"img="badge.svg"@@ -53,16 +60,17 @@</template><script lang="ts" setup>-import { HoppRESTRequest } from "@hoppscotch/data"+import { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"import { useVModel } from "@vueuse/core"import { PropType, ref } from "vue"import { useI18n } from "~/composables/i18n"+import { isRESTRequest } from "~/helpers/request-type"const t = useI18n()const props = defineProps({request: {- type: Object as PropType<HoppRESTRequest | null>,+ type: Object as PropType<HoppRESTRequest | HoppGQLRequest | null>,required: true,},modelValue: {@@ -141,4 +149,33 @@ const embedOption = ref<EmbedOption>({],theme: "system",})++// GraphQL preview shape — different tab set, separate ref so the REST+// preview's selections aren't accidentally clobbered when toggling between+// request types.+type GQLTabs = "query" | "variables" | "headers" | "authorization"+type GQLEmbedOption = {+ selectedTab: GQLTabs+ tabs: {+ value: GQLTabs+ label: string+ enabled: boolean+ }[]+ theme: "light" | "dark" | "system"+}++const gqlEmbedOption = ref<GQLEmbedOption>({+ selectedTab: "query",+ tabs: [+ { value: "query", label: t("tab.query"), enabled: true },+ { value: "variables", label: t("tab.variables"), enabled: true },+ { value: "headers", label: t("tab.headers"), enabled: true },+ {+ value: "authorization",+ label: t("tab.authorization"),+ enabled: false,+ },+ ],+ theme: "system",+})</script>diff --git a/packages/hoppscotch-common/src/components/share/CustomizeGQLModal.vue b/packages/hoppscotch-common/src/components/share/CustomizeGQLModal.vuenew file mode 100644index 000000000..223914bf4--- /dev/null+++ b/packages/hoppscotch-common/src/components/share/CustomizeGQLModal.vue@@ -0,0 +1,469 @@+<template>+ <div+ v-if="selectedWidget"+ class="border divide-y rounded divide-divider border-divider"+ >+ <div v-if="loading" class="px-4 py-2">+ {{ t("shared_requests.creating_widget") }}+ </div>+ <div v-else class="px-4 py-2">+ {{ t("shared_requests.customize") }}+ </div>+ <div v-if="loading" class="flex flex-col items-center justify-center p-4">+ <HoppSmartSpinner class="my-4" />+ <span class="text-secondaryLight">{{ t("state.loading") }}</span>+ </div>+ <div v-else class="flex flex-col divide-y divide-divider">+ <div class="flex flex-col p-2 space-y-2">+ <HoppSmartRadioGroup+ v-model="selectedWidget.value"+ :radios="widgets"+ class="flex !flex-row"+ />+ </div>+ <div class="flex flex-col divide-y divide-divider">+ <div class="flex items-center justify-center px-6 py-4">+ <div v-if="selectedWidget.value === 'embed'" class="w-full">+ <div class="flex flex-col pb-4">+ <div+ v-for="option in embedOptions.tabs"+ :key="option.value"+ class="flex justify-between py-2"+ >+ <span class="capitalize">+ {{ t(option.label) }}+ </span>+ <HoppSmartCheckbox+ :on="option.enabled"+ @change="removeEmbedOption(option.value)"+ >+ </HoppSmartCheckbox>+ </div>+ <div class="flex items-center justify-between">+ <span>+ {{ t("shared_requests.theme.title") }}+ </span>+ <div>+ <tippy+ interactive+ trigger="click"+ theme="popover"+ :on-shown="() => tippyActions!.focus()"+ >+ <HoppButtonSecondary+ class="!py-2 !px-0 capitalize"+ :label="embedOptions.theme"+ :icon="embedThemeIcon"+ />+ <template #content="{ hide }">+ <div+ ref="tippyActions"+ class="flex flex-col focus:outline-none"+ tabindex="0"+ @keyup.escape="hide()"+ >+ <HoppSmartItem+ :label="t('shared_requests.theme.system')"+ :icon="IconMonitor"+ :active="embedOptions.theme === 'system'"+ @click="+ () => {+ embedOptions.theme = 'system'+ hide()+ }+ "+ />+ <HoppSmartItem+ :label="t('shared_requests.theme.light')"+ :icon="IconSun"+ :active="embedOptions.theme === 'light'"+ @click="+ () => {+ embedOptions.theme = 'light'+ hide()+ }+ "+ />+ <HoppSmartItem+ :label="t('shared_requests.theme.dark')"+ :icon="IconMoon"+ :active="embedOptions.theme === 'dark'"+ @click="+ () => {+ embedOptions.theme = 'dark'+ hide()+ }+ "+ />+ </div>+ </template>+ </tippy>+ </div>+ </div>+ </div>+ <span+ class="flex justify-center mb-2 text-secondaryLight text-tiny"+ >+ {{ t("shared_requests.preview") }}+ </span>+ <ShareTemplatesEmbedsGQL+ :url="request?.url"+ :model-value="embedOptions"+ />+ <div class="flex items-center justify-center">+ <HoppButtonSecondary+ :label="t('shared_requests.copy_html')"+ class="underline text-secondaryDark"+ @click="+ copyContent({+ widget: 'embed',+ type: 'html',+ })+ "+ />+ </div>+ </div>+ <div+ v-else-if="selectedWidget.value === 'button'"+ class="flex flex-col space-y-8"+ >+ <div+ v-for="variant in buttonVariants"+ :key="variant.id"+ class="flex flex-col"+ >+ <span+ class="flex justify-center mb-2 text-secondaryLight text-tiny"+ >+ {{ t("shared_requests.preview") }}+ </span>+ <ShareTemplatesButton :img="variant.img" />+ <div class="flex items-center justify-between">+ <HoppButtonSecondary+ :label="t('shared_requests.copy_html')"+ class="underline text-secondaryDark"+ @click="+ copyContent({+ widget: 'button',+ type: 'html',+ id: variant.id,+ })+ "+ />+ <HoppButtonSecondary+ :label="t('shared_requests.copy_markdown')"+ class="underline text-secondaryDark"+ @click="+ copyContent({+ widget: 'button',+ type: 'markdown',+ id: variant.id,+ })+ "+ />+ </div>+ </div>+ </div>+ <div v-else class="flex flex-col space-y-8">+ <div+ v-for="variant in linkVariants"+ :key="variant.type"+ class="flex flex-col items-center justify-center"+ >+ <span+ class="flex justify-center mb-2 text-secondaryLight text-tiny"+ >+ {{ t("shared_requests.preview") }}+ </span>+ <ShareTemplatesLink :link="variant.link" :label="variant.label" />+ <HoppButtonSecondary+ :label="t(`shared_requests.copy_${variant.type}`)"+ class="underline text-secondaryDark"+ @click="+ copyContent({+ widget: 'link',+ type: variant.type,+ id: variant.id,+ })+ "+ />+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { useVModel } from "@vueuse/core"+import { computed, onMounted, ref } from "vue"+import { PropType } from "vue"+import { useI18n } from "~/composables/i18n"+import IconMonitor from "~icons/lucide/monitor"+import IconSun from "~icons/lucide/sun"+import IconMoon from "~icons/lucide/moon"+import { TippyComponent } from "vue-tippy"+import { HoppGQLRequest } from "@hoppscotch/data"+import { platform } from "~/platform"++const t = useI18n()++const props = defineProps({+ request: {+ type: Object as PropType<HoppGQLRequest | null>,+ required: true,+ },+ modelValue: {+ type: Object as PropType<Widget | null>,+ default: null,+ },+ loading: {+ type: Boolean,+ default: false,+ },+ embedOptions: {+ type: Object as PropType<GQLEmbedOption>,+ default: () => ({+ selectedTab: "query",+ tabs: [+ {+ value: "query",+ label: "tab.query",+ enabled: true,+ },+ {+ value: "variables",+ label: "tab.variables",+ enabled: true,+ },+ {+ value: "headers",+ label: "tab.headers",+ enabled: true,+ },+ {+ value: "authorization",+ label: "tab.authorization",+ enabled: false,+ },+ ],+ theme: "system",+ }),+ },+})++const emit = defineEmits<{+ (+ e: "copy-shared-request",+ request: {+ sharedRequestID: string | undefined+ content: string | undefined+ }+ ): void+ (e: "hide-modal"): void+ (e: "update:modelValue", value: string): void+}>()++const selectedWidget = useVModel(props, "modelValue")+const embedOptions = useVModel(props, "embedOptions")++type WidgetID = "embed" | "button" | "link"++type Widget = {+ value: WidgetID+ label: string+}++const widgets: Widget[] = [+ {+ value: "embed",+ label: t("shared_requests.embed"),+ },+ {+ value: "button",+ label: t("shared_requests.button"),+ },+ {+ value: "link",+ label: t("shared_requests.link"),+ },+]++// GraphQL surfaces the request as four panels (mirrors the live editor's+// RequestOptions tabs). REST's `params` / `body` / `requestVariables` are+// not applicable.+type GQLEmbedTabs = "query" | "variables" | "headers" | "authorization"++type GQLEmbedOption = {+ selectedTab: GQLEmbedTabs+ tabs: {+ value: GQLEmbedTabs+ label: string+ enabled: boolean+ }[]+ theme: "light" | "dark" | "system"+}++const organizationDomain = ref<string>("")++onMounted(async () => {+ const { organization } = platform++ if (!organization || organization.isDefaultCloudInstance) {+ return+ }++ const orgInfo = await organization.getOrgInfo()++ if (orgInfo) {+ const { orgDomain } = orgInfo++ organizationDomain.value = orgDomain+ }+})++const embedThemeIcon = computed(() => {+ if (embedOptions.value.theme === "system") {+ return IconMonitor+ } else if (embedOptions.value.theme === "light") {+ return IconSun+ }+ return IconMoon+})++const removeEmbedOption = (option: GQLEmbedTabs) => {+ const index = embedOptions.value.tabs.findIndex((tab) => tab.value === option)+ if (index === -1) return++ const willDisable = embedOptions.value.tabs[index].enabled+ embedOptions.value.tabs[index].enabled = !willDisable++ // If we just disabled the currently selected tab, advance to the next+ // still-enabled one. If none remain enabled, fall back to the first tab+ // in the list so `selectedTab` is never out of sync with the rendered+ // tabs — otherwise the preview's `selectedTab` binding would dangle and+ // the embed-side `GqlRequestOptions` would receive an unknown id.+ if (willDisable && embedOptions.value.selectedTab === option) {+ const nextEnabled = embedOptions.value.tabs.find((tab) => tab.enabled)+ embedOptions.value.selectedTab =+ nextEnabled?.value ?? embedOptions.value.tabs[0].value+ }+}++type ButtonVariant = {+ id: string+ img: string+}+const buttonVariants: ButtonVariant[] = [+ {+ id: "button1",+ img: "badge.svg",+ },+ {+ id: "button2",+ img: "badge-light.svg",+ },+ {+ id: "button3",+ img: "badge-dark.svg",+ },+]++type LinkVariant = {+ id: string+ link?: string+ label?: string+ type: "html" | "markdown" | "link"+}++const linkVariants: LinkVariant[] = [+ {+ id: "link1",+ link: props.request?.id,+ type: "link",+ },+ {+ id: "link2",+ label: "shared_requests.run_in_hoppscotch",+ type: "html",+ },+ {+ id: "link3",+ label: "shared_requests.run_in_hoppscotch",+ type: "markdown",+ },+]++const shortcodeBaseURL = computed(() => {+ const { organization } = platform++ if (!organization || organization.isDefaultCloudInstance) {+ return import.meta.env.VITE_SHORTCODE_BASE_URL ?? "https://hopp.sh"+ }++ const rootDomain = organization.getRootDomain()+ return `https://${organizationDomain.value}.${rootDomain}`+})++const copyEmbed = () => {+ // No `sandbox`: the embed is already cross-origin from the host page, and+ // sandboxing gives it an opaque origin — breaking localStorage on boot and+ // stamping `Origin: null` on every request it fires+ return `<iframe src="${shortcodeBaseURL.value}/e/${props.request?.id}" title="Hoppscotch Embed" style="width: 100%; height: 480px; border-radius: 4px; border: 1px solid rgba(0, 0, 0, 0.1);"></iframe>`+}++const copyButton = (+ variationID: string,+ type: "html" | "markdown" | "link"+) => {+ let badge = ""+ if (variationID === "button1") {+ badge = "badge.svg"+ } else if (variationID === "button2") {+ badge = "badge-light.svg"+ } else {+ badge = "badge-dark.svg"+ }++ if (type === "markdown") {+ return `[](${shortcodeBaseURL.value}/r/${props.request?.id})`+ }+ return `<a href="${shortcodeBaseURL.value}/r/${props.request?.id}"><img src="${shortcodeBaseURL.value}/${badge}" alt="Run in Hoppscotch" /></a>`+}++const copyLink = (variationID: string) => {+ if (variationID === "link1") {+ return `${shortcodeBaseURL.value}/r/${props.request?.id}`+ } else if (variationID === "link2") {+ return `<a href="${shortcodeBaseURL.value}/r/${props.request?.id}">Run in Hoppscotch</a>`+ }+ return `[Run in Hoppscotch](${shortcodeBaseURL.value}/r/${props.request?.id})`+}++const copyContent = ({+ id,+ widget,+ type,+}: {+ id?: string | undefined+ widget: WidgetID+ type: "html" | "markdown" | "link"+}) => {+ let content = ""+ if (widget === "button") {+ content = copyButton(id!, type)+ } else if (widget === "link") {+ content = copyLink(id!)+ } else {+ content = copyEmbed()+ }+ const copyContent = {+ sharedRequestID: props.request?.id,+ content,+ }+ emit("copy-shared-request", copyContent)+}++const tippyActions = ref<TippyComponent | null>(null)+</script>diff --git a/packages/hoppscotch-common/src/components/share/CustomizeModal.vue b/packages/hoppscotch-common/src/components/share/CustomizeModal.vueindex 63180ae39..6d0c75759 100644--- a/packages/hoppscotch-common/src/components/share/CustomizeModal.vue+++ b/packages/hoppscotch-common/src/components/share/CustomizeModal.vue@@ -292,11 +292,7 @@ const widgets: Widget[] = []type EmbedTabs =- | "params"- | "bodyParams"- | "headers"- | "authorization"- | "requestVariables"+ "params" | "bodyParams" | "headers" | "authorization" | "requestVariables"type EmbedOption = {selectedTab: EmbedTabs@@ -339,16 +335,18 @@ const removeEmbedOption = (option: EmbedTabs) => {const index = embedOptions.value.tabs.findIndex((tab) => tab.value === option)if (index === -1) return- //if removed tab is the selected tab, select the next tab with enabled true- if (embedOptions.value.selectedTab === option) {- const nextTab = embedOptions.value.tabs.find((tab) => tab.enabled)- if (nextTab) {- embedOptions.value.selectedTab = nextTab.value- }+ const willDisable = embedOptions.value.tabs[index].enabled+ embedOptions.value.tabs[index].enabled = !willDisable++ // If we just disabled the currently selected tab, advance to the next+ // still-enabled one. If none remain enabled, fall back to the first tab+ // in the list so `selectedTab` is never out of sync with the rendered+ // tabs — otherwise the embed-side renderer would receive an unknown id.+ if (willDisable && embedOptions.value.selectedTab === option) {+ const nextEnabled = embedOptions.value.tabs.find((tab) => tab.enabled)+ embedOptions.value.selectedTab =+ nextEnabled?.value ?? embedOptions.value.tabs[0].value}-- embedOptions.value.tabs[index].enabled =- !embedOptions.value.tabs[index].enabled}type ButtonVariant = {@@ -407,6 +405,9 @@ const shortcodeBaseURL = computed(() => {})const copyEmbed = () => {+ // No `sandbox`: the embed is already cross-origin from the host page, and+ // sandboxing gives it an opaque origin — breaking localStorage on boot and+ // stamping `Origin: null` on every request it firesreturn `<iframe src="${shortcodeBaseURL.value}/e/${props.request?.id}" title="Hoppscotch Embed" style="width: 100%; height: 480px; border-radius: 4px; border: 1px solid rgba(0, 0, 0, 0.1);"></iframe>`}diff --git a/packages/hoppscotch-common/src/components/share/Modal.vue b/packages/hoppscotch-common/src/components/share/Modal.vueindex 38c0c1b40..162739beb 100644--- a/packages/hoppscotch-common/src/components/share/Modal.vue+++ b/packages/hoppscotch-common/src/components/share/Modal.vue@@ -9,6 +9,16 @@@close="hideModal"><template #body>+ <div+ v-if="hasSharedSecrets"+ class="mb-3 flex items-start gap-2 rounded border border-yellow-500/40 bg-yellow-500/10 px-3 py-2 text-tiny text-yellow-700 dark:text-yellow-400"+ data-testid="share_secret_warning"+ >+ <icon-lucide-alert-triangle class="mt-0.5 h-3 w-3 flex-shrink-0" />+ <span>+ {{ t("shared_requests.auth_warning") }}+ </span>+ </div><div v-if="loading" class="flex flex-col items-center justify-center p-4"><HoppSmartSpinner class="my-4" /><span class="text-secondaryLight">{{ t("state.loading") }}</span>@@ -21,10 +31,18 @@@create-shared-request="createSharedRequest"/><ShareCustomizeModal- v-else-if="step === 2"+ v-else-if="step === 2 && request && isRESTRequest(request)"v-model="selectedWidget"v-model:embed-options="embedOptions"- :request="request"+ :request="request as HoppRESTRequest"+ :loading="loading"+ @copy-shared-request="copySharedRequest"+ />+ <ShareCustomizeGQLModal+ v-else-if="step === 2 && request"+ v-model="selectedWidget"+ v-model:embed-options="gqlEmbedOptions"+ :request="request as HoppGQLRequest":loading="loading"@copy-shared-request="copySharedRequest"/>@@ -49,19 +67,16 @@</template><script lang="ts" setup>-import { HoppRESTRequest } from "@hoppscotch/data"+import { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"import { useVModel } from "@vueuse/core"-import { PropType } from "vue"+import { computed, PropType } from "vue"import { useI18n } from "~/composables/i18n"+import { isRESTRequest, requestHasSharedSecrets } from "~/helpers/request-type"const t = useI18n()type EmbedTabs =- | "params"- | "bodyParams"- | "headers"- | "authorization"- | "requestVariables"+ "params" | "bodyParams" | "headers" | "authorization" | "requestVariables"type EmbedOption = {selectedTab: EmbedTabs@@ -73,9 +88,24 @@ type EmbedOption = {theme: "light" | "dark" | "system"}+// GraphQL-shaped embed options — separate from REST because the tab set+// differs. Kept as a sibling prop so each customize component owns a clean,+// non-union shape and we don't carry stale REST fields onto a GQL share.+type GQLEmbedTabs = "query" | "variables" | "headers" | "authorization"++type GQLEmbedOption = {+ selectedTab: GQLEmbedTabs+ tabs: {+ value: GQLEmbedTabs+ label: string+ enabled: boolean+ }[]+ theme: "light" | "dark" | "system"+}+const props = defineProps({request: {- type: Object as PropType<HoppRESTRequest | null>,+ type: Object as PropType<HoppRESTRequest | HoppGQLRequest | null>,required: true,},show: {@@ -124,6 +154,35 @@ const props = defineProps({theme: "system",}),},+ gqlEmbedOptions: {+ type: Object as PropType<GQLEmbedOption>,+ default: () => ({+ selectedTab: "query",+ tabs: [+ {+ value: "query",+ label: "tab.query",+ enabled: true,+ },+ {+ value: "variables",+ label: "tab.variables",+ enabled: true,+ },+ {+ value: "headers",+ label: "tab.headers",+ enabled: true,+ },+ {+ value: "authorization",+ label: "tab.authorization",+ enabled: false,+ },+ ],+ theme: "system",+ }),+ },})type WidgetID = "embed" | "button" | "link"@@ -136,9 +195,13 @@ type Widget = {const selectedWidget = useVModel(props, "modelValue")const embedOptions = useVModel(props, "embedOptions")+const gqlEmbedOptions = useVModel(props, "gqlEmbedOptions")const emit = defineEmits<{- (e: "create-shared-request", request: HoppRESTRequest | null): void+ (+ e: "create-shared-request",+ request: HoppRESTRequest | HoppGQLRequest | null+ ): void(e: "hide-modal"): void(e: "update:modelValue", value: string): void(e: "update:step", value: number): void@@ -151,8 +214,18 @@ const emit = defineEmits<{): void}>()+// Show a warning when the request carries active auth credentials. The+// `Shortcode.request` column on the backend is opaque JSON and readable by+// anyone with the code, so a bearer token / password / API key in the+// payload becomes public the moment the shortcode is created. Disabling+// the Authorization toggle in customize only hides it from the embed UI,+// not from the stored payload.+const hasSharedSecrets = computed(() =>+ props.request ? requestHasSharedSecrets(props.request) : false+)+const createSharedRequest = () => {- emit("create-shared-request", props.request as HoppRESTRequest)+ emit("create-shared-request", props.request)}const copySharedRequest = (payload: {diff --git a/packages/hoppscotch-common/src/components/share/Request.vue b/packages/hoppscotch-common/src/components/share/Request.vueindex b6607612e..cc02a4a9b 100644--- a/packages/hoppscotch-common/src/components/share/Request.vue+++ b/packages/hoppscotch-common/src/components/share/Request.vue@@ -10,24 +10,35 @@@click="customizeSharedRequest()"><span+ v-if="parsed.protocol === 'rest'"class="flex items-center justify-center w-16 px-2 truncate pointer-events-none":style="{ color: requestLabelColor }"><span class="font-semibold truncate text-tiny">- {{ parseRequest.method }}+ {{ parsed.request.method }}</span></span>+ <span+ v-else+ class="flex items-center justify-center w-16 px-2 pointer-events-none text-accent"+ >+ <component :is="IconGraphql" class="h-4 w-4" />+ </span><spanclass="flex items-center flex-1 min-w-0 pr-2 transition pointer-events-none group-hover:text-secondaryDark"><span class="flex-1 truncate">- {{ parseRequest.endpoint }}+ {{+ parsed.protocol === "rest"+ ? parsed.request.endpoint+ : parsed.request.url+ }}</span></span><spanclass="flex px-2 truncate text-secondaryLight group-hover:text-secondaryDark">- {{ parseRequest.name }}+ {{ parsed.request.name }}</span></div><div>@@ -62,7 +73,7 @@:shortcut="['T']"@click="() => {- emit('open-shared-request', parseRequest)+ emit('open-shared-request', parsed.request)hide()}"@@ -100,8 +111,12 @@</template><script lang="ts" setup>-import { HoppRESTRequest, translateToNewRequest } from "@hoppscotch/data"-import { pipe } from "fp-ts/lib/function"+import {+ HoppGQLRequest,+ HoppRESTRequest,+ translateToGQLRequest,+ translateToNewRequest,+} from "@hoppscotch/data"import { ref } from "vue"import { computed } from "vue"import { TippyComponent } from "vue-tippy"@@ -112,6 +127,7 @@ import IconArrowUpRight from "~icons/lucide/arrow-up-right-square"import IconMoreVertical from "~icons/lucide/more-vertical"import IconCustomize from "~icons/lucide/settings-2"import IconTrash2 from "~icons/lucide/trash-2"+import IconGraphql from "~icons/hopp/graphql"import { shortDateTime } from "~/helpers/utils/date"const t = useI18n()@@ -123,12 +139,12 @@ const props = defineProps<{const emit = defineEmits<{(e: "customize-shared-request",- request: HoppRESTRequest,+ request: HoppRESTRequest | HoppGQLRequest,id: string,embedProperties?: string | null): void(e: "delete-shared-request", codeID: string): void- (e: "open-shared-request", request: HoppRESTRequest): void+ (e: "open-shared-request", request: HoppRESTRequest | HoppGQLRequest): void}>()const tippyActions = ref<TippyComponent | null>(null)@@ -137,19 +153,39 @@ const customizeAction = ref<HTMLButtonElement | null>(null)const deleteAction = ref<HTMLButtonElement | null>(null)const options = ref<any | null>(null)-const parseRequest = computed(() =>- pipe(props.request.request, JSON.parse, translateToNewRequest)-)+// Shape-discriminated parse — GraphQL shortcodes have `query` + `url`,+// REST shortcodes have `endpoint`. We run each through its own translator+// so we get schema defaults regardless of how the payload was stored.+type ParsedShortcode =+ | { protocol: "rest"; request: HoppRESTRequest }+ | { protocol: "gql"; request: HoppGQLRequest }++const parsed = computed<ParsedShortcode>(() => {+ const raw = JSON.parse(props.request.request) as Record<string, unknown>+ // Object check first — `in` throws on null/primitives+ if (+ !!raw &&+ typeof raw === "object" &&+ "query" in raw &&+ "url" in raw &&+ !("endpoint" in raw)+ ) {+ return { protocol: "gql", request: translateToGQLRequest(raw) }+ }+ return { protocol: "rest", request: translateToNewRequest(raw) }+})const requestLabelColor = computed(() =>- getMethodLabelColorClassOf(parseRequest.value.method)+ parsed.value.protocol === "rest"+ ? getMethodLabelColorClassOf(parsed.value.request.method)+ : "")const customizeSharedRequest = () => {const embedProperties = props.request.propertiesemit("customize-shared-request",- parseRequest.value,+ parsed.value.request,props.request.id,embedProperties)diff --git a/packages/hoppscotch-common/src/components/share/index.vue b/packages/hoppscotch-common/src/components/share/index.vueindex 9f7d58ee8..3a51a16f3 100644--- a/packages/hoppscotch-common/src/components/share/index.vue+++ b/packages/hoppscotch-common/src/components/share/index.vue@@ -95,8 +95,10 @@@resolve="resolveConfirmModal"/><ShareModal+ v-if="showShareRequestModal && requestToShare"v-model="selectedWidget"v-model:embed-options="embedOptions"+ v-model:gql-embed-options="gqlEmbedOptions":step="step":request="requestToShare":show="showShareRequestModal"@@ -128,10 +130,12 @@ import {import { GQLError } from "~/helpers/backend/GQLClient"import { useToast } from "~/composables/toast"import { ref } from "vue"-import { HoppRESTRequest } from "@hoppscotch/data"+import { debounce } from "lodash-es"+import { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"+import { isRESTRequest } from "~/helpers/request-type"import { copyToClipboard } from "~/helpers/utils/clipboard"import * as E from "fp-ts/Either"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { useService } from "dioc/vue"import { watch } from "vue"@@ -148,7 +152,10 @@ const showShareRequestModal = ref(false)const sharedRequestID = ref("")const shareRequestCreatingLoading = ref(false)-const requestToShare = ref<HoppRESTRequest | null>(null)+// The shared-request modal holds either kind. Discriminated downstream via+// the request's shape (`isRESTRequest` / `isGQLRequest`). The CustomizeModal+// is REST-shaped today — GQL goes through its own modal (added in next step).+const requestToShare = ref<HoppRESTRequest | HoppGQLRequest | null>(null)const embedOptions = ref<EmbedOption>({selectedTab: "params",@@ -182,6 +189,37 @@ const embedOptions = ref<EmbedOption>({theme: "system",})+// GraphQL shares use the same modal scaffold but a different tab set —+// kept as a sibling ref so the REST options ref stays untouched and each+// shape has its own translated labels. Initialised lazily; only consumed+// when the active request is GQL.+const gqlEmbedOptions = ref<GQLEmbedOption>({+ selectedTab: "query",+ tabs: [+ {+ value: "query",+ label: t("tab.query"),+ enabled: false,+ },+ {+ value: "variables",+ label: t("tab.variables"),+ enabled: false,+ },+ {+ value: "headers",+ label: t("tab.headers"),+ enabled: false,+ },+ {+ value: "authorization",+ label: t("tab.authorization"),+ enabled: false,+ },+ ],+ theme: "system",+})+const updateEmbedProperty = async (shareRequestID: string,properties: string@@ -197,29 +235,60 @@ const updateEmbedProperty = async (}}-watch(- () => embedOptions.value,- () => {+// Push the current embed customize options to the backend. Called from both+// REST and GQL watchers below; the `options` array contains protocol-specific+// tab values (e.g. "params"/"bodyParams" for REST, "query"/"variables" for+// GQL). The Shortcode.properties column is opaque JSON, so the backend+// accepts either shape — the consumer (the /e/<id> renderer) discriminates+// from the request payload's shape.+// Debounced: the customize modal's checkboxes fire the watcher on every+// click, and without coalescing we'd send one mutation per toggle. 400ms+// is short enough to feel instant on save, long enough to fold a burst of+// toggles into a single network round-trip.+const persistEmbedProperties = debounce(+ (options: { tabs: { enabled: boolean; value: string }[]; theme: string }) => {if (requestToShare.value &&requestToShare.value.id &&- showShareRequestModal.value+ showShareRequestModal.value &&+ selectedWidget.value.value === "embed") {- if (selectedWidget.value.value === "embed") {- const properties = {- options: embedOptions.value.tabs- .filter((tab) => tab.enabled)- .map((tab) => tab.value),- theme: embedOptions.value.theme,- }- updateEmbedProperty(requestToShare.value.id, JSON.stringify(properties))+ const properties = {+ options: options.tabs+ .filter((tab) => tab.enabled)+ .map((tab) => tab.value),+ theme: options.theme,}+ updateEmbedProperty(requestToShare.value.id, JSON.stringify(properties))+ }+ },+ 400+)++// Per-protocol watchers — guarded by the active request's shape so they+// don't double-persist. With a single union ref this guard would be+// unnecessary, but the union shape makes per-modal code messier.+watch(+ () => embedOptions.value,+ () => {+ if (requestToShare.value && isRESTRequest(requestToShare.value)) {+ persistEmbedProperties(embedOptions.value)+ }+ },+ { deep: true }+)++watch(+ () => gqlEmbedOptions.value,+ () => {+ if (requestToShare.value && !isRESTRequest(requestToShare.value)) {+ persistEmbedProperties(gqlEmbedOptions.value)}},{ deep: true })-const restTab = useService(RESTTabService)+const workspaceTab = useService(WorkspaceTabsService)const currentUser = useReadonlyStream(platform.auth.getCurrentUserStream(),@@ -229,11 +298,7 @@ const currentUser = useReadonlyStream(const step = ref(1)type EmbedTabs =- | "params"- | "bodyParams"- | "headers"- | "authorization"- | "requestVariables"+ "params" | "bodyParams" | "headers" | "authorization" | "requestVariables"type EmbedOption = {selectedTab: EmbedTabs@@ -245,6 +310,20 @@ type EmbedOption = {theme: "light" | "dark" | "system"}+// GraphQL embed customize tabs — kept separate from REST so each modal+// owns a clean shape rather than a union with always-undefined fields.+type GQLEmbedTabs = "query" | "variables" | "headers" | "authorization"++type GQLEmbedOption = {+ selectedTab: GQLEmbedTabs+ tabs: {+ value: GQLEmbedTabs+ label: string+ enabled: boolean+ }[]+ theme: "light" | "dark" | "system"+}+type WidgetID = "embed" | "button" | "link"type Widget = {@@ -301,9 +380,12 @@ onAuthEvent((ev) => {const shareRequest = () => {if (currentUser.value) {- const tab = restTab.currentActiveTab+ const doc = workspaceTab.currentActiveTab.value.document+ // Only request-bearing documents can be shared — test-runner and+ // example-response tabs have no `request` to snapshot+ if (doc.type !== "request" && doc.type !== "gql-request") returninvokeAction("share.request", {- request: tab.value.document.request,+ request: doc.request,})} else {invokeAction("modals.login.toggle")@@ -352,113 +434,167 @@ const displayCustomizeRequestModal = (show: boolean,embedProperties?: string | null) => {+ if (!show) {+ // Flush any pending debounced persist before the guards it re-checks+ // (modal open, embed widget) go false — otherwise the last customize+ // toggle within the debounce window is silently dropped+ persistEmbedProperties.flush()+ }showShareRequestModal.value = showstep.value = 2++ // Discriminate by the request currently in flight. `requestToShare` is set+ // before this function is called (by `customizeSharedRequest`), so its+ // shape tells us which embedOptions ref to populate.+ const isGQL = !!requestToShare.value && !isRESTRequest(requestToShare.value)+if (!embedProperties) {selectedWidget.value = {value: "button",label: t("shared_requests.button"),info: t("shared_requests.button_info"),}- embedOptions.value = {- selectedTab: "params",- tabs: [- {- value: "params",- label: t("tab.parameters"),- enabled: false,- },- {- value: "bodyParams",- label: t("tab.body"),- enabled: false,- },- {- value: "headers",- label: t("tab.headers"),- enabled: false,- },- {- value: "authorization",- label: t("tab.authorization"),- enabled: false,- },- {- value: "requestVariables",- label: t("tab.variables"),- enabled: false,- },- ],- theme: "system",+ if (isGQL) {+ gqlEmbedOptions.value = {+ selectedTab: "query",+ tabs: [+ { value: "query", label: t("tab.query"), enabled: false },+ { value: "variables", label: t("tab.variables"), enabled: false },+ { value: "headers", label: t("tab.headers"), enabled: false },+ {+ value: "authorization",+ label: t("tab.authorization"),+ enabled: false,+ },+ ],+ theme: "system",+ }+ } else {+ embedOptions.value = {+ selectedTab: "params",+ tabs: [+ { value: "params", label: t("tab.parameters"), enabled: false },+ { value: "bodyParams", label: t("tab.body"), enabled: false },+ { value: "headers", label: t("tab.headers"), enabled: false },+ {+ value: "authorization",+ label: t("tab.authorization"),+ enabled: false,+ },+ {+ value: "requestVariables",+ label: t("tab.variables"),+ enabled: false,+ },+ ],+ theme: "system",+ }+ }+ return+ }++ const parsedEmbedProperties = JSON.parse(embedProperties)+ if (isGQL) {+ gqlEmbedOptions.value = {+ selectedTab: parsedEmbedProperties.options[0],+ tabs: gqlEmbedOptions.value.tabs.map((tab) => ({+ ...tab,+ enabled: parsedEmbedProperties.options.includes(tab.value),+ })),+ theme: parsedEmbedProperties.theme,}} else {- const parsedEmbedProperties = JSON.parse(embedProperties)embedOptions.value = {selectedTab: parsedEmbedProperties.options[0],- tabs: embedOptions.value.tabs.map((tab) => {- return {- ...tab,- enabled: parsedEmbedProperties.options.includes(tab.value),- }- }),+ tabs: embedOptions.value.tabs.map((tab) => ({+ ...tab,+ enabled: parsedEmbedProperties.options.includes(tab.value),+ })),theme: parsedEmbedProperties.theme,}}}-const createSharedRequest = async (request: HoppRESTRequest | null) => {- if (request && selectedWidget.value) {- const properties = {- options: ["parameters", "body", "headers"],- theme: "system",- }- shareRequestCreatingLoading.value = true- const sharedRequestResult = await createShortcode(- request,- selectedWidget.value.value === "embed"- ? JSON.stringify(properties)- : undefined- )()+const createSharedRequest = async (+ request: HoppRESTRequest | HoppGQLRequest | null+) => {+ if (!request || !selectedWidget.value) return- platform.analytics?.logEvent({- type: "HOPP_SHORTCODE_CREATED",- })+ const isGQL = !isRESTRequest(request)- if (E.isLeft(sharedRequestResult)) {- toast.error(`${sharedRequestResult.left.error}`)- toast.error(t("error.something_went_wrong"))- } else if (E.isRight(sharedRequestResult)) {- if (sharedRequestResult.right.createShortcode) {- shareRequestCreatingLoading.value = false- requestToShare.value = {- ...JSON.parse(sharedRequestResult.right.createShortcode.request),- id: sharedRequestResult.right.createShortcode.id,- }- step.value = 2-- if (sharedRequestResult.right.createShortcode.properties) {- const parsedEmbedProperties = JSON.parse(- sharedRequestResult.right.createShortcode.properties- )-- embedOptions.value = {- selectedTab: parsedEmbedProperties.options[0],- tabs: embedOptions.value.tabs.map((tab) => {- return {- ...tab,- enabled: parsedEmbedProperties.options.includes(tab.value),- }- }),- theme: parsedEmbedProperties.theme,- }- }- }+ // Default embed tab set per protocol. The values must match the tab.value+ // strings used by each CustomizeModal so the round-trip through+ // `embedProperties` correctly toggles checkboxes on later loads.+ const defaultEmbedOptions = isGQL+ ? ["query", "variables", "headers"]+ : ["parameters", "body", "headers"]++ const properties = {+ options: defaultEmbedOptions,+ theme: "system",+ }++ shareRequestCreatingLoading.value = true+ const sharedRequestResult = await createShortcode(+ request,+ selectedWidget.value.value === "embed"+ ? JSON.stringify(properties)+ : undefined+ )()++ platform.analytics?.logEvent({+ type: "HOPP_SHORTCODE_CREATED",+ })++ // Reset before the early-return branches — an error must not strand the+ // modal on an infinite spinner+ shareRequestCreatingLoading.value = false++ if (E.isLeft(sharedRequestResult)) {+ toast.error(`${sharedRequestResult.left.error}`)+ toast.error(t("error.something_went_wrong"))+ return+ }++ if (!sharedRequestResult.right.createShortcode) return++ requestToShare.value = {+ ...JSON.parse(sharedRequestResult.right.createShortcode.request),+ id: sharedRequestResult.right.createShortcode.id,+ }+ step.value = 2++ if (!sharedRequestResult.right.createShortcode.properties) return++ const parsedEmbedProperties = JSON.parse(+ sharedRequestResult.right.createShortcode.properties+ )++ // Hydrate the matching options ref so the customize modal opens with+ // the just-saved selections.+ if (isGQL) {+ gqlEmbedOptions.value = {+ selectedTab: parsedEmbedProperties.options[0],+ tabs: gqlEmbedOptions.value.tabs.map((tab) => ({+ ...tab,+ enabled: parsedEmbedProperties.options.includes(tab.value),+ })),+ theme: parsedEmbedProperties.theme,+ }+ } else {+ embedOptions.value = {+ selectedTab: parsedEmbedProperties.options[0],+ tabs: embedOptions.value.tabs.map((tab) => ({+ ...tab,+ enabled: parsedEmbedProperties.options.includes(tab.value),+ })),+ theme: parsedEmbedProperties.theme,}}}const customizeSharedRequest = (- request: HoppRESTRequest,+ request: HoppRESTRequest | HoppGQLRequest,shredRequestID: string,embedProperties?: string | null) => {@@ -503,11 +639,21 @@ const getErrorMessage = (err: GQLError<string>) => {}}-const openRequestInNewTab = (request: HoppRESTRequest) => {- restTab.createNewTab({+const openRequestInNewTab = (request: HoppRESTRequest | HoppGQLRequest) => {+ if (isRESTRequest(request)) {+ workspaceTab.createNewTab({+ isDirty: false,+ request: request as HoppRESTRequest,+ type: "request",+ })+ return+ }+ // GraphQL shortcode — open as a gql-request tab in the unified workspace.+ workspaceTab.createNewTab({isDirty: false,- request,- type: "request",+ request: request as HoppGQLRequest,+ type: "gql-request",+ cursorPosition: 0,})}diff --git a/packages/hoppscotch-common/src/components/share/templates/Embeds.vue b/packages/hoppscotch-common/src/components/share/templates/Embeds.vueindex b2ce645fa..f31ca75c7 100644--- a/packages/hoppscotch-common/src/components/share/templates/Embeds.vue+++ b/packages/hoppscotch-common/src/components/share/templates/Embeds.vue@@ -58,11 +58,7 @@ import { computed } from "vue"import { useI18n } from "~/composables/i18n"type Tabs =- | "params"- | "bodyParams"- | "headers"- | "authorization"- | "requestVariables"+ "params" | "bodyParams" | "headers" | "authorization" | "requestVariables"type EmbedOption = {selectedTab: Tabsdiff --git a/packages/hoppscotch-common/src/components/share/templates/EmbedsGQL.vue b/packages/hoppscotch-common/src/components/share/templates/EmbedsGQL.vuenew file mode 100644index 000000000..cb7975272--- /dev/null+++ b/packages/hoppscotch-common/src/components/share/templates/EmbedsGQL.vue@@ -0,0 +1,104 @@+<template>+ <div+ class="flex flex-col p-4 border rounded border-dividerDark"+ :class="embedColours"+ >+ <div class="flex items-stretch space-x-2">+ <span+ class="flex items-center flex-1 min-w-0 border rounded"+ :class="embedColours"+ >+ <span+ class="flex w-16 rounded-l h-full items-center justify-center border-r flex-shrink-0"+ :class="embedColours"+ >+ <component :is="IconGraphql" class="h-4 w-4" />+ </span>+ <span class="flex-1 min-w-0 px-3 truncate">+ {{ url }}+ </span>+ </span>+ <button+ class="flex items-center justify-center flex-shrink-0 px-3 py-2 font-semibold border rounded"+ :class="embedColours"+ >+ {{ t("request.run") }}+ </button>+ </div>+ <div+ class="flex overflow-x-scroll"+ :class="[{ 'border-b pt-2': !noActiveTab }, embedColours]"+ >+ <span+ v-for="option in embedOptions.tabs"+ v-show="option.enabled"+ :key="option.value"+ class="p-2"+ :class="[+ {+ 'border-b':+ embedOptions.tabs.filter((tab) => tab.enabled)[0]?.value ===+ option.value,+ },+ embedColours,+ ]"+ >+ {{ t(option.label) }}+ </span>+ </div>+ </div>+</template>++<script lang="ts" setup>+import { usePreferredDark, useVModel } from "@vueuse/core"+import { computed } from "vue"++import { useI18n } from "~/composables/i18n"+import IconGraphql from "~icons/hopp/graphql"++// Mirrors share/templates/Embeds.vue but for GraphQL: a single URL bar with+// the Hopp GraphQL icon instead of an HTTP method, and a Run button instead+// of Send. Tabs come from the parent CustomizeGQLModal so the toggles match+// the eventual embed surface 1:1.+type Tabs = "query" | "variables" | "headers" | "authorization"++type EmbedOption = {+ selectedTab: Tabs+ tabs: {+ value: Tabs+ label: string+ enabled: boolean+ }[]+ theme: "light" | "dark" | "system"+}++const props = defineProps<{+ url: string | undefined+ modelValue: EmbedOption+}>()++const embedOptions = useVModel(props, "modelValue")++const t = useI18n()++const noActiveTab = computed(() =>+ embedOptions.value.tabs.every((tab) => !tab.enabled)+)++const systemPrefersDark = usePreferredDark()++const embedColours = computed(() => {+ const { theme } = embedOptions.value++ const darkThemeClasses = "bg-dark-800 text-white !border-dark-50"+ const lightThemeClasses = "bg-white text-black !border-white-50"++ const colorThemeMap = {+ light: lightThemeClasses,+ dark: darkThemeClasses,+ system: systemPrefersDark.value ? darkThemeClasses : lightThemeClasses,+ }++ return colorThemeMap[theme]+})+</script>diff --git a/packages/hoppscotch-common/src/components/smart/EnvInput.vue b/packages/hoppscotch-common/src/components/smart/EnvInput.vueindex 1a1e79821..fdafe6895 100644--- a/packages/hoppscotch-common/src/components/smart/EnvInput.vue+++ b/packages/hoppscotch-common/src/components/smart/EnvInput.vue@@ -98,7 +98,7 @@ import IconEye from "~icons/lucide/eye"import IconEyeoff from "~icons/lucide/eye-off"import { CompletionContext, autocompletion } from "@codemirror/autocomplete"import { useService } from "dioc/vue"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { syntaxTree } from "@codemirror/language"import { uniqueID } from "~/helpers/utils/uniqueID"import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"@@ -390,13 +390,15 @@ const aggregateEnvs = useReadonlyStream([]) as Ref<AggregateEnvironment[]>-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const envVars = computed(() => {// If envs are passed directly as props, mask secrets and return them.// Keep sourceEnvID: the env tooltip uses it to look up secret/current values// for collection-scoped variables (otherwise they show as "Empty").- if (props.envs?.length) {+ // An explicitly-passed EMPTY list scopes to nothing (embeds) — only a+ // missing prop falls back to the global aggregate envs.+ if (props.envs) {return props.envs.map(({key,@@ -419,16 +421,21 @@ const envVars = computed(() => {const currentTab = tabs.currentActiveTab.valueconst { document } = currentTabconst isRequest = document.type === "request"- const isExample = document.type === "example-response"+ const isRESTExample = document.type === "example-response"+ const isGQLExample = document.type === "gql-example-response"+ const isExample = isRESTExample || isGQLExample+ const isGQLRequest = document.type === "gql-request"const requestVariables = isRequest? document.request.requestVariables- : isExample+ : isRESTExample? document.response.originalRequest.requestVariables: []const inheritedVariables =- isRequest || isExample ? document.inheritedProperties?.variables : []+ isRequest || isExample || isGQLRequest+ ? document.inheritedProperties?.variables+ : []// Merge in precedence order (request → collection → environment).// Collection secrets stay masked here (showSecretCollectionValues = false).diff --git a/packages/hoppscotch-common/src/components/workspace/Selector.vue b/packages/hoppscotch-common/src/components/workspace/Selector.vueindex 81535d83d..90a4a0cb4 100644--- a/packages/hoppscotch-common/src/components/workspace/Selector.vue+++ b/packages/hoppscotch-common/src/components/workspace/Selector.vue@@ -186,10 +186,7 @@ const switchToPersonalWorkspace = () => {watch(() => currentUser.value,(user) => {- if (!user) {- switchToPersonalWorkspace()- teamListadapter.dispose()- }+ if (!user) teamListadapter.dispose()})diff --git a/packages/hoppscotch-common/src/composables/ai-experiments.ts b/packages/hoppscotch-common/src/composables/ai-experiments.tsindex a71e78ccb..723b4d9ca 100644--- a/packages/hoppscotch-common/src/composables/ai-experiments.ts+++ b/packages/hoppscotch-common/src/composables/ai-experiments.ts@@ -2,21 +2,15 @@ import { computed, Ref, ref } from "vue"import { useReadonlyStream } from "./stream"import { platform } from "~/platform"import { useSetting } from "./settings"-import { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"+import { HoppGQLRequest, HoppRESTRequest, isGQLRequest } from "@hoppscotch/data"import { useToast } from "@composables/toast"import { useI18n } from "@composables/i18n"import * as E from "fp-ts/Either"-import { useRoute } from "vue-router"import { invokeAction } from "~/helpers/actions"export const useRequestNameGeneration = (targetNameRef: Ref<string>) => {const toast = useToast()const t = useI18n()- const route = useRoute()-- const targetPage = computed(() => {- return route.fullPath.includes("/graphql") ? "gql" : "rest"- })const isGenerateRequestNamePending = ref(false)@@ -54,9 +48,11 @@ export const useRequestNameGeneration = (targetNameRef: Ref<string>) => {isGenerateRequestNamePending.value = true+ // Derive from the request itself — the route can't tell a GQL request+ // apart on the unified REST pageplatform.analytics?.logEvent({type: "EXPERIMENTS_GENERATE_REQUEST_NAME_WITH_AI",- platform: targetPage.value,+ platform: isGQLRequest(requestContext) ? "gql" : "rest",})const result = await generateRequestNameForPlatform(diff --git a/packages/hoppscotch-common/src/composables/codemirror.ts b/packages/hoppscotch-common/src/composables/codemirror.tsindex 112752355..df6e97a95 100644--- a/packages/hoppscotch-common/src/composables/codemirror.ts+++ b/packages/hoppscotch-common/src/composables/codemirror.ts@@ -25,7 +25,17 @@ import {insertTab,redo,} from "@codemirror/commands"-import { Completion, autocompletion } from "@codemirror/autocomplete"+import {+ Completion,+ CompletionContext,+ CompletionResult,+ CompletionSource,+ autocompletion,+} from "@codemirror/autocomplete"+import {+ AggregateEnvironment,+ getAggregateEnvsWithCurrentValue,+} from "~/newstore/environments"import { linter } from "@codemirror/lint"import { watch, ref, Ref, onMounted, onBeforeUnmount } from "vue"import { javascriptLanguage } from "@codemirror/lang-javascript"@@ -85,6 +95,11 @@ type CodeMirrorOptions = {// NOTE: This property is not reactiveenvironmentHighlights: boolean+ // Embed-only env scope for highlights/tooltips/completions; `undefined`+ // keeps the live tab + global stream. Pass a `computed` into the reactive+ // options object so scope changes (e.g. request-variable edits) propagate.+ envs?: AggregateEnvironment[]+/*** Whether or not to highlight predefined variables, such as: `<<$guid>>`.* - These are special variables that starts with a dolar sign.@@ -103,39 +118,83 @@ type CodeMirrorOptions = {onInit?: (view: EditorView) => void}-const hoppCompleterExt = (completer: Completer): Extension => {- return autocompletion({- override: [- async (context) => {- // Expensive operation! Disable on bigger files ?- const text = context.state.doc.toJSON().join(context.state.lineBreak)-- const line = context.state.doc.lineAt(context.pos)- const lineStart = line.from- const lineNo = line.number - 1- const ch = context.pos - lineStart-- // Only do trigger on type when typing a word token, else stop (unless explicit)- if (!context.matchBefore(/\w+/) && !context.explicit)- return {- from: context.pos,- options: [],- }+const languageCompletionSource =+ (completer: Completer): CompletionSource =>+ async (context) => {+ // Expensive operation! Disable on bigger files ?+ const text = context.state.doc.toJSON().join(context.state.lineBreak)- const result = await completer(text, { line: lineNo, ch })+ const line = context.state.doc.lineAt(context.pos)+ const lineStart = line.from+ const lineNo = line.number - 1+ const ch = context.pos - lineStart- // Use more completion features ?- const completions =- result?.completions.map<Completion>((comp) => ({- label: comp.text,- detail: comp.meta,- })) ?? []+ // Only do trigger on type when typing a word token, else stop (unless explicit)+ if (!context.matchBefore(/\w+/) && !context.explicit)+ return {+ from: context.pos,+ options: [],+ }- return {- from: context.state.wordAt(context.pos)?.from ?? context.pos,- options: completions,- }- },+ const result = await completer(text, { line: lineNo, ch })++ // Use more completion features ?+ const completions =+ result?.completions.map<Completion>((comp) => ({+ label: comp.text,+ detail: comp.meta,+ })) ?? []++ return {+ from: context.state.wordAt(context.pos)?.from ?? context.pos,+ options: completions,+ }+ }++/**+ * Environment variable completion for `<<...>>` templates — the multi-line+ * editor counterpart of SmartEnvInput's `envAutoCompletion`. Suggests the+ * aggregate env list (predefined + selected + global) with the current→initial+ * value fallback in the info preview; secrets stay masked.+ */+const makeEnvCompletionSource =+ (getScopedEnvs?: () => AggregateEnvironment[] | undefined) =>+ (context: CompletionContext): CompletionResult | null => {+ const tagBefore = context.matchBefore(/<<\$?[A-Za-z0-9_.-]*/)+ if (!tagBefore && !context.explicit) return null++ // If closing brackets already exist after the cursor, don't re-insert them+ const textAfter = context.state.sliceDoc(context.pos, context.pos + 2)+ const hasClosingBrackets = textAfter === ">>"++ // Both the scoped list and the global store are read at fire time so+ // completions always see fresh values+ const options = (getScopedEnvs?.() ?? getAggregateEnvsWithCurrentValue())+ .filter((env) => !!env.key)+ .map<Completion>((env) => ({+ label: `<<${env.key}>>`,+ info: env.secret+ ? "••••••"+ : env.currentValue || env.initialValue || "",+ apply: hasClosingBrackets ? `<<${env.key}` : `<<${env.key}>>`,+ }))++ return {+ from: tagBefore ? tagBefore.from : context.pos,+ options,+ validFor: /^(<<\$?[A-Za-z0-9_.-]*)?$/,+ }+ }++const hoppCompleterExt = (+ completer: Completer | null,+ envComplete: boolean,+ getScopedEnvs?: () => AggregateEnvironment[] | undefined+): Extension => {+ return autocompletion({+ override: [+ ...(completer ? [languageCompletionSource(completer)] : []),+ ...(envComplete ? [makeEnvCompletionSource(getScopedEnvs)] : []),],})}@@ -167,12 +226,15 @@ const hoppLinterExt = (hoppLinter: LinterDefinition | undefined): Extension => {const hoppLang = (language: Language | undefined,linter?: LinterDefinition | undefined,- completer?: Completer | undefined+ completer?: Completer | undefined,+ envComplete = false,+ getScopedEnvs?: () => AggregateEnvironment[] | undefined): Extension | LanguageSupport => {const exts: Extension[] = []exts.push(hoppLinterExt(linter))- if (completer) exts.push(hoppCompleterExt(completer))+ if (completer || envComplete)+ exts.push(hoppCompleterExt(completer ?? null, envComplete, getScopedEnvs))// Add comment token configuration for JSONC to enable comment toggleif (language === jsoncLanguage) {@@ -282,8 +344,17 @@ const parseDoc = (const getEditorLanguage = (langMime: string,linter: LinterDefinition | undefined,- completer: Completer | undefined-): Extension => hoppLang(getLanguage(langMime) ?? undefined, linter, completer)+ completer: Completer | undefined,+ envComplete = false,+ getScopedEnvs?: () => AggregateEnvironment[] | undefined+): Extension =>+ hoppLang(+ getLanguage(langMime) ?? undefined,+ linter,+ completer,+ envComplete,+ getScopedEnvs+ )/*** Strips the `export {};\n` prefix from the value for display in the editor.@@ -335,7 +406,11 @@ export function useCodemirror(const view = ref<EditorView>()const environmentTooltip = options.environmentHighlights- ? new HoppEnvironmentPlugin(subscribeToStream, view)+ ? new HoppEnvironmentPlugin(+ subscribeToStream,+ view,+ options.envs !== undefined ? () => options.envs : undefined+ ): nullconst closeContextMenu = () => {@@ -483,7 +558,12 @@ export function useCodemirror(? ((options.extendedEditorConfig.mode as any) ?? ""): "",options.linter ?? undefined,- options.completer ?? undefined+ options.completer ?? undefined,+ // Completions can never apply in a read-only editor — highlights+ // and tooltips stay on, the popup stays off+ options.environmentHighlights &&+ !options.extendedEditorConfig.readOnly,+ () => options.envs)),lineWrapping.of(@@ -624,7 +704,10 @@ export function useCodemirror(? ((options.extendedEditorConfig.mode as any) ?? ""): "",options.linter ?? undefined,- options.completer ?? undefined+ options.completer ?? undefined,+ options.environmentHighlights &&+ !options.extendedEditorConfig.readOnly,+ () => options.envs)),})diff --git a/packages/hoppscotch-common/src/composables/gqlWorkspaceVisibility.ts b/packages/hoppscotch-common/src/composables/gqlWorkspaceVisibility.tsnew file mode 100644index 000000000..8f0ea9fd4--- /dev/null+++ b/packages/hoppscotch-common/src/composables/gqlWorkspaceVisibility.ts@@ -0,0 +1,25 @@+import { computed } from "vue"++import { useSetting } from "~/composables/settings"++/**+ * Composable that exposes whether GraphQL is hosted inside the unified REST+ * workspace, based on the `ENABLE_GQL_IN_REST_WORKSPACE` experimental flag.+ *+ * When enabled, GraphQL requests open as `gql-request` tabs in the REST+ * workspace and the protocol switcher is available. When disabled, GraphQL+ * stays on the standalone /graphql page.+ */+export function useGqlWorkspaceVisibility() {+ const ENABLE_GQL_IN_REST_WORKSPACE = useSetting(+ "ENABLE_GQL_IN_REST_WORKSPACE"+ )++ const isGqlWorkspaceEnabled = computed(+ () => ENABLE_GQL_IN_REST_WORKSPACE.value+ )++ return {+ isGqlWorkspaceEnabled,+ }+}diff --git a/packages/hoppscotch-common/src/composables/useDocumentationWorker.ts b/packages/hoppscotch-common/src/composables/useDocumentationWorker.tsindex 211a3e713..c6b8d390d 100644--- a/packages/hoppscotch-common/src/composables/useDocumentationWorker.ts+++ b/packages/hoppscotch-common/src/composables/useDocumentationWorker.ts@@ -1,9 +1,13 @@-import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data"+import {+ HoppCollection,+ HoppGQLRequest,+ HoppRESTRequest,+} from "@hoppscotch/data"import { ref, readonly } from "vue"export interface DocumentationItem {type: "folder" | "request"- item: HoppCollection | HoppRESTRequest+ item: HoppCollection | HoppRESTRequest | HoppGQLRequestparentPath: stringid: stringpathOrID?: string | nulldiff --git a/packages/hoppscotch-common/src/helpers/RequestRunner.ts b/packages/hoppscotch-common/src/helpers/RequestRunner.tsindex 94221a6f4..dc8eb6ee5 100644--- a/packages/hoppscotch-common/src/helpers/RequestRunner.ts+++ b/packages/hoppscotch-common/src/helpers/RequestRunner.ts@@ -56,7 +56,7 @@ import {import { HoppTab } from "~/services/tab"import { updateTeamEnvironment } from "./backend/mutations/TeamEnvironment"import { createRESTNetworkRequestStream } from "./network"-import { HoppRequestDocument } from "./rest/document"+import { HoppRequestDocument } from "./tab/document"import { stripIterationVarsFromEnvs } from "./runner/iteration-vars"import {getTemporaryVariables,@@ -123,6 +123,18 @@ export const waitForBrowserPaint = (): Promise<void> => {})}+// Empty env state for isolated runs (embeds) — viewer envs must not+// resolve into a shared request's execution+export const emptyInitialEnvironmentState = (): InitialEnvironmentState => ({+ initialGlobalEnvs: [],+ initialEnvID: "",+ initialSelectedEnvs: [],+ initialEnvironmentIndex: { type: "NO_ENV_SELECTED" },+ initialEnvName: "",+ initialEnvs: { global: [], selected: [], temp: [] },+ initialEnvsForComparison: { global: [], selected: [] },+})+/*** Captures the initial environment state before request execution* So that we can compare and update environment variables after test script execution@@ -353,7 +365,11 @@ const getEnvironmentVariableValue = ()}-const delegatePreRequestScriptRunner = (+// Re-exported for consumers that resolve envs the same way the runner does+// (the GQL tab-connection service imports it from here)+export { filterNonEmptyEnvironmentVariables }++export const delegatePreRequestScriptRunner = (request: HoppRESTRequest,envs: {global: Environment["variables"]@@ -401,7 +417,7 @@ const delegatePreRequestScriptRunner = (})}-const runPostRequestScript = (+export const runPostRequestScript = (envs: TestResult["envs"],request: HoppRESTRequest,response: HoppRESTResponse,@@ -450,8 +466,25 @@ const runPostRequestScript = (})}+/**+ * Executes the tab's REST request end-to-end: pre-request script, env/auth+ * templating, network call, then post-request (test) script with env/cookie+ * writeback and history capture.+ *+ * @param tab The tab whose document request is run; response/testResults are+ * written back onto it+ * @param runOptions `isolatedEnvs` (embeds) runs with an empty env set and+ * skips every viewer-store writeback (envs, cookies, history)+ * @returns A cancel function and a promise of the response stream (`Left` on+ * script failure or cancellation)+ */export function runRESTRequest$(- tab: Ref<HoppTab<HoppRequestDocument>>+ tab: Ref<HoppTab<HoppRequestDocument>>,+ runOptions?: {+ // Embeds: empty env set for templating/scripts, no env/cookie/history+ // writeback to the viewer's stores+ isolatedEnvs?: boolean+ }): [() => void,Promise<@@ -467,7 +500,11 @@ export function runRESTRequest$(cancelFunc?.()}- const cookieJarEntries = getCookieJarEntries()+ // Isolated runs never see the viewer's cookie jar — independent of the+ // platform's cookiesEnabled flag+ const cookieJarEntries = runOptions?.isolatedEnvs+ ? null+ : getCookieJarEntries()const { request, inheritedProperties } = tab.value.document@@ -499,7 +536,9 @@ export function runRESTRequest$(initialEnvName,initialEnvs,initialEnvsForComparison,- } = captureInitialEnvironmentState()+ } = runOptions?.isolatedEnvs+ ? emptyInitialEnvironmentState()+ : captureInitialEnvironmentState()// Extract inherited scripts from collection hierarchy, filtering out empty/module-prefix-only scriptsconst inheritedScripts = inheritedProperties?.scripts ?? []@@ -566,22 +605,35 @@ export function runRESTRequest$(combineEnvVariables(finalEnvs))- const effectiveRequest = await getEffectiveRESTRequest(finalRequest, {- id: "env-id",- v: 2,- name: "Env",- variables: finalEnvsWithNonEmptyValues,- })+ const effectiveRequest = await getEffectiveRESTRequest(+ finalRequest,+ {+ id: "env-id",+ v: 2,+ name: "Env",+ variables: finalEnvsWithNonEmptyValues,+ },+ false,+ false,+ // Isolated runs resolve missing body vars to "" like the URL/headers+ !runOptions?.isolatedEnvs+ )- const [stream, cancelRun] =- await createRESTNetworkRequestStream(effectiveRequest)+ const [stream, cancelRun] = await createRESTNetworkRequestStream(+ effectiveRequest,+ // Isolated runs also opt out of the interceptor-level cookie jar+ { noCookieJar: runOptions?.isolatedEnvs }+ )cancelFunc = cancelRunconst subscription = stream.pipe(filter((res) => res.type === "success" || res.type === "fail")).subscribe(async (res) => {if (res.type === "success" || res.type === "fail") {- executedResponses$.next(res)+ // Sole subscriber persists history — skip for isolated runs+ if (!runOptions?.isolatedEnvs) {+ executedResponses$.next(res)+ }const postRequestScriptResult = await runPostRequestScript(preRequestScriptResult.right.updatedEnvs,@@ -619,15 +671,16 @@ export function runRESTRequest$(initialSelectedEnvs)- // Check if scripts actually modified environment variables+ // Skip env writeback for isolated runsif (+ !runOptions?.isolatedEnvs &&hasEnvironmentChanges(initialEnvsForComparison, // Initial environment when request startedpostRequestScriptResult.right.envs // Final script environment after test script execution)) {updateEnvsAfterTestScript(- combinedResult,+ combinedResult.right.envs,initialEnvironmentIndex,initialEnvName,initialEnvsForComparison,@@ -692,8 +745,8 @@ export function runRESTRequest$(return [cancel, res]}-function updateEnvsAfterTestScript(- runResult: E.Right<SandboxTestResult>,+export function updateEnvsAfterTestScript(+ finalEnvs: TestResult["envs"],initialEnvironmentIndex: SelectedEnvironmentIndex,initialEnvName: string,initialEnvsForComparison: TestResult["envs"],@@ -706,16 +759,16 @@ function updateEnvsAfterTestScript(// globals (and the same happens the other way for TEAM_ENV).const globalChanged = hasScopeChanges(initialEnvsForComparison.global,- runResult.right.envs.global+ finalEnvs.global)const selectedChanged = hasScopeChanges(initialEnvsForComparison.selected,- runResult.right.envs.selected+ finalEnvs.selected)if (globalChanged) {const globalEnvVariables = updateEnvironments(- runResult.right.envs.global,+ finalEnvs.global,"global",undefined,nonSecretKeysOf(initialEnvsForComparison.global)@@ -729,7 +782,7 @@ function updateEnvsAfterTestScript(if (selectedChanged) {const selectedEnvVariables = updateEnvironments(- cloneDeep(runResult.right.envs.selected),+ cloneDeep(finalEnvs.selected),"selected",initialEnvID,nonSecretKeysOf(initialEnvsForComparison.selected)@@ -790,7 +843,7 @@ const hasScopeChanges = (getRemovedEnvVariables(initial, final).length > 0 ||getUpdatedEnvVariables(initial, final).length > 0-const hasEnvironmentChanges = (+export const hasEnvironmentChanges = (initialEnvs: TestResult["envs"],finalEnvs: TestResult["envs"]): boolean =>@@ -1017,7 +1070,9 @@ export async function runTestRunnerRequest()) {updateEnvsAfterTestScript(- E.right(filteredPostRequestScriptResult),+ // Filtered — a data run must not persist data-file columns+ // as environment variables.+ filteredPostRequestScriptResult.envs,initialEnvironmentIndex,initialEnvName,initialEnvsForComparison,@@ -1145,7 +1200,7 @@ const resolveEnvVars = (}})-function translateToSandboxTestResults(+export function translateToSandboxTestResults(testDesc: SandboxTestResult,initialGlobalEnvs: Environment["variables"],initialSelectedEnvs: Environment["variables"]diff --git a/packages/hoppscotch-common/src/helpers/actions.ts b/packages/hoppscotch-common/src/helpers/actions.tsindex 1d4f639c7..55757967b 100644--- a/packages/hoppscotch-common/src/helpers/actions.ts+++ b/packages/hoppscotch-common/src/helpers/actions.ts@@ -4,7 +4,7 @@import { Ref, onBeforeUnmount, onMounted, reactive, watch, computed } from "vue"import { BehaviorSubject } from "rxjs"-import { HoppRequestDocument } from "./rest/document"+import { HoppGQLRequestDocument, HoppRequestDocument } from "./tab/document"import { Environment, HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"import { RESTOptionTabs } from "~/components/http/RequestOptions.vue"import { HoppGQLSaveContext } from "./graphql/document"@@ -120,9 +120,10 @@ export type HoppAction =| "workspace.switch" // Switch workspace| "rest.request.open" // Open REST request| "request.open-tab" // Open REST request- | "share.request" // Share REST request+ | "share.request" // Share REST or GraphQL request| "tab.duplicate-tab" // Duplicate REST request| "gql.request.open" // Open GraphQL request+ | "rest.gql-request.open" // Open GQL request in REST tab| "app.quit" // Quit app/**@@ -181,7 +182,7 @@ type HoppActionArgsMap = {tab: RESTOptionTabs | GQLOptionTabs}"share.request": {- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequest}"tab.duplicate-tab": {tabID?: string@@ -190,6 +191,9 @@ type HoppActionArgsMap = {request: HoppGQLRequestsaveContext?: HoppGQLSaveContext}+ "rest.gql-request.open": {+ doc: HoppGQLRequestDocument+ }"modals.environment.add": {envName: stringvariableName: string@@ -210,8 +214,7 @@ export type HoppActionWithArgs = keyof HoppActionArgsMap*/export type HoppActionWithOptionalArgs =- | HoppActionWithNoArgs- | KeysWithValueUndefined<HoppActionArgsMap>+ HoppActionWithNoArgs | KeysWithValueUndefined<HoppActionArgsMap>/*** HoppActions which do not require arguments for their invocationdiff --git a/packages/hoppscotch-common/src/helpers/auth/index.ts b/packages/hoppscotch-common/src/helpers/auth/index.tsindex 02103ce95..e09483712 100644--- a/packages/hoppscotch-common/src/helpers/auth/index.ts+++ b/packages/hoppscotch-common/src/helpers/auth/index.ts@@ -1,5 +1,5 @@import { getService } from "~/modules/dioc"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { parseTemplateStringE } from "@hoppscotch/data"import * as E from "fp-ts/Either"import {@@ -14,7 +14,8 @@ export const replaceTemplateStringsInObjectValues = <obj: T,source: "REST" | "GQL" = "REST") => {- const document = getService(RESTTabService).currentActiveTab.value.document+ const document =+ getService(WorkspaceTabsService).currentActiveTab.value.document// Only a REST request tab has request/collection variables.const isRESTRequest = source === "REST" && document.type === "request"diff --git a/packages/hoppscotch-common/src/helpers/backend/GQLClient.ts b/packages/hoppscotch-common/src/helpers/backend/GQLClient.tsindex d3ac3baab..1f9191300 100644--- a/packages/hoppscotch-common/src/helpers/backend/GQLClient.ts+++ b/packages/hoppscotch-common/src/helpers/backend/GQLClient.ts@@ -19,7 +19,7 @@ import { AuthConfig, authExchange } from "@urql/exchange-auth"import { SubscriptionClient } from "subscriptions-transport-ws"import * as E from "fp-ts/Either"import * as TE from "fp-ts/TaskEither"-import { pipe, constVoid, flow } from "fp-ts/function"+import { pipe, flow } from "fp-ts/function"import { subscribe, pipe as wonkaPipe } from "wonka"import { filter, map, Subject, Subscription } from "rxjs"import { platform } from "~/platform"diff --git a/packages/hoppscotch-common/src/helpers/backend/helpers.ts b/packages/hoppscotch-common/src/helpers/backend/helpers.tsindex 2e3243d7e..37b46847d 100644--- a/packages/hoppscotch-common/src/helpers/backend/helpers.ts+++ b/packages/hoppscotch-common/src/helpers/backend/helpers.ts@@ -6,7 +6,6 @@ import {HoppRESTHeaders,HoppRESTRequest,makeCollection,- translateToNewRequest,} from "@hoppscotch/data"import * as A from "fp-ts/Array"import * as E from "fp-ts/Either"@@ -16,7 +15,7 @@ import { z } from "zod"import { getI18n } from "~/modules/i18n"import { TeamCollection } from "../teams/TeamCollection"-import { TeamRequest } from "../teams/TeamRequest"+import { TeamRequest, normalizeTeamRequestBody } from "../teams/TeamRequest"import { GQLError, runGQLQuery } from "./GQLClient"import { stripCollectionTreeForStore } from "~/helpers/clientLocalVariables"import {@@ -102,7 +101,7 @@ const getCollectionRequests = async (collID: string) => {(x) =><TeamRequest>{id: x.id,- request: translateToNewRequest(JSON.parse(x.request)),+ request: normalizeTeamRequestBody(x.request),collectionID: collID,title: x.title,}diff --git a/packages/hoppscotch-common/src/helpers/backend/mutations/MockServer.ts b/packages/hoppscotch-common/src/helpers/backend/mutations/MockServer.tsindex 3a17f394a..2a16be225 100644--- a/packages/hoppscotch-common/src/helpers/backend/mutations/MockServer.ts+++ b/packages/hoppscotch-common/src/helpers/backend/mutations/MockServer.ts@@ -19,12 +19,10 @@ type CreateMockServerError =| "mock_server/already_exists"type UpdateMockServerError =- | "mock_server/not_found"- | "mock_server/access_denied"+ "mock_server/not_found" | "mock_server/access_denied"type DeleteMockServerError =- | "mock_server/not_found"- | "mock_server/access_denied"+ "mock_server/not_found" | "mock_server/access_denied"export const createMockServer = (name: string,diff --git a/packages/hoppscotch-common/src/helpers/backend/mutations/PublishedDocs.ts b/packages/hoppscotch-common/src/helpers/backend/mutations/PublishedDocs.tsindex e0320473f..b1bee236d 100644--- a/packages/hoppscotch-common/src/helpers/backend/mutations/PublishedDocs.ts+++ b/packages/hoppscotch-common/src/helpers/backend/mutations/PublishedDocs.ts@@ -19,12 +19,10 @@ type CreatePublishedDocError =| "team/invalid_id"type UpdatePublishedDocError =- | "published_docs/update_failed"- | "published_docs/not_found"+ "published_docs/update_failed" | "published_docs/not_found"type DeletePublishedDocError =- | "published_docs/deletion_failed"- | "published_docs/not_found"+ "published_docs/deletion_failed" | "published_docs/not_found"export const createPublishedDoc = (doc: CreatePublishedDocsArgs) =>runMutation<diff --git a/packages/hoppscotch-common/src/helpers/backend/mutations/Shortcode.ts b/packages/hoppscotch-common/src/helpers/backend/mutations/Shortcode.tsindex d827b4d80..065328b86 100644--- a/packages/hoppscotch-common/src/helpers/backend/mutations/Shortcode.ts+++ b/packages/hoppscotch-common/src/helpers/backend/mutations/Shortcode.ts@@ -1,4 +1,4 @@-import { HoppRESTRequest } from "@hoppscotch/data"+import { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"import { platform } from "~/platform"import { runMutation } from "../GQLClient"import {@@ -13,7 +13,7 @@ import {type DeleteShortcodeErrors = "shortcode/not_found"export const createShortcode = (- request: HoppRESTRequest,+ request: HoppRESTRequest | HoppGQLRequest,properties?: string) => platform.backend.createShortcode(request, properties)diff --git a/packages/hoppscotch-common/src/helpers/backend/mutations/Team.ts b/packages/hoppscotch-common/src/helpers/backend/mutations/Team.tsindex 75afa8b96..b7e301fde 100644--- a/packages/hoppscotch-common/src/helpers/backend/mutations/Team.ts+++ b/packages/hoppscotch-common/src/helpers/backend/mutations/Team.ts@@ -29,26 +29,18 @@ type DeleteTeamErrors =| "ea/not_invite_or_admin"type LeaveTeamErrors =- | "team/invalid_id"- | "team/member_not_found"- | "ea/not_invite_or_admin"+ "team/invalid_id" | "team/member_not_found" | "ea/not_invite_or_admin"type CreateTeamErrors = "team/name_invalid" | "ea/not_invite_or_admin"type RenameTeamErrors =- | "ea/not_invite_or_admin"- | "team/invalid_id"- | "team/not_required_role"+ "ea/not_invite_or_admin" | "team/invalid_id" | "team/not_required_role"type UpdateTeamAccessRoleErrors =- | "ea/not_invite_or_admin"- | "team/invalid_id"- | "team/not_required_role"+ "ea/not_invite_or_admin" | "team/invalid_id" | "team/not_required_role"type RemoveTeamMemberErrors =- | "ea/not_invite_or_admin"- | "team/invalid_id"- | "team/not_required_role"+ "ea/not_invite_or_admin" | "team/invalid_id" | "team/not_required_role"export const createTeam = (name: TeamName) => {return pipe(diff --git a/packages/hoppscotch-common/src/helpers/backend/mutations/TeamCollection.ts b/packages/hoppscotch-common/src/helpers/backend/mutations/TeamCollection.tsindex 6549f32e8..2b37a24dc 100644--- a/packages/hoppscotch-common/src/helpers/backend/mutations/TeamCollection.ts+++ b/packages/hoppscotch-common/src/helpers/backend/mutations/TeamCollection.ts@@ -53,6 +53,7 @@ type UpdateCollectionOrderError =| "team/invalid_coll_id"| "team/collection_and_next_collection_are_same"| "team/team_collections_have_different_parents"+ | "team_coll/not_same_parent"export const createNewRootCollection = (title: string, teamID: string) =>runMutation<diff --git a/packages/hoppscotch-common/src/helpers/backend/mutations/TeamInvitation.ts b/packages/hoppscotch-common/src/helpers/backend/mutations/TeamInvitation.tsindex ae5b6648e..4b1587fb0 100644--- a/packages/hoppscotch-common/src/helpers/backend/mutations/TeamInvitation.ts+++ b/packages/hoppscotch-common/src/helpers/backend/mutations/TeamInvitation.ts@@ -19,8 +19,7 @@ export type CreateTeamInvitationErrors =| "user/not_found"type RevokeTeamInvitationErrors =- | "team/not_required_role"- | "team_invite/no_invite_found"+ "team/not_required_role" | "team_invite/no_invite_found"type AcceptTeamInvitationErrors =| "team_invite/no_invite_found"diff --git a/packages/hoppscotch-common/src/helpers/backend/queries/MockServerLogs.ts b/packages/hoppscotch-common/src/helpers/backend/queries/MockServerLogs.tsindex 2e30b2c12..c228ce152 100644--- a/packages/hoppscotch-common/src/helpers/backend/queries/MockServerLogs.ts+++ b/packages/hoppscotch-common/src/helpers/backend/queries/MockServerLogs.ts@@ -17,10 +17,10 @@ export const getMockServerLogs = (TE.tryCatch(async () => {const result = await client- .value!.query<- GetMockServerLogsQuery,- GetMockServerLogsQueryVariables- >(GetMockServerLogsDocument, { mockServerID, skip, take })+ .value!.query<GetMockServerLogsQuery, GetMockServerLogsQueryVariables>(+ GetMockServerLogsDocument,+ { mockServerID, skip, take }+ ).toPromise()if (result.error)diff --git a/packages/hoppscotch-common/src/helpers/backend/queries/PublishedDocs.ts b/packages/hoppscotch-common/src/helpers/backend/queries/PublishedDocs.tsindex 806ef75cf..b7f335fbe 100644--- a/packages/hoppscotch-common/src/helpers/backend/queries/PublishedDocs.ts+++ b/packages/hoppscotch-common/src/helpers/backend/queries/PublishedDocs.ts@@ -12,7 +12,10 @@ import {} from "../graphql"import {HoppCollection,+ HoppGQLRequest,+ HoppRESTRequest,makeCollection,+ translateToGQLRequest,translateToNewRequest,} from "@hoppscotch/data"import type { CollectionDataProps } from "../helpers"@@ -60,12 +63,30 @@ export type PublishedDocQuery = {export type CollectionFolder = {id?: stringfolders: CollectionFolder[]- // Backend stores this as any, we translate it to HoppRESTRequest via translateToNewRequest+ // Opaque JSON on the backend. Each request is shape-detected client-side+ // and routed through `translateToNewRequest` (REST) or `translateToGQLRequest` (GQL).requests: any[]name: stringdata?: string}+// Unified-collection requests can be REST or GQL bodies. Discriminate by shape+// using the same predicate the data package uses internally — `isGQLRequest`+// is gated on `query` + `url` + no `endpoint`.+function translatePublishedRequest(req: any): HoppRESTRequest | HoppGQLRequest {+ // Object check first — `in` throws on primitives+ if (+ !!req &&+ typeof req === "object" &&+ "query" in req &&+ "url" in req &&+ !("endpoint" in req)+ ) {+ return translateToGQLRequest(req)+ }+ return translateToNewRequest(req)+}+// Type for the versions list in the REST response source of truth: packages/hoppscotch-backend/src/published-docs/published-docs.model.tsexport type PublishedDocsVersion = {id: string@@ -144,7 +165,7 @@ export function collectionFolderToHoppCollection(return makeCollection({name: folder.name,folders: folder.folders.map(collectionFolderToHoppCollection),- requests: (folder.requests || []).map(translateToNewRequest),+ requests: (folder.requests || []).map(translatePublishedRequest),auth,headers,variables,@@ -239,8 +260,7 @@ export const findPublishedDocForCollection = (}type GetPublishedDocError =- | "published_docs/not_found"- | "published_docs/unauthorized"+ "published_docs/not_found" | "published_docs/unauthorized"// Get a single published doc by ID (GraphQL)export const getPublishedDocByID = (id: string) =>diff --git a/packages/hoppscotch-common/src/helpers/clientLocalVariables.ts b/packages/hoppscotch-common/src/helpers/clientLocalVariables.tsindex 43046ec22..9c1c8e41b 100644--- a/packages/hoppscotch-common/src/helpers/clientLocalVariables.ts+++ b/packages/hoppscotch-common/src/helpers/clientLocalVariables.ts@@ -115,10 +115,17 @@ export const populateLocalStoresFromCollectionTree = (;(collection.folders ?? []).forEach(populateLocalStoresFromCollectionTree)}-/** Fresh node objects + `folders` arrays; other fields alias the input. */+/** Fresh node objects + `folders`/`requests` arrays; other fields alias the input. */export const ensureRefIds = (collection: HoppCollection): HoppCollection => ({...collection,_ref_id: collection._ref_id ?? generateUniqueRefId("coll"),+ // Exports strip request `_ref_id`s (stripRefIdReplacer) and schema parse+ // doesn't backfill them — stamp at import so tab↔request matching and+ // sync row identity work for imported requests+ requests: (collection.requests ?? []).map((request) => ({+ ...request,+ _ref_id: request._ref_id ?? generateUniqueRefId("req"),+ })),folders: (collection.folders ?? []).map(ensureRefIds),})diff --git a/packages/hoppscotch-common/src/helpers/collection/collection.ts b/packages/hoppscotch-common/src/helpers/collection/collection.tsindex 0e892631d..6810efd6a 100644--- a/packages/hoppscotch-common/src/helpers/collection/collection.ts+++ b/packages/hoppscotch-common/src/helpers/collection/collection.ts@@ -4,7 +4,7 @@ import { GetSingleRequestDocument } from "../backend/graphql"import { runGQLQuery } from "../backend/GQLClient"import * as E from "fp-ts/Either"import { getService } from "~/modules/dioc"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { GQLTabService } from "~/services/tab/graphql"import { TeamCollectionsService } from "~/services/team-collection.service"import { cascadeParentCollectionForProperties } from "~/newstore/collections"@@ -56,7 +56,7 @@ export function resolveSaveContextOnCollectionReorder(}}- const tabService = getService(RESTTabService)+ const tabService = getService(WorkspaceTabsService)const tabs = tabService.getTabsRefTo((tab) => {if (tab.document.type === "test-runner") return false@@ -116,7 +116,7 @@ export function updateSaveContextForAffectedRequests(oldFolderPath: string,newFolderPath: string | null) {- const tabService = getService(RESTTabService)+ const tabService = getService(WorkspaceTabsService)const tabs = tabService.getTabsRefTo((tab) => {if (tab.document.type === "test-runner") return false@@ -162,7 +162,9 @@ export function updateInheritedPropertiesForAffectedRequests(type: "rest" | "graphql") {const tabService =- type === "rest" ? getService(RESTTabService) : getService(GQLTabService)+ type === "rest"+ ? getService(WorkspaceTabsService)+ : getService(GQLTabService)const teamCollectionService = getService(TeamCollectionsService)const effectedTabs = tabService.getTabsRefTo((tab) => {@@ -215,7 +217,7 @@ export function updateInheritedPropertiesForAffectedRequests(}function resetSaveContextForAffectedRequests(folderPath: string) {- const tabService = getService(RESTTabService)+ const tabService = getService(WorkspaceTabsService)const tabs = tabService.getTabsRefTo((tab) => {if (tab.document.type === "test-runner") return falsereturn (@@ -235,6 +237,9 @@ function resetSaveContextForAffectedRequests(folderPath: string) {// remove inherited propertiestab.value.document.inheritedProperties = undefined+ } else if (tab.value.document.type === "gql-request") {+ // GQL requests have no saved responses; just drop inherited properties+ tab.value.document.inheritedProperties = undefined}}}@@ -244,7 +249,7 @@ function resetSaveContextForAffectedRequests(folderPath: string) {* only runs when collection or folder is deleted*/export async function resetTeamRequestsContext() {- const tabService = getService(RESTTabService)+ const tabService = getService(WorkspaceTabsService)const tabs = tabService.getTabsRefTo((tab) => {if (tab.document.type === "test-runner") return falsereturn tab.document.saveContext?.originLocation === "team-collection"@@ -268,6 +273,9 @@ export async function resetTeamRequestsContext() {// remove inherited propertiestab.value.document.inheritedProperties = undefined+ } else if (tab.value.document.type === "gql-request") {+ // GQL requests have no saved responses; just drop inherited properties+ tab.value.document.inheritedProperties = undefined}}}diff --git a/packages/hoppscotch-common/src/helpers/collection/request.ts b/packages/hoppscotch-common/src/helpers/collection/request.tsindex f99d74e75..a14707793 100644--- a/packages/hoppscotch-common/src/helpers/collection/request.ts+++ b/packages/hoppscotch-common/src/helpers/collection/request.ts@@ -2,10 +2,9 @@ import {HoppCollection,HoppGQLRequest,HoppRESTRequest,- RESTReqSchemaVersion,} from "@hoppscotch/data"import { getAffectedIndexes } from "./affectedIndex"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { getService } from "~/modules/dioc"/**@@ -38,7 +37,7 @@ export function resolveSaveContextOnRequestReorder(payload: {// if (newIndex === -1) remove it from the map because it will be deletedif (newIndex === -1) affectedIndexes.delete(lastIndex)- const tabService = getService(RESTTabService)+ const tabService = getService(WorkspaceTabsService)const tabs = tabService.getTabsRefTo((tab) => {return (tab.document.saveContext?.originLocation === "user-collection" &&@@ -60,27 +59,16 @@ export function resolveSaveContextOnRequestReorder(payload: {export function getRequestsByPath(collections: HoppCollection[],path: string-): HoppRESTRequest[] | HoppGQLRequest[] {+): (HoppRESTRequest | HoppGQLRequest)[] {// path will be like this "0/0/1" these are the indexes of the foldersconst pathArray = path.split("/").map((index) => parseInt(index))let currentCollection = collections[pathArray[0]]- if (pathArray.length === 1) {- const latestVersionedRequests = currentCollection.requests.filter(- (req): req is HoppRESTRequest => req.v === RESTReqSchemaVersion- )-- return latestVersionedRequests- }for (let i = 1; i < pathArray.length; i++) {const folder = currentCollection.folders[pathArray[i]]if (folder) currentCollection = folder}- const latestVersionedRequests = currentCollection.requests.filter(- (req): req is HoppRESTRequest => req.v === RESTReqSchemaVersion- )-- return latestVersionedRequests+ return currentCollection.requests as (HoppRESTRequest | HoppGQLRequest)[]}diff --git a/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.ts b/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.tsindex 89b3bbb51..2a773112c 100644--- a/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.ts+++ b/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.ts@@ -21,7 +21,7 @@ import {getSelectedEnvironmentType,} from "~/newstore/environments"import { SecretEnvironmentService } from "~/services/secret-environment.service"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { CurrentValueService } from "~/services/current-environment-value.service"import IconEdit from "~icons/lucide/edit?raw"@@ -59,7 +59,7 @@ const TOOLTIP_ENV_CONTAINER_Z_INDEX_CLASS = "!z-[1002]"const secretEnvironmentService = getService(SecretEnvironmentService)const currentEnvironmentValueService = getService(CurrentValueService)-const restTabs = getService(RESTTabService)+const workspaceTabs = getService(WorkspaceTabsService)const cursorTooltipField = (aggregateEnvs: AggregateEnvironment[]) =>hoverTooltip(@@ -226,9 +226,9 @@ const cursorTooltipField = (aggregateEnvs: AggregateEnvironment[]) =>if (tooltipEnv?.sourceEnv === "RequestVariable" &&- restTabs.currentActiveTab.value.document.type === "request"+ workspaceTabs.currentActiveTab.value.document.type === "request") {- restTabs.currentActiveTab.value.document.optionTabPreference =+ workspaceTabs.currentActiveTab.value.document.optionTabPreference ="requestVariables"} else {invokeAction(invokeActionType, {@@ -363,11 +363,32 @@ export class HoppEnvironmentPlugin {constructor(subscribeToStream: StreamSubscriberFunc,- private editorView: Ref<EditorView | undefined>+ private editorView: Ref<EditorView | undefined>,+ getScopedEnvs?: () => AggregateEnvironment[] | undefined) {+ // A scoped getter (embeds) replaces the live tab/store wiring entirely —+ // the viewer's stored environments must not highlight or resolve there.+ // Watched so scope changes (e.g. request-variable edits) re-render.+ if (getScopedEnvs) {+ watch(+ () => getScopedEnvs() ?? [],+ (envs) => {+ this.envs = envs+ this.editorView.value?.dispatch({+ effects: this.compartment.reconfigure([+ cursorTooltipField(this.envs),+ environmentHighlightStyle(this.envs),+ ]),+ })+ },+ { immediate: true, deep: true }+ )+ return+ }+// Watch the current active tab to update the variables accordinglywatch(- () => restTabs.currentActiveTab.value,+ () => workspaceTabs.currentActiveTab.value,(currentTab) => {const request =currentTab.document.type === "example-response"@@ -407,7 +428,7 @@ export class HoppEnvironmentPlugin {subscribeToStream(aggregateEnvsWithCurrentValue$, (envs) => {// Recompute request and collection variables from current tab to avoid stale closure values- const tab = restTabs.currentActiveTab.value+ const tab = workspaceTabs.currentActiveTab.valueconst request =tab.document.type === "example-response"? tab.document.response.originalRequestdiff --git a/packages/hoppscotch-common/src/helpers/fixBrokenRequestVersion.ts b/packages/hoppscotch-common/src/helpers/fixBrokenRequestVersion.tsindex 0145a7475..a1f0b1d3c 100644--- a/packages/hoppscotch-common/src/helpers/fixBrokenRequestVersion.ts+++ b/packages/hoppscotch-common/src/helpers/fixBrokenRequestVersion.ts@@ -1,11 +1,12 @@import {getDefaultRESTRequest,+ isGQLRequest,safelyExtractRESTRequest,} from "@hoppscotch/data"import { z } from "zod"-import { REST_TAB_STATE_SCHEMA } from "~/services/persistence/validation-schemas"+import { WORKSPACE_TABS_STATE_SCHEMA } from "~/services/persistence/validation-schemas"-type HoppRESTab = z.infer<typeof REST_TAB_STATE_SCHEMA>+type WorkspaceTabsState = z.infer<typeof WORKSPACE_TABS_STATE_SCHEMA>/*** Fixes broken request versions in the given REST tab documents.@@ -21,9 +22,9 @@ type HoppRESTab = z.infer<typeof REST_TAB_STATE_SCHEMA>* @returns The fixed ordered documents with valid request structures.*/export const fixBrokenRequestVersion = (- docs: HoppRESTab["orderedDocs"]-): HoppRESTab["orderedDocs"] => {- return docs.map((x: HoppRESTab["orderedDocs"][number]) => {+ docs: WorkspaceTabsState["orderedDocs"]+): WorkspaceTabsState["orderedDocs"] => {+ return docs.map((x: WorkspaceTabsState["orderedDocs"][number]) => {if (x.doc.type === "request") {const req = safelyExtractRESTRequest(x.doc.request,@@ -35,24 +36,25 @@ export const fixBrokenRequestVersion = (}if (x.doc.type === "test-runner") {- // Runner docs persist `request: null` deliberately. Resurrecting the- // null into a default request lets a runner doc with an invalid- // collection satisfy the tab-state union's request-tab branch and- // silently morph into a blank request tab — only sanitize a request- // that actually exists. A missing key is normalized to null: the tab- // schema accepts null but not undefined.- if (x.doc.request === null || x.doc.request === undefined) {- x.doc.request = null- } else {- x.doc.request = safelyExtractRESTRequest(- x.doc.request,- getDefaultRESTRequest()- )- }+ // `request` (the selected result row): keep null as null rather than+ // resurrecting a phantom default request, and repair only REST-shaped+ // selections — the tabs schema accepts both protocols, so GQL+ // selections pass through untouched like the result rows below.+ x.doc.request = !x.doc.request+ ? null+ : isGQLRequest(x.doc.request)+ ? x.doc.request+ : safelyExtractRESTRequest(x.doc.request, getDefaultRESTRequest())if (x.doc.resultCollection) {x.doc.resultCollection.requests = x.doc.resultCollection?.requests.map((req) => {+ // Unified runner collections mix REST and GQL rows. Coercing a+ // GQL request through `safelyExtractRESTRequest` would rebuild+ // it as a default REST request (no endpoint/method to copy),+ // silently destroying the row on every app restore — so GQL rows+ // pass through untouched and validate via their own schema.+ if (isGQLRequest(req)) return reqreturn safelyExtractRESTRequest(req, getDefaultRESTRequest())})diff --git a/packages/hoppscotch-common/src/helpers/graphql/__tests__/testRunner.spec.ts b/packages/hoppscotch-common/src/helpers/graphql/__tests__/testRunner.spec.tsnew file mode 100644index 000000000..53ee78a60--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/graphql/__tests__/testRunner.spec.ts@@ -0,0 +1,190 @@+import * as E from "fp-ts/Either"+import { afterEach, describe, expect, test, vi } from "vitest"++// ~/modules/i18n transitively imports the persistence service, which imports+// newstore/history, which subscribes to RequestRunner's executedResponses$ —+// a cycle that in test import order runs before RequestRunner finishes+// initializing. Stubbing i18n severs that edge; this spec never renders text.+vi.mock("~/modules/i18n", () => ({+ getI18n: () => (key: string) => key,+}))++import { runTestRunnerGQLRequest } from "~/helpers/graphql/testRunner"+import { getService } from "~/modules/dioc"+import { KernelInterceptorService } from "~/services/kernel-interceptor.service"++// The executor captures the interceptor service singleton at module load —+// spying on the same singleton's `execute` intercepts the outgoing kernel+// request without touching the network. Returning a cancellation keeps each+// run one-shot: the request is captured, then the executor short-circuits.+const interceptor = getService(KernelInterceptorService)++const captureExecutedRequest = () => {+ const spy = vi.spyOn(interceptor, "execute").mockImplementation(+ () =>+ ({+ cancel: () => {},+ response: Promise.resolve(E.left("cancellation")),+ }) as any+ )+ return spy+}++afterEach(() => {+ vi.restoreAllMocks()+})++const envVar = (key: string, value: string) => ({+ key,+ initialValue: value,+ currentValue: value,+ secret: false,+})++const makeEnvState = (selected: ReturnType<typeof envVar>[] = []) => ({+ initialGlobalEnvs: [],+ initialEnvID: "env-id",+ initialSelectedEnvs: selected,+ initialEnvironmentIndex: { type: "NO_ENV_SELECTED" as const },+ initialEnvName: "No environment",+ initialEnvs: { global: [], selected, temp: [] },+ initialEnvsForComparison: { global: [], selected },+})++// Scriptless request — the pre/post script stages short-circuit, so the run+// exercises only env resolution, auth, and the wire-request build.+const gqlRequest = (url: string, query: string) => ({+ v: 10 as const,+ name: "executor-under-test",+ _ref_id: "gql-exec-1",+ url,+ query,+ variables: "{}",+ headers: [],+ auth: { authType: "none" as const, authActive: false },+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",+})++describe("runTestRunnerGQLRequest — dataset iteration variables", () => {+ test("<<column>> resolves from iteration variables in URL and query", async () => {+ const spy = captureExecutedRequest()++ await runTestRunnerGQLRequest(+ gqlRequest(+ "https://<<host>>/graphql",+ "query { user(id: <<uid>>) { name } }"+ ) as any,+ true,+ [],+ makeEnvState() as any,+ [],+ [],+ [],+ [envVar("host", "rows.example.com"), envVar("uid", "42")]+ )++ expect(spy).toHaveBeenCalledTimes(1)+ const kernelRequest = spy.mock.calls[0][0] as any+ expect(kernelRequest.url).toBe("https://rows.example.com/graphql")+ expect(kernelRequest.content.content.query).toBe(+ "query { user(id: 42) { name } }"+ )+ })++ test("iteration values outrank collection variables of the same key", async () => {+ const spy = captureExecutedRequest()++ await runTestRunnerGQLRequest(+ gqlRequest(+ "https://api.example.com/graphql",+ "query { v(x: <<col>>) }"+ ) as any,+ true,+ [envVar("col", "from-collection")] as any,+ makeEnvState() as any,+ [],+ [],+ [],+ [envVar("col", "from-dataset-row")]+ )++ const kernelRequest = spy.mock.calls[0][0] as any+ expect(kernelRequest.content.content.query).toBe(+ "query { v(x: from-dataset-row) }"+ )+ })++ test("iteration values outrank selected-environment variables of the same key", async () => {+ const spy = captureExecutedRequest()++ await runTestRunnerGQLRequest(+ gqlRequest(+ "https://api.example.com/graphql",+ "query { v(x: <<col>>) }"+ ) as any,+ true,+ [],+ makeEnvState([envVar("col", "from-environment")]) as any,+ [],+ [],+ [],+ [envVar("col", "from-dataset-row")]+ )++ const kernelRequest = spy.mock.calls[0][0] as any+ expect(kernelRequest.content.content.query).toBe(+ "query { v(x: from-dataset-row) }"+ )+ })++ test("interceptor failures surface the invoked humanMessage heading, not the function", async () => {+ vi.spyOn(interceptor, "execute").mockImplementation(+ () =>+ ({+ cancel: () => {},+ response: Promise.resolve(+ E.left({+ humanMessage: { heading: () => "Interceptor exploded" },+ error: { message: "boom" },+ })+ ),+ }) as any+ )++ const result = await runTestRunnerGQLRequest(+ gqlRequest("https://api.example.com/graphql", "query { hello }") as any,+ true,+ [],+ makeEnvState() as any,+ [],+ [],+ []+ )++ expect(E.isLeft(result)).toBe(true)+ expect((result as any).left).toEqual({+ type: "request_fail",+ message: "Interceptor exploded",+ })+ })++ test("without iteration variables, environment resolution is unchanged", async () => {+ const spy = captureExecutedRequest()++ await runTestRunnerGQLRequest(+ gqlRequest("https://<<host>>/graphql", "query { hello }") as any,+ true,+ [],+ makeEnvState([envVar("host", "env.example.com")]) as any,+ [],+ [],+ []+ )++ const kernelRequest = spy.mock.calls[0][0] as any+ expect(kernelRequest.url).toBe("https://env.example.com/graphql")+ })+})diff --git a/packages/hoppscotch-common/src/helpers/graphql/connection.ts b/packages/hoppscotch-common/src/helpers/graphql/connection.tsindex 66b05120d..5377139d5 100644--- a/packages/hoppscotch-common/src/helpers/graphql/connection.ts+++ b/packages/hoppscotch-common/src/helpers/graphql/connection.ts@@ -81,10 +81,7 @@ export type GQLResponseEvent =}export type ConnectionState =- | "CONNECTING"- | "CONNECTED"- | "DISCONNECTED"- | "ERROR"+ "CONNECTING" | "CONNECTED" | "DISCONNECTED" | "ERROR"export type SubscriptionState = "SUBSCRIBING" | "SUBSCRIBED" | "UNSUBSCRIBED"const GQL = {@@ -112,8 +109,19 @@ type Connection = {} | null}-const tabs = getService(GQLTabService)-const currentTabID = computed(() => tabs.currentTabID.value)+/**+ * The current GQL tab ID for the legacy `/graphql` page, derived from the+ * single source of truth on `GQLTabService`. A computed (not a writable ref)+ * so it can't go stale or diverge: the page and its child request component+ * previously each wrote this from their own watch, which risked the+ * subscription-state map (keyed by this ID) reading the wrong slot.+ *+ * `getService` is resolved lazily inside the getter to avoid touching the DI+ * container at module-eval time.+ */+export const currentGQLTabID = computed(+ () => getService(GQLTabService).currentTabID.value+)export const connection = reactive<Connection>({state: "DISCONNECTED",@@ -125,7 +133,7 @@ export const connection = reactive<Connection>({export const schema = computed(() => connection.schema)export const subscriptionState = computed(() =>- connection.subscriptionState.get(currentTabID.value)+ connection.subscriptionState.get(currentGQLTabID.value))export const gqlMessageEvent = ref<GQLResponseEvent | "reset">()@@ -330,7 +338,17 @@ const getSchema = async (options: ConnectionRequestOptions) => {connection.error = null} catch (e: any) {console.error(e)- disconnect()++ // On an established connection this is a transient poll failure (server+ // blip, malformed introspection). Keep the last good schema and return so+ // `poll()` re-arms its timer and the next tick self-heals — tearing the+ // connection down here would blank the docs panes and stop polling for+ // the rest of the session, since poll()'s catch never re-arms.+ if (connection.state === "CONNECTED") return++ // Initial connect: there is no schema to fall back on, so surface the+ // failure and let poll() set ERROR rather than promoting a null schema.+ throw e}}@@ -410,13 +428,18 @@ export const runGQLOperation = async (options: RunQueryOptions) => {)const gqlRequest: HoppGQLRequest = {- v: 9,+ v: 10,name: options.name || "Untitled Request",url: finalUrl,headers: finalHoppHeaders,query,variables,auth: auth ?? request.auth,+ description: null,+ responses: {},+ // Wire-shape object only — scripts never ride the network request+ preRequestScript: "",+ testScript: "",}if (operationType === "subscription") {@@ -577,7 +600,7 @@ export const runSubscription = (const { url, query, operationName } = optionsconst wsUrl = url.replace(/^http/, "ws")- connection.subscriptionState.set(currentTabID.value, "SUBSCRIBING")+ connection.subscriptionState.set(currentGQLTabID.value, "SUBSCRIBING")connection.socket = new WebSocket(wsUrl, "graphql-ws")@@ -606,7 +629,7 @@ export const runSubscription = (const data = JSON.parse(event.data)switch (data.type) {case GQL.CONNECTION_ACK: {- connection.subscriptionState.set(currentTabID.value, "SUBSCRIBED")+ connection.subscriptionState.set(currentGQLTabID.value, "SUBSCRIBED")break}case GQL.CONNECTION_ERROR: {@@ -635,7 +658,7 @@ export const runSubscription = (connection.socket.onclose = (event) => {console.log("WebSocket is closed now.", event)- connection.subscriptionState.set(currentTabID.value, "UNSUBSCRIBED")+ connection.subscriptionState.set(currentGQLTabID.value, "UNSUBSCRIBED")}addQueryToHistory(options, "")@@ -658,6 +681,11 @@ const addQueryToHistory = (options: RunQueryOptions, response: string) => {headers: request.headers,variables,auth: request.auth as HoppGQLAuth,+ description: null,+ responses: {},+ // Snapshot scripts so reopening the history entry restores them+ preRequestScript: request.preRequestScript ?? "",+ testScript: request.testScript ?? "",}),response,star: false,diff --git a/packages/hoppscotch-common/src/helpers/graphql/default.ts b/packages/hoppscotch-common/src/helpers/graphql/default.tsindex 88d2321c5..0f3b3076e 100644--- a/packages/hoppscotch-common/src/helpers/graphql/default.ts+++ b/packages/hoppscotch-common/src/helpers/graphql/default.ts@@ -1,5 +1,9 @@import { parse, print } from "graphql"-import { HoppGQLRequest, GQL_REQ_SCHEMA_VERSION } from "@hoppscotch/data"+import {+ HoppGQLRequest,+ GQL_REQ_SCHEMA_VERSION,+ generateUniqueRefId,+} from "@hoppscotch/data"const DEFAULT_QUERY = print(parse(@@ -30,4 +34,9 @@ export const getDefaultGQLRequest = (): HoppGQLRequest => ({authType: "inherit",authActive: true,},+ _ref_id: generateUniqueRefId("req"),+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",})diff --git a/packages/hoppscotch-common/src/helpers/graphql/explorer.ts b/packages/hoppscotch-common/src/helpers/graphql/explorer.tsindex e2c78156c..b6dbff247 100644--- a/packages/hoppscotch-common/src/helpers/graphql/explorer.ts+++ b/packages/hoppscotch-common/src/helpers/graphql/explorer.ts@@ -24,9 +24,7 @@ import {* Can be a field, input field, or argument*/export type ExplorerFieldDef =- | GraphQLField<unknown, unknown, unknown>- | GraphQLInputField- | GraphQLArgument+ GraphQLField<unknown, unknown, unknown> | GraphQLInputField | GraphQLArgument/*** Represents a single item in the explorer navigation stackdiff --git a/packages/hoppscotch-common/src/helpers/graphql/index.ts b/packages/hoppscotch-common/src/helpers/graphql/index.tsindex 1ce9b9473..b57ce2cb9 100644--- a/packages/hoppscotch-common/src/helpers/graphql/index.ts+++ b/packages/hoppscotch-common/src/helpers/graphql/index.ts@@ -37,6 +37,11 @@ export const HoppGQLRequestEq = Eq.struct<HoppGQLRequest>({query: S.Eq,variables: S.Eq,auth: lodashIsEqualEq,+ responses: lodashIsEqualEq,+ preRequestScript: S.Eq,+ testScript: S.Eq,+ _ref_id: undefinedEq(S.Eq),+ description: lodashIsEqualEq,})export const isEqualHoppGQLRequest = HoppGQLRequestEq.equalsdiff --git a/packages/hoppscotch-common/src/helpers/graphql/testRunner.ts b/packages/hoppscotch-common/src/helpers/graphql/testRunner.tsnew file mode 100644index 000000000..baf6e5013--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/graphql/testRunner.ts@@ -0,0 +1,407 @@+import {+ Environment,+ GQLHeader,+ HoppCollectionVariable,+ HoppGQLRequest,+ HoppRESTAuth,+ HoppRESTRequest,+} from "@hoppscotch/data"+import * as E from "fp-ts/Either"+import { parse } from "graphql"+import type { OperationDefinitionNode } from "graphql"++import { getDefaultRESTRequest } from "~/helpers/rest/default"+import {+ InitialEnvironmentState,+ combineEnvVariables,+ delegatePreRequestScriptRunner,+ filterNonEmptyEnvironmentVariables,+ getTestableBody,+ hasEnvironmentChanges,+ runPostRequestScript,+ translateToSandboxTestResults,+ updateEnvsAfterTestScript,+} from "~/helpers/RequestRunner"+import { stripIterationVarsFromEnvs } from "~/helpers/runner/iteration-vars"+import {+ getTemporaryVariables,+ scriptEnvsToTemporaryVariables,+ setTemporaryVariables,+} from "~/helpers/runner/temp_envs"+import { HoppTestResult } from "~/helpers/types/HoppTestResult"+import { TestResult } from "@hoppscotch/js-sandbox"+import { getI18n } from "~/modules/i18n"+import { getEffectiveHoppGQLRequest } from "~/helpers/utils/EffectiveURL"+import {+ generateAuthHeaders,+ generateAuthParams,+} from "~/helpers/auth/auth-types"+import { GQLRequest } from "~/helpers/kernel/gql/request"+import { RESTResponse } from "~/helpers/kernel/rest/response"+import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"+import { KernelInterceptorService } from "~/services/kernel-interceptor.service"+import { getService } from "~/modules/dioc"++const kernelInterceptorService = getService(KernelInterceptorService)++export type GQLTestRunnerFailure =+ | { type: "subscription_unsupported" }+ | { type: "request_fail"; message: string }++/**+ * Picks the operation a collection-run should execute. Mirrors the tab+ * behaviour of defaulting to the first operation in the document — runs+ * don't have a cursor position to disambiguate with.+ */+const getRunnableOperation = (+ query: string+): E.Either<GQLTestRunnerFailure, OperationDefinitionNode | null> => {+ try {+ const ast = parse(query)+ const operations = ast.definitions.filter(+ (d): d is OperationDefinitionNode => d.kind === "OperationDefinition"+ )++ if (operations.length === 0) return E.right(null)++ const op = operations[0]+ if (op.operation === "subscription") {+ return E.left({ type: "subscription_unsupported" })+ }+ return E.right(op)+ } catch (_e) {+ // Let the server report the syntax error — it produces a real GraphQL+ // error response the user can read in the result panel, which beats a+ // client-side parse message.+ return E.right(null)+ }+}++/**+ * Executes a GraphQL request inside a collection run.+ *+ * The result is shaped as a `HoppRESTResponse`. For a run this is the honest+ * shape, not a coercion: a GraphQL-over-HTTP query/mutation is a single POST+ * returning a single HTTP response (status, headers, JSON body), and+ * `HoppRESTResponse` is the app's plain "HTTP response" type — so the runner+ * result tree, status chips, response lenses, run-meta accounting, and the+ * persistence schema all render it with zero protocol branches. The GQL+ * tab's `GQLResponseEvent[]` shape exists to model subscription event+ * streams, which runs skip — one-shot runs would carry that as dead weight+ * and force discrimination through every consumer.+ *+ * Known trade-off: GraphQL servers report operation errors as+ * `200 OK` + `{ errors: [...] }` in the body, so such rows chip green+ * (HTTP-level truth; REST rows behave the same for error payloads).+ * Surfacing body-level GraphQL errors on the row is a planned enhancement+ * in `runTestGQLRequest` — purely additive, no change to this shape.+ *+ * Mirrors `runTestRunnerRequest` including the script stages: the combined+ * (root → request) pre-request script mutates envs/headers before execution,+ * and the (request → root) test script runs against the HTTP response. The+ * sandbox is REST-shaped, so scripts see the GQL request as a synthetic POST.+ *+ * The `request` arrives with auth already resolved by the test-runner+ * service walk; inherited headers are passed separately so auth headers can+ * be applied between them and the request's own headers+ * (precedence: request > auth > inherited).+ */+export async function runTestRunnerGQLRequest(+ request: HoppGQLRequest,+ persistEnv = true,+ inheritedVariables: HoppCollectionVariable[] = [],+ initialEnvironmentState: InitialEnvironmentState,+ inheritedHeaders: GQLHeader[] = [],+ inheritedPreRequestScripts: string[] = [],+ inheritedTestScripts: string[] = [],+ iterationVars: Environment["variables"] = []+): Promise<+ E.Either<+ GQLTestRunnerFailure,+ { response: HoppRESTResponse; testResult: HoppTestResult }+ >+> {+ const {+ initialGlobalEnvs,+ initialEnvID,+ initialSelectedEnvs,+ initialEnvironmentIndex,+ initialEnvName,+ initialEnvs,+ initialEnvsForComparison,+ } = initialEnvironmentState++ const iterationVarKeys = new Set(iterationVars.map(({ key }) => key))+ // Injected into `selected` only — the sandbox env shape has no data scope;+ // template resolution gets the iteration values via the env list below.+ // Mirrors `runTestRunnerRequest`.+ const initialEnvsWithIterationData = {+ ...initialEnvs,+ selected: [...iterationVars, ...initialEnvs.selected],+ }+ const stripIterationVars = (envs: TestResult["envs"]): TestResult["envs"] =>+ stripIterationVarsFromEnvs(envs, iterationVarKeys, initialEnvs.selected)++ // --- Pre-request script stage --- (short-circuits when no script exists)+ const scriptSyntheticRequest: HoppRESTRequest = {+ ...getDefaultRESTRequest(),+ name: request.name,+ method: "POST",+ endpoint: request.url,+ headers: request.headers,+ auth: request.auth as HoppRESTAuth,+ preRequestScript: request.preRequestScript ?? "",+ testScript: request.testScript ?? "",+ }++ const preResult = await delegatePreRequestScriptRunner(+ scriptSyntheticRequest,+ initialEnvsWithIterationData,+ null,+ inheritedPreRequestScripts+ )+ if (E.isLeft(preResult)) {+ return E.left({+ type: "request_fail",+ message: `Pre-request script failed: ${preResult.left}`,+ })+ }++ // v1 request-mutation surface: headers only (hopp.request.setHeader) —+ // REST and GQL header shapes are structurally identical+ const scriptedRequest = preResult.right.updatedRequest?.headers+ ? { ...request, headers: preResult.right.updatedRequest.headers }+ : request++ const envVars = filterNonEmptyEnvironmentVariables([+ // Data-file iteration values take precedence over every other scope for+ // the duration of the iteration — REST parity (see runTestRunnerRequest):+ // prepend them once, then drop those keys from the combined scopes so+ // each appears exactly once and stays authoritative.+ ...iterationVars,+ ...combineEnvVariables({+ environments: {+ ...preResult.right.updatedEnvs,+ temp: !persistEnv ? getTemporaryVariables() : [],+ },+ // GraphQL requests have no request-level variables (REST-style+ // requestVariables) — collection variables are the innermost scope.+ requestVariables: [],+ collectionVariables: inheritedVariables as Environment["variables"],+ }).filter(({ key }) => !iterationVarKeys.has(key)),+ ]) as Environment["variables"]++ const effective = getEffectiveHoppGQLRequest(scriptedRequest, envVars, {+ inheritedHeaders,+ })++ // Detect on the env-resolved query — a templated document (e.g. the whole+ // query in a `<<doc>>` variable) only reveals its operations after+ // substitution.+ const operationResult = getRunnableOperation(effective.effectiveFinalQuery)+ if (E.isLeft(operationResult)) return operationResult+ const operation = operationResult.right++ // Synthetic REST request for auth signing and the response viewer's `req`+ // field. Truthful for GraphQL-over-HTTP: a POST to the resolved URL.+ // Signing-sensitive auth types (AWS, digest, HAWK) hash exactly this+ // method + URL pair.+ const syntheticRESTRequest: HoppRESTRequest = {+ ...getDefaultRESTRequest(),+ name: request.name,+ method: "POST",+ endpoint: effective.effectiveFinalURL,+ }++ // GQL auth is a structural subset of REST auth for the shared types, and+ // collection-inherited auth can legitimately be a REST-only type (digest,+ // HAWK, JWT…) — the REST generators handle the full union, so GraphQL+ // requests get complete auth coverage in runs.+ const effectiveAuth = effective.effectiveFinalAuth as HoppRESTAuth++ const authHeaders = effectiveAuth.authActive+ ? await generateAuthHeaders(effectiveAuth, syntheticRESTRequest, envVars)+ : []+ const authParams = effectiveAuth.authActive+ ? await generateAuthParams(effectiveAuth, syntheticRESTRequest, envVars)+ : []++ let finalUrl = effective.effectiveFinalURL+ if (authParams.length > 0) {+ try {+ const urlObj = new URL(finalUrl)+ for (const param of authParams) {+ urlObj.searchParams.append(param.key, param.value)+ }+ finalUrl = urlObj.toString()+ } catch (_e) {+ // Unparseable URL — let the network layer surface the real error.+ }+ }++ // Precedence: request > auth > inherited (same as the tab execution path).+ const finalHeaders: Record<string, string> = {}+ effective.effectiveFinalHeaders.forEach((h) => {+ finalHeaders[h.key] = h.value+ })+ authHeaders.forEach((h) => {+ finalHeaders[h.key] = h.value+ })+ effective.effectiveFinalRequestHeaders.forEach((h) => {+ finalHeaders[h.key] = h.value+ })++ const gqlRequest: HoppGQLRequest = {+ v: 10,+ name: request.name,+ url: finalUrl,+ headers: Object.entries(finalHeaders).map(([key, value]) => ({+ active: true,+ key,+ value,+ description: "",+ })),+ query: effective.effectiveFinalQuery,+ variables: effective.effectiveFinalVariables,+ auth: effective.effectiveFinalAuth,+ description: null,+ responses: {},+ // Wire-shape object only — scripts never ride the network request+ preRequestScript: "",+ testScript: "",+ }++ try {+ const kernelRequest = await GQLRequest.toRequest(gqlRequest)++ // Multi-operation documents need an explicit operationName — match the+ // tab behaviour of running the first operation.+ if (operation?.name?.value && kernelRequest.content?.kind === "json") {+ const jsonContent = kernelRequest.content.content as Record<+ string,+ unknown+ >+ jsonContent.operationName = operation.name.value+ }++ const { response } = kernelInterceptorService.execute(kernelRequest)+ const result = await response++ if (E.isLeft(result)) {+ // `humanMessage.heading` is a translator-taking function, not a string+ const message =+ result.left === "cancellation"+ ? "Request cancelled"+ : (result.left.humanMessage?.heading?.(getI18n()) ??+ result.left.error?.message ??+ "Request execution failed")+ return E.left({ type: "request_fail", message })+ }++ const parsedResponse = await RESTResponse.toResponse(+ result.right,+ syntheticRESTRequest+ )++ if (parsedResponse.type === "fail") {+ return E.left({+ type: "request_fail",+ message: parsedResponse.error.message,+ })+ }++ // --- Post-request (test) script stage --- (short-circuits when empty)+ // Test scripts observe the executed request (resolved URL, final wire+ // headers), mirroring REST runs+ const executedScriptRequest: HoppRESTRequest = {+ ...scriptSyntheticRequest,+ endpoint: finalUrl,+ headers: gqlRequest.headers,+ }+ const postResult = await runPostRequestScript(+ preResult.right.updatedEnvs,+ executedScriptRequest,+ {+ status: parsedResponse.statusCode,+ body: getTestableBody(parsedResponse),+ headers: parsedResponse.headers,+ statusText: parsedResponse.statusText,+ responseTime: parsedResponse.meta.responseDuration,+ // Runtime contract is TestResponse — the param annotation says+ // HoppRESTResponse but every call site passes this shape+ } as never,+ preResult.right.updatedCookies ?? null,+ inheritedTestScripts+ )++ if (E.isLeft(postResult)) {+ console.error("[Post-Request Script Error]", postResult.left)+ return E.right({+ response: parsedResponse,+ testResult: {+ description: "",+ expectResults: [],+ tests: [],+ envDiff: {+ global: { additions: [], deletions: [], updations: [] },+ selected: { additions: [], deletions: [], updations: [] },+ },+ scriptError: true,+ consoleEntries: [],+ },+ })+ }++ // Iteration values are injected into the environment for the duration of+ // the request only; strip them back out so a data run never persists+ // data-file columns as environment variables — REST parity+ const filteredPostResult = {+ ...postResult.right,+ envs: stripIterationVars(postResult.right.envs),+ }++ const combinedResult = {+ ...filteredPostResult,+ consoleEntries: [+ ...(preResult.right.consoleEntries ?? []),+ ...(postResult.right.consoleEntries ?? []),+ ],+ }++ const testResult = translateToSandboxTestResults(+ combinedResult,+ initialGlobalEnvs,+ initialSelectedEnvs+ )++ // Persist env mutations after the test script (or stash them as+ // temporary variables when keepVariableValues is off) — REST parity+ if (persistEnv) {+ if (+ hasEnvironmentChanges(initialEnvsForComparison, filteredPostResult.envs)+ ) {+ updateEnvsAfterTestScript(+ filteredPostResult.envs,+ initialEnvironmentIndex,+ initialEnvName,+ initialEnvsForComparison,+ initialEnvID+ )+ }+ } else {+ // `selected` before `global` — the temp store dedupes+ // first-occurrence-wins, and the selected scope must shadow global+ setTemporaryVariables(+ scriptEnvsToTemporaryVariables(filteredPostResult.envs)+ )+ }++ return E.right({ response: parsedResponse, testResult })+ } catch (error) {+ return E.left({+ type: "request_fail",+ message:+ error instanceof Error ? error.message : "Request execution failed",+ })+ }+}diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/__tests__/runnerResults.spec.ts b/packages/hoppscotch-common/src/helpers/import-export/export/__tests__/runnerResults.spec.tsindex f04457da6..c4a243b71 100644--- a/packages/hoppscotch-common/src/helpers/import-export/export/__tests__/runnerResults.spec.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/export/__tests__/runnerResults.spec.ts@@ -1,6 +1,6 @@import { describe, expect, test } from "vitest"-import { HoppTestRunnerDocument } from "~/helpers/rest/document"+import { HoppTestRunnerDocument } from "~/helpers/tab/document"import { buildRunnerResultReport } from "../runnerResults"// Minimal document fixture: a single iteration with one request whose response@@ -105,6 +105,28 @@ describe("buildRunnerResultReport", () => {expect(exported?.durationInMs).toBe(42)})+ test("GQL rows export their wire shape (POST + url) instead of dropping the keys", () => {+ const document = makeDocument("success")+ const gqlRow = {+ name: "gql-row",+ url: "https://example.com/graphql",+ query: "query { hello }",+ passedTests: 1,+ failedTests: 0,+ error: undefined,+ testResults: null,+ response: null,+ }+ ;(document.iterationResults![0].resultCollection as any).requests = [gqlRow]++ const report = buildRunnerResultReport(document, "all", "none")+ const exported = report.iterationResults[0].requests[0]++ expect(exported.name).toBe("gql-row")+ expect(exported.method).toBe("POST")+ expect(exported.endpoint).toBe("https://example.com/graphql")+ })+test("derives a failed outcome from an errored assertion (no plain failures)", () => {const request = {name: "req",diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/openapi.ts b/packages/hoppscotch-common/src/helpers/import-export/export/openapi.tsindex f19f5e280..4fa0af71b 100644--- a/packages/hoppscotch-common/src/helpers/import-export/export/openapi.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/export/openapi.ts@@ -1,6 +1,8 @@import {HoppCollection,+ HoppGQLRequest,HoppRESTRequest,+ isGQLRequest,makeCollection,parseRawKeyValueEntries,rawKeyValueEntriesToString,@@ -849,6 +851,9 @@ export function hoppCollectionToOpenAPI(collection: HoppCollection): {const variableValues = buildVariableValues(inheritedVariables)const secretKeys = collectSecretKeys(inheritedVariables)for (const request of requests) {+ // GQL requests have no OpenAPI representation — skip instead of+ // failing the whole export on a missing endpoint/method+ if (isGQLRequest(request as HoppRESTRequest | HoppGQLRequest)) continueconst {server,path: rawPath,diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/runnerResults.ts b/packages/hoppscotch-common/src/helpers/import-export/export/runnerResults.tsindex b952c8be6..2f8aea3fb 100644--- a/packages/hoppscotch-common/src/helpers/import-export/export/runnerResults.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/export/runnerResults.ts@@ -4,7 +4,8 @@ import {HoppTestRunnerDocument,TestRunnerIterationResult,TestRunnerMeta,-} from "~/helpers/rest/document"+} from "~/helpers/tab/document"+import { isRESTRequest } from "~/helpers/request-type"import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"import { HoppTestData, HoppTestResult } from "~/helpers/types/HoppTestResult"import { TestRunnerRequest } from "~/services/test-runner/test-runner.service"@@ -203,8 +204,11 @@ const exportRequest = (bodyMode: RunnerBodyMode): ExportedRequest => ({name: request.name,- method: request.method,- endpoint: request.endpoint,+ // Unified runs hold both protocols. A GraphQL row has no method/endpoint —+ // report its wire truth (a single POST to its url) instead of silently+ // dropping the keys from the JSON.+ method: isRESTRequest(request) ? request.method : "POST",+ endpoint: isRESTRequest(request) ? request.endpoint : request.url,passedTests: request.passedTests,failedTests: request.failedTests,error: request.error,diff --git a/packages/hoppscotch-common/src/helpers/import-export/import/hopp.ts b/packages/hoppscotch-common/src/helpers/import-export/import/hopp.tsindex 4168f8eb1..0f0004d75 100644--- a/packages/hoppscotch-common/src/helpers/import-export/import/hopp.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/import/hopp.ts@@ -3,9 +3,9 @@ import {HoppRESTRequest,getDefaultGQLRequest,getDefaultRESTRequest,- translateToNewRESTCollection,+ isGQLRequest,+ translateToNewCollection,HoppGQLRequest,- translateToNewGQLCollection,} from "@hoppscotch/data"import * as A from "fp-ts/Array"import * as O from "fp-ts/Option"@@ -43,9 +43,20 @@ const validateCollection = (collection: unknown) => {(request) => {const requestSchemaParsedResult = HoppRESTRequest.safeParse(request)- return requestSchemaParsedResult.type === "ok"- ? requestSchemaParsedResult.value- : getDefaultRESTRequest()+ if (requestSchemaParsedResult.type === "ok") {+ return requestSchemaParsedResult.value+ }++ // Unified collections hold mixed types — keep GQL requests as GQL+ // instead of clobbering them into a default REST request+ if (isGQLRequest(request as HoppRESTRequest | HoppGQLRequest)) {+ const gqlParsedResult = HoppGQLRequest.safeParse(request)+ return gqlParsedResult.type === "ok"+ ? gqlParsedResult.value+ : getDefaultGQLRequest()+ }++ return getDefaultRESTRequest()})@@ -55,7 +66,7 @@ const validateCollection = (collection: unknown) => {})}- return O.some(translateToNewRESTCollection(collection))+ return O.some(translateToNewCollection(collection))}/**@@ -91,9 +102,17 @@ export const validateGQLCollection = (collection: unknown) => {(request) => {const requestSchemaParsedResult = HoppGQLRequest.safeParse(request)- return requestSchemaParsedResult.type === "ok"- ? requestSchemaParsedResult.value- : getDefaultGQLRequest()+ if (requestSchemaParsedResult.type === "ok") {+ return requestSchemaParsedResult.value+ }++ // Mirror of the REST importer above — keep REST requests as REST+ if (!isGQLRequest(request as HoppRESTRequest | HoppGQLRequest)) {+ const restParsedResult = HoppRESTRequest.safeParse(request)+ if (restParsedResult.type === "ok") return restParsedResult.value+ }++ return getDefaultGQLRequest()})@@ -103,5 +122,5 @@ export const validateGQLCollection = (collection: unknown) => {})}- return O.some(translateToNewGQLCollection(collection))+ return O.some(translateToNewCollection(collection))}diff --git a/packages/hoppscotch-common/src/helpers/import-export/import/index.ts b/packages/hoppscotch-common/src/helpers/import-export/import/index.tsindex 2783d1503..454b8ef71 100644--- a/packages/hoppscotch-common/src/helpers/import-export/import/index.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/import/index.ts@@ -5,7 +5,7 @@ import {HoppCollection,generateUniqueRefId,makeCollection,- translateToNewRESTCollection,+ translateToNewCollection,} from "@hoppscotch/data"/**@@ -88,7 +88,7 @@ export const sanitizeCollection = (_ref_id: _refId,v: _v,...rest- } = translateToNewRESTCollection(collection)+ } = translateToNewCollection(collection)return makeCollection({...rest,diff --git a/packages/hoppscotch-common/src/helpers/import-export/import/insomnia/types.ts b/packages/hoppscotch-common/src/helpers/import-export/import/insomnia/types.tsindex 99fb54741..7798c2f77 100644--- a/packages/hoppscotch-common/src/helpers/import-export/import/insomnia/types.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/import/insomnia/types.ts@@ -64,9 +64,7 @@ export type InsomniaDocV5 = {description?: string}collection: (- | InsomniaFolderV5- | InsomniaRequestResource- | InsomniaScriptOnlyV5+ InsomniaFolderV5 | InsomniaRequestResource | InsomniaScriptOnlyV5)[]cookieJar?: InsomniaCookieJarV5environments?: InsomniaEnvironmentV5diff --git a/packages/hoppscotch-common/src/helpers/import-export/import/openapi/example-generators/v3.ts b/packages/hoppscotch-common/src/helpers/import-export/import/openapi/example-generators/v3.tsindex 3953306ff..776ec0190 100644--- a/packages/hoppscotch-common/src/helpers/import-export/import/openapi/example-generators/v3.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/import/openapi/example-generators/v3.ts@@ -3,8 +3,7 @@ import { pipe } from "fp-ts/function"import * as O from "fp-ts/Option"type SchemaType =- | OpenAPIV3.ArraySchemaObjectType- | OpenAPIV3.NonArraySchemaObjectType+ OpenAPIV3.ArraySchemaObjectType | OpenAPIV3.NonArraySchemaObjectTypetype PrimitiveSchemaType = Exclude<SchemaType, "array" | "object">diff --git a/packages/hoppscotch-common/src/helpers/import-export/import/openapi/example-generators/v31.ts b/packages/hoppscotch-common/src/helpers/import-export/import/openapi/example-generators/v31.tsindex 82fcea824..e2f96e0e8 100644--- a/packages/hoppscotch-common/src/helpers/import-export/import/openapi/example-generators/v31.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/import/openapi/example-generators/v31.ts@@ -4,8 +4,7 @@ import * as O from "fp-ts/Option"import * as A from "fp-ts/Array"type MixedArraySchemaType = (- | OpenAPIV31.ArraySchemaObjectType- | OpenAPIV31.NonArraySchemaObjectType+ OpenAPIV31.ArraySchemaObjectType | OpenAPIV31.NonArraySchemaObjectType)[]type SchemaType =diff --git a/packages/hoppscotch-common/src/helpers/import-export/import/openapi/index.ts b/packages/hoppscotch-common/src/helpers/import-export/import/openapi/index.tsindex 390b9d508..dc332e059 100644--- a/packages/hoppscotch-common/src/helpers/import-export/import/openapi/index.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/import/openapi/index.ts@@ -271,14 +271,11 @@ const parseOpenAPIV3Responses = (for (const [key, value] of Object.entries(responses)) {const response = value as- | OpenAPIV3.ResponseObject- | OpenAPIV31.ResponseObject+ OpenAPIV3.ResponseObject | OpenAPIV31.ResponseObjectconst contentType = Object.keys(response.content ?? {})[0]const mediaObject = response.content?.[contentType] as- | OpenAPIV3.MediaTypeObject- | OpenAPIV31.MediaTypeObject- | undefined+ OpenAPIV3.MediaTypeObject | OpenAPIV31.MediaTypeObject | undefinedconst name = response.description ?? key@@ -559,9 +556,7 @@ const parseOpenAPIV3BodyFormData = (mediaObj: OpenAPIV3.MediaTypeObject | OpenAPIV31.MediaTypeObject): HoppRESTReqBody => {const schema = mediaObj.schema as- | OpenAPIV3.SchemaObject- | OpenAPIV31.SchemaObject- | undefined+ OpenAPIV3.SchemaObject | OpenAPIV31.SchemaObject | undefinedif (!schema || schema.type !== "object") {return contentType === "application/x-www-form-urlencoded"@@ -613,9 +608,7 @@ const parseOpenAPIV3Body = (const objs = Object.entries((op.requestBody as- | OpenAPIV3.RequestBodyObject- | OpenAPIV31.RequestBodyObject- | undefined+ OpenAPIV3.RequestBodyObject | OpenAPIV31.RequestBodyObject | undefined)?.content ?? {})@@ -716,8 +709,8 @@ const parseOpenAPIV3Body = (const isOpenAPIV3Operation = (doc: OpenAPI.Document,- op: OpenAPIOperationType-): op is OpenAPIV3.OperationObject | OpenAPIV31.OperationObject =>+ _op: OpenAPIOperationType+): _op is OpenAPIV3.OperationObject | OpenAPIV31.OperationObject =>objectHasProperty(doc, "openapi") &&typeof doc.openapi === "string" &&doc.openapi.startsWith("3.")@@ -889,8 +882,7 @@ const resolveOpenAPIV3SecurityScheme = (schemeData: string[]): HoppRESTAuth => {const scheme = doc.components?.securitySchemes?.[schemeName] as- | OpenAPIV3.SecuritySchemeObject- | undefined+ OpenAPIV3.SecuritySchemeObject | undefinedif (!scheme) return { authType: "none", authActive: true }return resolveOpenAPIV3SecurityObj(scheme, schemeData)diff --git a/packages/hoppscotch-common/src/helpers/kernel/__tests__/kernel.spec.ts b/packages/hoppscotch-common/src/helpers/kernel/__tests__/kernel.spec.tsindex 3e3c10958..9d6b77c2f 100644--- a/packages/hoppscotch-common/src/helpers/kernel/__tests__/kernel.spec.ts+++ b/packages/hoppscotch-common/src/helpers/kernel/__tests__/kernel.spec.ts@@ -136,13 +136,17 @@ describe("GraphQL Response Transformation", () => {describe("GraphQL Request Transformation", () => {const baseRequest: HoppGQLRequest = {- v: 9,+ v: 10,name: "Test Query",url: "https://api.example.com/graphql",headers: [],query: "",variables: "",auth: { authType: "none", authActive: true },+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",}it("transforms a basic GraphQL request correctly", async () => {diff --git a/packages/hoppscotch-common/src/helpers/kernel/common/auth.ts b/packages/hoppscotch-common/src/helpers/kernel/common/auth.tsindex dd6861796..750939d91 100644--- a/packages/hoppscotch-common/src/helpers/kernel/common/auth.ts+++ b/packages/hoppscotch-common/src/helpers/kernel/common/auth.ts@@ -177,53 +177,45 @@ const Processors: {O.alt(() =>pipe(Guards.grants.authCode(g),- O.map(- (g): GrantType => ({- kind: "authorization_code",- authEndpoint: g.authEndpoint,- tokenEndpoint: g.tokenEndpoint,- clientId: g.clientID,- clientSecret: g.clientSecret,- })- )+ O.map((g): GrantType => ({+ kind: "authorization_code",+ authEndpoint: g.authEndpoint,+ tokenEndpoint: g.tokenEndpoint,+ clientId: g.clientID,+ clientSecret: g.clientSecret,+ })))),O.alt(() =>pipe(Guards.grants.clientCreds(g),- O.map(- (g): GrantType => ({- kind: "client_credentials",- tokenEndpoint: g.authEndpoint,- clientId: g.clientID,- clientSecret: g.clientSecret,- })- )+ O.map((g): GrantType => ({+ kind: "client_credentials",+ tokenEndpoint: g.authEndpoint,+ clientId: g.clientID,+ clientSecret: g.clientSecret,+ })))),O.alt(() =>pipe(Guards.grants.password(g),- O.map(- (g): GrantType => ({- kind: "password",- tokenEndpoint: g.authEndpoint,- username: g.username,- password: g.password,- })- )+ O.map((g): GrantType => ({+ kind: "password",+ tokenEndpoint: g.authEndpoint,+ username: g.username,+ password: g.password,+ })))),O.alt(() =>pipe(Guards.grants.implicit(g),- O.map(- (g): GrantType => ({- kind: "implicit",- authEndpoint: g.authEndpoint,- clientId: g.clientID,- })- )+ O.map((g): GrantType => ({+ kind: "implicit",+ authEndpoint: g.authEndpoint,+ clientId: g.clientID,+ }))))),diff --git a/packages/hoppscotch-common/src/helpers/kernel/gql/response.ts b/packages/hoppscotch-common/src/helpers/kernel/gql/response.tsindex e194a273d..8a01724f3 100644--- a/packages/hoppscotch-common/src/helpers/kernel/gql/response.ts+++ b/packages/hoppscotch-common/src/helpers/kernel/gql/response.ts@@ -27,13 +27,6 @@ type GQLParsedResponse = {errors?: Array<{ message: string }>}-const determineOperationType = (query: string): OperationType => {- const trimmed = query.trim().toLowerCase()- if (trimmed.startsWith("mutation")) return "mutation"- if (trimmed.startsWith("subscription")) return "subscription"- return "query"-}-const createTransformError = (message: string): GQLTransformError => ({type: "error",error: {@@ -75,7 +68,10 @@ export const GQLResponse = {? response.meta.timing.end - response.meta.timing.start: 0,operationName: options.operationName,- operationType: determineOperationType(options.query),+ // The run's actual operation — `options.query` is the whole+ // editor document, whose first keyword can belong to a+ // different operation in a multi-operation document+ operationType: options.operationType,data: JSON.stringify(validBody, null, 2),rawQuery: options,}diff --git a/packages/hoppscotch-common/src/helpers/network.ts b/packages/hoppscotch-common/src/helpers/network.tsindex 64df67ee5..31b6dc6ab 100644--- a/packages/hoppscotch-common/src/helpers/network.ts+++ b/packages/hoppscotch-common/src/helpers/network.ts@@ -13,7 +13,13 @@ export type NetworkStrategy = () => TE.TaskEither<RelayError, HoppRESTResponse>export function createRESTNetworkRequestStream(- request: EffectiveHoppRESTRequest+ request: EffectiveHoppRESTRequest,+ streamOptions?: {+ // Opts the request out of the shared cookie jar at the interceptor+ // level (`meta.options.cookies: false`) — isolated embed runs must not+ // ride the viewer's cookies even on cookie-enabled platforms (desktop)+ noCookieJar?: boolean+ }): [Observable<HoppRESTResponse>, () => void] {const response = new BehaviorSubject<HoppRESTResponse>({type: "loading",@@ -23,6 +29,12 @@ export function createRESTNetworkRequestStream(const req = cloneDeep(request)const execResult = RESTRequest.toRequest(req).then((kernelRequest) => {+ if (kernelRequest && streamOptions?.noCookieJar) {+ kernelRequest.meta = {+ ...kernelRequest.meta,+ options: { ...kernelRequest.meta?.options, cookies: false },+ }+ }if (!kernelRequest) {response.next({type: "network_fail",diff --git a/packages/hoppscotch-common/src/helpers/realtime/SIOClients.ts b/packages/hoppscotch-common/src/helpers/realtime/SIOClients.tsindex abb4b059d..1b624a9fa 100644--- a/packages/hoppscotch-common/src/helpers/realtime/SIOClients.ts+++ b/packages/hoppscotch-common/src/helpers/realtime/SIOClients.ts@@ -11,12 +11,7 @@ type Options = {}type PossibleEvent =- | "connect"- | "connect_error"- | "reconnect_error"- | "error"- | "disconnect"- | "*"+ "connect" | "connect_error" | "reconnect_error" | "error" | "disconnect" | "*"export interface SIOClient {connect(url: string, opts?: Options): voiddiff --git a/packages/hoppscotch-common/src/helpers/request-type.ts b/packages/hoppscotch-common/src/helpers/request-type.tsnew file mode 100644index 000000000..3cd427f5c--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/request-type.ts@@ -0,0 +1,124 @@+import {+ HoppGQLRequest,+ HoppGQLResponseOriginalRequest,+ HoppRESTRequest,+ HoppRESTResponseOriginalRequest,+} from "@hoppscotch/data"++type AnyRequest =+ | HoppRESTRequest+ | HoppRESTResponseOriginalRequest+ | HoppGQLRequest+ | HoppGQLResponseOriginalRequest++/**+ * The `in` operator throws on `null`/primitives, so every shape guard below+ * has to establish "is a non-null object" before probing for keys — callers+ * feed these raw persisted and imported JSON.+ */+const isRequestObject = (req: AnyRequest): req is AnyRequest =>+ !!req && typeof req === "object"++/**+ * Type guard to check if a request object is GraphQL-shaped.+ * GQL requests / saved example original-requests have `query` + `url` but not+ * `endpoint`. Predicate kept aligned with `isGQLRequest` in+ * `@hoppscotch/data/collection` (this one admits the example+ * original-request variants, hence the wider signature).+ */+export function isGQLRequest(+ req: AnyRequest+): req is HoppGQLRequest | HoppGQLResponseOriginalRequest {+ // Object check first — callers pass raw persisted/imported JSON, and the+ // `in` operator throws on primitives+ return (+ isRequestObject(req) &&+ "url" in req &&+ "query" in req &&+ !("endpoint" in req)+ )+}++/**+ * Type guard to check if a request object is REST-shaped.+ */+export function isRESTRequest(+ req: AnyRequest+): req is HoppRESTRequest | HoppRESTResponseOriginalRequest {+ return isRequestObject(req) && "endpoint" in req+}++/**+ * Returns true if the request has an active auth config that carries a+ * credential (token, password, secret key, etc.). Used by the share flow to+ * warn users before publishing a shortcode whose payload would expose their+ * credentials to anyone with the link.+ *+ * Errs on the side of "yes": when in doubt about an unknown auth type, we+ * treat it as carrying a secret so the user is shown the warning.+ */+export function requestHasSharedSecrets(+ req: HoppRESTRequest | HoppGQLRequest+): boolean {+ const auth = req.auth as+ | undefined+ | (Record<string, unknown> & { authActive?: boolean; authType?: string })+ if (!auth?.authActive) return false++ const nonEmpty = (v: unknown) => typeof v === "string" && v.length > 0++ switch (auth.authType) {+ case "none":+ case "inherit":+ return false++ case "basic":+ return nonEmpty(auth.username) || nonEmpty(auth.password)++ case "bearer":+ return nonEmpty(auth.token)++ case "oauth-2": {+ const info = auth.grantTypeInfo as Record<string, unknown> | undefined+ return (+ nonEmpty(info?.token) ||+ nonEmpty(info?.clientSecret) ||+ nonEmpty(info?.password) ||+ nonEmpty(info?.refreshToken)+ )+ }++ case "api-key":+ return nonEmpty(auth.key) || nonEmpty(auth.value)++ case "aws-signature":+ return (+ nonEmpty(auth.accessKey) ||+ nonEmpty(auth.secretKey) ||+ nonEmpty(auth.serviceToken)+ )++ case "digest":+ return nonEmpty(auth.username) || nonEmpty(auth.password)++ case "hawk":+ return nonEmpty(auth.authKeyId) || nonEmpty(auth.authKey)++ case "jwt":+ return nonEmpty(auth.secret) || nonEmpty(auth.privateKey)++ case "akamai-eg":+ return (+ nonEmpty(auth.accessToken) ||+ nonEmpty(auth.clientSecret) ||+ nonEmpty(auth.clientToken)+ )++ case "asap":+ return nonEmpty(auth.privateKey)++ default:+ // Unknown / future auth type — warn rather than silently leak.+ return true+ }+}diff --git a/packages/hoppscotch-common/src/helpers/runner/collection-tree.ts b/packages/hoppscotch-common/src/helpers/runner/collection-tree.tsindex 57102cd1b..e2e3a3372 100644--- a/packages/hoppscotch-common/src/helpers/runner/collection-tree.ts+++ b/packages/hoppscotch-common/src/helpers/runner/collection-tree.ts@@ -35,6 +35,7 @@ export const getErrorMessage = (case "team_req/requests_not_from_same_collection":return t("request.different_collection")case "team/team_collections_have_different_parents":+ case "team_coll/not_same_parent":return t("collection.different_parent")default:return t("error.something_went_wrong")diff --git a/packages/hoppscotch-common/src/helpers/runner/selection.ts b/packages/hoppscotch-common/src/helpers/runner/selection.tsindex 8139e3d0a..addab99ff 100644--- a/packages/hoppscotch-common/src/helpers/runner/selection.ts+++ b/packages/hoppscotch-common/src/helpers/runner/selection.ts@@ -1,7 +1,11 @@-import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data"+import {+ HoppCollection,+ HoppGQLRequest,+ HoppRESTRequest,+} from "@hoppscotch/data"export const getRequestSelectionID = (- request: HoppRESTRequest,+ request: HoppRESTRequest | HoppGQLRequest,path: number[]) => request._ref_id || `path:${path.join("/")}`diff --git a/packages/hoppscotch-common/src/helpers/rest/document.ts b/packages/hoppscotch-common/src/helpers/tab/document.tssimilarity index 73%rename from packages/hoppscotch-common/src/helpers/rest/document.tsrename to packages/hoppscotch-common/src/helpers/tab/document.tsindex 8558934de..fdf9f3955 100644--- a/packages/hoppscotch-common/src/helpers/rest/document.ts+++ b/packages/hoppscotch-common/src/helpers/tab/document.ts@@ -1,16 +1,20 @@import {HoppCollection,+ HoppGQLRequest,+ HoppGQLRequestResponse,HoppRESTRequest,HoppRESTRequestResponse,} from "@hoppscotch/data"import { RESTOptionTabs } from "~/components/http/RequestOptions.vue"+import { GQLOptionTabs } from "~/components/graphql/RequestOptions.vue"+import { type GQLResponseEvent } from "~/services/gql-tab-connection.service"import { HoppInheritedProperty } from "../types/HoppInheritedProperties"import { HoppRESTResponse } from "../types/HoppRESTResponse"import { HoppTestResult } from "../types/HoppTestResult"import { TestRunnerRequest } from "~/services/test-runner/test-runner.service"import { TestRunnerDataset } from "../runner/dataset"-export type HoppRESTSaveContext =+export type HoppTabSaveContext =| {/*** The origin source of the request@@ -244,7 +248,7 @@ export type HoppRequestDocument = {* Info about where this request should be saved.* This contains where the request is originated from basically.*/- saveContext?: HoppRESTSaveContext+ saveContext?: HoppTabSaveContext/*** The response as it is in the document@@ -295,7 +299,7 @@ export type HoppSavedExampleDocument = {* Info about where this response should be saved.* This contains where the response is originated from basically.*/- saveContext?: HoppRESTSaveContext+ saveContext?: HoppTabSaveContext/*** Whether the response has any unsaved changes@@ -310,10 +314,102 @@ export type HoppSavedExampleDocument = {inheritedProperties?: HoppInheritedProperty}+export type HoppSavedGQLExampleDocument = {+ /**+ * The type of the document+ */+ type: "gql-example-response"++ /**+ * The response as it is in the document.+ * Carries the GQL example shape (with a GQL `originalRequest` snapshot) so+ * the renderer can reuse the GQL request/response surfaces.+ */+ response: HoppGQLRequestResponse++ /**+ * Info about where this response should be saved.+ * This contains where the response is originated from basically.+ */+ saveContext?: HoppTabSaveContext++ /**+ * Whether the response has any unsaved changes+ * (atleast as far as we can say)+ */+ isDirty: boolean++ /**+ * The inherited properties from the parent collection+ * (if any)+ */+ inheritedProperties?: HoppInheritedProperty+}++export type HoppGQLRequestDocument = {+ /**+ * The document type+ */+ type: "gql-request"++ /**+ * The GQL request as it is in the document+ */+ request: HoppGQLRequest++ /**+ * Whether the request has any unsaved changes+ * (atleast as far as we can say)+ */+ isDirty: boolean++ /**+ * The cursor position in the query editor+ */+ cursorPosition?: number++ /**+ * Info about where this request should be saved.+ * This contains where the request is originated from basically.+ */+ saveContext?: HoppTabSaveContext++ /**+ * The response as it is in the document+ * (if any)+ */+ response?: GQLResponseEvent[] | null++ /**+ * The test script results of the last query/mutation run (if any).+ * `null` while a run is in flight — the Results tab renders its loading+ * state off that sentinel (GQL has no `loading` response type like REST).+ */+ testResults?: HoppTestResult | null++ /**+ * Response tab preference for the current tab's document+ */+ responseTabPreference?: string++ /**+ * Options tab preference for the current tab's document+ */+ optionTabPreference?: GQLOptionTabs++ /**+ * The inherited properties from the parent collection+ * (if any)+ */+ inheritedProperties?: HoppInheritedProperty+}+/*** Defines a live 'document' (something that is open and being edited) in the app*/export type HoppTabDocument =| HoppSavedExampleDocument+ | HoppSavedGQLExampleDocument| HoppRequestDocument| HoppTestRunnerDocument+ | HoppGQLRequestDocumentdiff --git a/packages/hoppscotch-common/src/helpers/tab/type-converter.ts b/packages/hoppscotch-common/src/helpers/tab/type-converter.tsnew file mode 100644index 000000000..4c806c997--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/tab/type-converter.ts@@ -0,0 +1,171 @@+import {+ HoppGQLRequest,+ HoppRESTRequest,+ GQL_REQ_SCHEMA_VERSION,+ RESTReqSchemaVersion,+ generateUniqueRefId,+ getDefaultGQLRequest,+ getDefaultRESTRequest,+} from "@hoppscotch/data"+import {+ HoppRequestDocument,+ HoppGQLRequestDocument,+} from "~/helpers/tab/document"+import type { ProtocolDraft } from "~/services/tab"++/**+ * Re-stamps a restored protocol draft with the live request's identity.+ *+ * Drafts are snapshots from the previous switch, so their `id`/`_ref_id` go+ * stale — the request may have been saved (gaining an id) or repointed by a+ * "Save as" since. Restoring verbatim either duplicates the backend row or+ * overwrites another collection's request. Content stays the draft's.+ */+const restoreDraftIdentity = <T extends { id?: string; _ref_id?: string }>(+ draft: T,+ source: { id?: string; _ref_id?: string }+): T => {+ const restored: T = {+ ...draft,+ _ref_id: source._ref_id ?? draft._ref_id ?? generateUniqueRefId("req"),+ }++ if (source.id) restored.id = source.id+ else delete restored.id++ return restored+}++/**+ * Converts a REST request document to a GQL request document.+ *+ * A `gqlDraft` (kept by the protocol switcher for round-trip preservation)+ * restores its content, with identity re-stamped via `restoreDraftIdentity`.+ * Otherwise the GQL request is seeded from the REST one: name, headers and+ * compatible auth carry over; URL, query and variables fall back to defaults.+ */+export function convertRESTToGQL(+ doc: HoppRequestDocument,+ gqlDraft?: ProtocolDraft<HoppGQLRequest>+): HoppGQLRequestDocument {+ const restReq = doc.request++ // Map shared auth types (GQL supports a subset of REST auth types)+ const gqlCompatibleAuthTypes = [+ "none",+ "inherit",+ "basic",+ "bearer",+ "oauth-2",+ "api-key",+ "aws-signature",+ ]++ const auth = gqlCompatibleAuthTypes.includes(restReq.auth.authType)+ ? (restReq.auth as HoppGQLRequest["auth"])+ : { authType: "inherit" as const, authActive: true }++ const defaultGQL = getDefaultGQLRequest()++ const gqlRequest: HoppGQLRequest = gqlDraft+ ? restoreDraftIdentity(gqlDraft.request, restReq)+ : {+ v: GQL_REQ_SCHEMA_VERSION,+ _ref_id: restReq._ref_id ?? generateUniqueRefId("req"),+ // Preserve the backend id so sync can issue `editUserRequest` against+ // the existing row — `editRequest` reads `request.id` to find it+ ...(restReq.id ? { id: restReq.id } : {}),+ name: restReq.name,+ // A REST path isn't a GraphQL endpoint; the real URL comes back via+ // the `gqlDraft` branch above+ url: defaultGQL.url,+ headers: restReq.headers.map((h) => ({+ key: h.key,+ value: h.value,+ active: h.active,+ description: h.description,+ })),+ query: defaultGQL.query,+ variables: defaultGQL.variables,+ auth,+ description: restReq.description ?? null,+ responses: {},+ // Scripts are protocol-agnostic — carry them instead of dropping code+ preRequestScript: restReq.preRequestScript,+ testScript: restReq.testScript,+ }++ return {+ type: "gql-request",+ request: gqlRequest,+ // A fresh conversion diverges from the saved entry, so it's dirty. A+ // restored draft carries the flag it was snapshotted with — round-tripping+ // a saved request back to its original shape leaves it clean+ isDirty: gqlDraft?.isDirty ?? true,+ cursorPosition: 0,+ saveContext: doc.saveContext,+ response: null,+ optionTabPreference: "query",+ inheritedProperties: doc.inheritedProperties,+ }+}++/**+ * Converts a GQL request document to a REST request document.+ *+ * Mirror of `convertRESTToGQL`: a `restDraft` restores its content with+ * identity re-stamped, otherwise the REST request is seeded from the GQL one.+ */+export function convertGQLToREST(+ doc: HoppGQLRequestDocument,+ restDraft?: ProtocolDraft<HoppRESTRequest>+): HoppRequestDocument {+ const gqlReq = doc.request++ const defaultREST = getDefaultRESTRequest()++ const restRequest: HoppRESTRequest = restDraft+ ? restoreDraftIdentity(restDraft.request, gqlReq)+ : {+ v: RESTReqSchemaVersion,+ _ref_id: gqlReq._ref_id ?? generateUniqueRefId("req"),+ // Mirror of `convertRESTToGQL` — preserve the backend id for sync+ ...(gqlReq.id ? { id: gqlReq.id } : {}),+ name: gqlReq.name,+ // Cross-protocol URLs aren't interchangeable; the real endpoint comes+ // back via the `restDraft` branch+ endpoint: defaultREST.endpoint,+ method: "GET",+ params: [],+ headers: gqlReq.headers.map((h) => ({+ key: h.key,+ value: h.value,+ active: h.active,+ description: h.description,+ })),+ // Scripts are protocol-agnostic — carry them instead of dropping code+ preRequestScript: gqlReq.preRequestScript ?? "",+ testScript: gqlReq.testScript ?? "",+ body: {+ contentType: null,+ body: null,+ },+ // Safe cast: every GQL auth variant is a REST one. The reverse needs+ // the guard above because REST has auth types GQL lacks+ auth: gqlReq.auth as HoppRESTRequest["auth"],+ requestVariables: [],+ responses: {},+ description: gqlReq.description ?? "",+ }++ return {+ type: "request",+ request: restRequest,+ // Same reasoning as `convertRESTToGQL`+ isDirty: restDraft?.isDirty ?? true,+ saveContext: doc.saveContext,+ response: null,+ optionTabPreference: "params",+ inheritedProperties: doc.inheritedProperties,+ }+}diff --git a/packages/hoppscotch-common/src/helpers/teams/TeamCollection.ts b/packages/hoppscotch-common/src/helpers/teams/TeamCollection.tsindex 5665cfdff..16b7f860c 100644--- a/packages/hoppscotch-common/src/helpers/teams/TeamCollection.ts+++ b/packages/hoppscotch-common/src/helpers/teams/TeamCollection.ts@@ -6,7 +6,7 @@ import {import { TeamRequest } from "./TeamRequest"/**- * Defines how a Team Collection is represented in the TeamCollectionAdapter+ * Defines how a Team Collection is represented in the team-collection service.*/export interface TeamCollection {id: stringdiff --git a/packages/hoppscotch-common/src/helpers/teams/TeamCollectionAdapter.ts b/packages/hoppscotch-common/src/helpers/teams/TeamCollectionAdapter.tsdeleted file mode 100644index 94ff86993..000000000--- a/packages/hoppscotch-common/src/helpers/teams/TeamCollectionAdapter.ts+++ /dev/null@@ -1,1215 +0,0 @@-import * as E from "fp-ts/Either"-import { BehaviorSubject, Subscription } from "rxjs"-import { HoppCollectionVariable, translateToNewRequest } from "@hoppscotch/data"-import { pull, remove } from "lodash-es"-import { hasActualScript } from "@hoppscotch/js-sandbox/scripting"-import { CollectionDataProps } from "~/helpers/backend/helpers"-import { Subscription as WSubscription } from "wonka"-import { runGQLQuery, runGQLSubscription } from "../backend/GQLClient"-import { TeamCollection } from "./TeamCollection"-import { TeamRequest } from "./TeamRequest"-import {- RootCollectionsOfTeamDocument,- TeamCollectionAddedDocument,- TeamCollectionUpdatedDocument,- TeamCollectionRemovedDocument,- TeamRequestAddedDocument,- TeamRequestUpdatedDocument,- TeamRequestDeletedDocument,- GetCollectionChildrenDocument,- GetCollectionRequestsDocument,- TeamRequestMovedDocument,- TeamCollectionMovedDocument,- TeamRequestOrderUpdatedDocument,- TeamCollectionOrderUpdatedDocument,-} from "~/helpers/backend/graphql"-import { HoppInheritedProperty } from "../types/HoppInheritedProperties"-import { SecretEnvironmentService } from "~/services/secret-environment.service"-import { CurrentValueService } from "~/services/current-environment-value.service"-import { getService } from "~/modules/dioc"--export const TEAMS_BACKEND_PAGE_SIZE = 10--/**- * Finds the parent of a collection and returns the REFERENCE (or null)- *- * @param {TeamCollection[]} tree - The tree to look in- * @param {string} collID - ID of the collection to find the parent of- * @param {TeamCollection} currentParent - (used for recursion, do not set) The parent in the current iteration (undefined if root)- *- * @returns REFERENCE to the collection or null if not found or the collection is in root- */-function findParentOfColl(- tree: TeamCollection[],- collID: string,- currentParent?: TeamCollection-): TeamCollection | null {- for (const coll of tree) {- // If the root is parent, return null- if (coll.id === collID) return currentParent || null-- // Else run it in children- if (coll.children) {- const result = findParentOfColl(coll.children, collID, coll)- if (result) return result- }- }-- return null-}--/**- * Finds and returns a REFERENCE collection in the given tree (or null)- *- * @param {TeamCollection[]} tree - The tree to look in- * @param {string} targetID - The ID of the collection to look for- *- * @returns REFERENCE to the collection or null if not found- */-function findCollInTree(- tree: TeamCollection[],- targetID: string-): TeamCollection | null {- for (const coll of tree) {- // If the direct child matched, then return that- if (coll.id === targetID) return coll-- // Else run it in the children- if (coll.children) {- const result = findCollInTree(coll.children, targetID)- if (result) return result- }- }-- // If nothing matched, return null- return null-}--/**- * Deletes a collection in the tree- *- * @param {TeamCollection[]} tree - The tree to delete in (THIS WILL BE MUTATED!)- * @param {string} targetID - ID of the collection to delete- */-function deleteCollInTree(tree: TeamCollection[], targetID: string) {- // Get the parent owning the collection- const parent = findParentOfColl(tree, targetID)-- // If we found a parent, update it- if (parent && parent.children) {- parent.children = parent.children.filter((coll) => coll.id !== targetID)- }-- // If there is no parent, it could mean:- // 1. The collection with that ID does not exist- // 2. The collection is in root (therefore, no parent)-- // Let's look for element, if not exist, then stop- const el = findCollInTree(tree, targetID)- if (!el) return-- // Collection exists, so this should be in root, hence removing element- pull(tree, el)-}--/**- * Updates a collection in the tree with the specified data- *- * @param {TeamCollection[]} tree - The tree to update in (THIS WILL BE MUTATED!)- * @param {Partial<TeamCollection> & Pick<TeamCollection, "id">} updateColl - An object defining all the fields that should be updated (ID is required to find the target collection)- */-function updateCollInTree(- tree: TeamCollection[],- updateColl: Partial<TeamCollection> & Pick<TeamCollection, "id">-) {- const el = findCollInTree(tree, updateColl.id)-- // If no match, stop the operation- if (!el) return-- // Update all the specified keys- Object.assign(el, updateColl)-}--/**- * Finds and returns a REFERENCE to the request with the given ID (or null)- *- * @param {TeamCollection[]} tree - The tree to look in- * @param {string} reqID - The ID of the request to look for- *- * @returns REFERENCE to the request or null if request not found- */-function findReqInTree(- tree: TeamCollection[],- reqID: string-): TeamRequest | null {- for (const coll of tree) {- // Check in root collections (if expanded)- if (coll.requests) {- const match = coll.requests.find((req) => req.id === reqID)- if (match) return match- }-- // Check in children of collections- if (coll.children) {- const match = findReqInTree(coll.children, reqID)- if (match) return match- }- }-- // No matches- return null-}--/**- * Finds and returns a REFERENCE to the collection containing a given request ID in tree (or null)- *- * @param {TeamCollection[]} tree - The tree to look in- * @param {string} reqID - The ID of the request to look for- *- * @returns REFERENCE to the collection or null if request not found- */-function findCollWithReqIDInTree(- tree: TeamCollection[],- reqID: string-): TeamCollection | null {- for (const coll of tree) {- // Check in root collections (if expanded)- if (coll.requests) {- if (coll.requests.find((req) => req.id === reqID)) return coll- }-- // Check in children of collections- if (coll.children) {- const result = findCollWithReqIDInTree(coll.children, reqID)- if (result) return result- }- }-- // No matches- return null-}--type EntityType = "request" | "collection"-type EntityID = `${EntityType}-${string}`--export default class NewTeamCollectionAdapter {- collections$: BehaviorSubject<TeamCollection[]>-- // Stream to the list of collections/folders that are being loaded in- loadingCollections$: BehaviorSubject<string[]>-- /**- * Stores the entity (collection/request/folder) ids of all the loaded entities.- * Used for preventing duplication of data which definitely is not possible (duplication due to network problems etc.)- */- private entityIDs: Set<EntityID>-- private teamCollectionAdded$: Subscription | null- private teamCollectionUpdated$: Subscription | null- private teamCollectionRemoved$: Subscription | null- private teamRequestAdded$: Subscription | null- private teamRequestUpdated$: Subscription | null- private teamRequestDeleted$: Subscription | null- private teamRequestMoved$: Subscription | null- private teamCollectionMoved$: Subscription | null- private teamRequestOrderUpdated$: Subscription | null- private teamCollectionOrderUpdated$: Subscription | null-- private teamCollectionAddedSub: WSubscription | null- private teamCollectionUpdatedSub: WSubscription | null- private teamCollectionRemovedSub: WSubscription | null- private teamRequestAddedSub: WSubscription | null- private teamRequestUpdatedSub: WSubscription | null- private teamRequestDeletedSub: WSubscription | null- private teamRequestMovedSub: WSubscription | null- private teamCollectionMovedSub: WSubscription | null- private teamRequestOrderUpdatedSub: WSubscription | null- private teamCollectionOrderUpdatedSub: WSubscription | null-- //collection variables current value and secret value- private secretEnvironmentService = getService(SecretEnvironmentService)- private currentEnvironmentValueService = getService(CurrentValueService)-- constructor(private teamID: string | null) {- this.collections$ = new BehaviorSubject<TeamCollection[]>([])- this.loadingCollections$ = new BehaviorSubject<string[]>([])-- this.entityIDs = new Set()-- this.teamCollectionAdded$ = null- this.teamCollectionUpdated$ = null- this.teamCollectionRemoved$ = null- this.teamRequestAdded$ = null- this.teamRequestDeleted$ = null- this.teamRequestUpdated$ = null- this.teamRequestMoved$ = null- this.teamCollectionMoved$ = null- this.teamRequestOrderUpdated$ = null- this.teamCollectionOrderUpdated$ = null-- this.teamCollectionAddedSub = null- this.teamCollectionUpdatedSub = null- this.teamCollectionRemovedSub = null- this.teamRequestAddedSub = null- this.teamRequestDeletedSub = null- this.teamRequestUpdatedSub = null- this.teamRequestMovedSub = null- this.teamCollectionMovedSub = null- this.teamRequestOrderUpdatedSub = null- this.teamCollectionOrderUpdatedSub = null-- if (this.teamID) this.initialize()- }-- changeTeamID(newTeamID: string | null) {- this.teamID = newTeamID- this.collections$.next([])- this.entityIDs.clear()-- this.loadingCollections$.next([])-- this.unsubscribeSubscriptions()-- if (this.teamID) this.initialize()- }-- /**- * Unsubscribes from the subscriptions- * NOTE: Once this is called, no new updates to the tree will be detected- */- unsubscribeSubscriptions() {- this.teamCollectionAdded$?.unsubscribe()- this.teamCollectionUpdated$?.unsubscribe()- this.teamCollectionRemoved$?.unsubscribe()- this.teamRequestAdded$?.unsubscribe()- this.teamRequestDeleted$?.unsubscribe()- this.teamRequestUpdated$?.unsubscribe()- this.teamRequestMoved$?.unsubscribe()- this.teamCollectionMoved$?.unsubscribe()- this.teamRequestOrderUpdated$?.unsubscribe()- this.teamCollectionOrderUpdated$?.unsubscribe()-- this.teamCollectionAddedSub?.unsubscribe()- this.teamCollectionUpdatedSub?.unsubscribe()- this.teamCollectionRemovedSub?.unsubscribe()- this.teamRequestAddedSub?.unsubscribe()- this.teamRequestDeletedSub?.unsubscribe()- this.teamRequestUpdatedSub?.unsubscribe()- this.teamRequestMovedSub?.unsubscribe()- this.teamCollectionMovedSub?.unsubscribe()- this.teamRequestOrderUpdatedSub?.unsubscribe()- this.teamCollectionOrderUpdatedSub?.unsubscribe()- }-- private async initialize() {- await this.loadRootCollections()- this.registerSubscriptions()- }-- /**- * Performs addition of a collection to the tree- *- * @param {TeamCollection} collection - The collection to add to the tree- * @param {string | null} parentCollectionID - The parent of the new collection, pass null if this collection is in root- */- private addCollection(- collection: TeamCollection,- parentCollectionID: string | null- ) {- // Check if we have it already in the entity tree, if so, we don't need it again- if (this.entityIDs.has(`collection-${collection.id}`)) return-- const tree = this.collections$.value-- if (!parentCollectionID) {- tree.push(collection)- } else {- const parentCollection = findCollInTree(tree, parentCollectionID)-- if (!parentCollection) return-- // Prevent adding child collections to a collection that has not been expanded yet incoming from GQL subscription, during import, etc- // Hence, add entries to the pre-existing list without setting 'children' if it is `null'- if (parentCollection.children !== null) {- parentCollection.children.push(collection)- }- }-- // Add to entity ids set- this.entityIDs.add(`collection-${collection.id}`)-- this.collections$.next(tree)- }-- private async loadRootCollections() {- if (this.teamID === null) throw new Error("Team ID is null")-- this.loadingCollections$.next([- ...this.loadingCollections$.getValue(),- "root",- ])-- const totalCollections: TeamCollection[] = []-- while (true) {- const result = await runGQLQuery({- query: RootCollectionsOfTeamDocument,- variables: {- teamID: this.teamID,- cursor:- totalCollections.length > 0- ? totalCollections[totalCollections.length - 1].id- : undefined,- },- })-- if (E.isLeft(result)) {- this.loadingCollections$.next(- this.loadingCollections$.getValue().filter((x) => x !== "root")- )-- throw new Error(`Error fetching root collections: ${result.left.error}`)- }-- totalCollections.push(- ...result.right.rootCollectionsOfTeam.map(- (x) =>- <TeamCollection>{- ...x,- children: null,- requests: null,- }- )- )-- if (result.right.rootCollectionsOfTeam.length !== TEAMS_BACKEND_PAGE_SIZE)- break- }-- this.loadingCollections$.next(- this.loadingCollections$.getValue().filter((x) => x !== "root")- )-- // Add all the collections to the entity ids list- totalCollections.forEach((coll) =>- this.entityIDs.add(`collection-${coll.id}`)- )-- this.collections$.next(totalCollections)- }-- /**- * Updates an existing collection in tree- *- * @param {Partial<TeamCollection> & Pick<TeamCollection, "id">} collectionUpdate - Object defining the fields that need to be updated (ID is required to find the target)- */- private updateCollection(- collectionUpdate: Partial<TeamCollection> & Pick<TeamCollection, "id">- ) {- const tree = this.collections$.value-- updateCollInTree(tree, collectionUpdate)-- this.collections$.next(tree)- }-- /**- * Removes a collection from the tree- *- * @param {string} collectionID - ID of the collection to remove- */- private removeCollection(collectionID: string) {- const tree = this.collections$.value-- deleteCollInTree(tree, collectionID)-- this.entityIDs.delete(`collection-${collectionID}`)-- this.collections$.next(tree)- }-- /**- * Adds a request to the tree- *- * @param {TeamRequest} request - The request to add to the tree- */- private addRequest(request: TeamRequest) {- // Check if we have it already in the entity tree, if so, we don't need it again- if (this.entityIDs.has(`request-${request.id}`)) return-- const tree = this.collections$.value-- // Check if we have the collection (if not, then not loaded?)- const coll = findCollInTree(tree, request.collectionID)- if (!coll) return // Ignore add request-- // Collection is not expanded- if (!coll.requests) return-- // Collection is expanded hence append request- coll.requests.push(request)-- // Update the Entity IDs list- this.entityIDs.add(`request-${request.id}`)-- this.collections$.next(tree)- }-- /**- * Updates the request in tree- *- * @param {Partial<TeamRequest> & Pick<TeamRequest, 'id'>} requestUpdate - Object defining all the fields to update in request (ID of the request is required)- */- private updateRequest(- requestUpdate: Partial<TeamRequest> & Pick<TeamRequest, "id">- ) {- const tree = this.collections$.value-- // Find request, if not present, don't update- const req = findReqInTree(tree, requestUpdate.id)- if (!req) return-- Object.assign(req, requestUpdate)-- this.collections$.next(tree)- }-- /**- * Removes a request from the tree- *- * @param {string} requestID - ID of the request to remove- */- private removeRequest(requestID: string) {- const tree = this.collections$.value-- // Find request in tree, don't attempt if no collection or no requests (expansion?)- const coll = findCollWithReqIDInTree(tree, requestID)- if (!coll || !coll.requests) return-- // Remove the collection- remove(coll.requests, (req) => req.id === requestID)-- // Remove from entityIDs set- this.entityIDs.delete(`request-${requestID}`)-- // Publish new tree- this.collections$.next(tree)- }-- /**- * Moves a request from one collection to another- *- * @param {string} request - The request to move- */- private async moveRequest(request: TeamRequest) {- const tree = this.collections$.value-- // Remove the request from the current collection- this.removeRequest(request.id)-- const currentRequest = request.request-- if (currentRequest === null || currentRequest === undefined) return-- // Find request in tree, don't attempt if no collection or no requests is found- const collection = findCollInTree(tree, request.collectionID)- if (!collection) return // Ignore add request-- // Collection is not expanded- if (!collection.requests) return-- this.addRequest({- id: request.id,- collectionID: request.collectionID,- request: translateToNewRequest(request.request),- title: request.title,- })- }-- /**- * Moves a collection from one collection to another or to root- *- * @param {string} collectionID - The ID of the collection to move- */- private async moveCollection(- collectionID: string,- parentID: string | null,- title: string,- data?: string | null- ) {- // Remove the collection from the current position- this.removeCollection(collectionID)-- if (collectionID === null || parentID === undefined) return-- // Expand the parent collection if it is not expanded- // so that the old children is also visible when expanding- if (parentID) this.expandCollection(parentID)-- this.addCollection(- {- id: collectionID,- children: null,- requests: null,- title: title,- data,- },- parentID ?? null- )- }-- private reorderItems = (array: unknown[], from: number, to: number) => {- const item = array.splice(from, 1)[0]- if (from < to) {- array.splice(to - 1, 0, item)- } else {- array.splice(to, 0, item)- }- }-- public updateRequestOrder(- dragedRequestID: string,- destinationRequestID: string | null,- destinationCollectionID: string- ) {- const tree = this.collections$.value-- // If the destination request is null, then it is the last request in the collection- if (destinationRequestID === null) {- const collection = findCollInTree(tree, destinationCollectionID)-- if (!collection) return // Ignore order update-- // Collection is not expanded- if (!collection.requests) return-- const requestIndex = collection.requests.findIndex(- (req) => req.id === dragedRequestID- )-- // If the collection index is not found, don't update- if (requestIndex === -1) return-- // Move the request to the end of the requests- collection.requests.push(collection.requests.splice(requestIndex, 1)[0])- } else {- // Find collection in tree, don't attempt if no collection is found- const collection = findCollInTree(tree, destinationCollectionID)- if (!collection) return // Ignore order update-- // Collection is not expanded- if (!collection.requests) return-- const requestIndex = collection.requests.findIndex(- (req) => req.id === dragedRequestID- )- const destinationIndex = collection.requests.findIndex(- (req) => req.id === destinationRequestID- )-- if (requestIndex === -1) return-- this.reorderItems(collection.requests, requestIndex, destinationIndex)- }-- this.collections$.next(tree)- }-- public updateCollectionOrder = (- collectionID: string,- destinationCollectionID: string | null- ) => {- const tree = this.collections$.value-- // If the destination collection is null, then it is the last collection in the tree- if (destinationCollectionID === null) {- const collLast = findParentOfColl(tree, collectionID)- if (collLast && collLast.children) {- const collectionIndex = collLast.children.findIndex(- (coll) => coll.id === collectionID- )-- // reorder the collection to the end of the collections- collLast.children.push(collLast.children.splice(collectionIndex, 1)[0])- } else {- const collectionIndex = tree.findIndex(- (coll) => coll.id === collectionID- )-- // If the collection index is not found, don't update- if (collectionIndex === -1) return-- // reorder the collection to the end of the collections in the root- tree.push(tree.splice(collectionIndex, 1)[0])- }- } else {- // Find collection in tree- const coll = findParentOfColl(tree, destinationCollectionID)-- // If the collection has a parent collection and check if it has children- if (coll && coll.children) {- const collectionIndex = coll.children.findIndex(- (coll) => coll.id === collectionID- )-- const destinationIndex = coll.children.findIndex(- (coll) => coll.id === destinationCollectionID- )-- // If the collection index is not found, don't update- if (collectionIndex === -1) return-- this.reorderItems(coll.children, collectionIndex, destinationIndex)- } else {- // If the collection has no parent collection, it is a root collection- const collectionIndex = tree.findIndex(- (coll) => coll.id === collectionID- )-- const destinationIndex = tree.findIndex(- (coll) => coll.id === destinationCollectionID- )-- // If the collection index is not found, don't update- if (collectionIndex === -1) return-- this.reorderItems(tree, collectionIndex, destinationIndex)- }- }-- this.collections$.next(tree)- }-- private registerSubscriptions() {- if (!this.teamID) return-- const [teamCollAdded$, teamCollAddedSub] = runGQLSubscription({- query: TeamCollectionAddedDocument,- variables: {- teamID: this.teamID,- },- })-- this.teamCollectionAddedSub = teamCollAddedSub-- this.teamCollectionAdded$ = teamCollAdded$.subscribe((result) => {- if (E.isLeft(result))- throw new Error(- `Team Collection Added Error: ${JSON.stringify(result.left)}`- )-- this.addCollection(- {- id: result.right.teamCollectionAdded.id,- children: null,- requests: null,- title: result.right.teamCollectionAdded.title,- data: result.right.teamCollectionAdded.data ?? null,- },- result.right.teamCollectionAdded.parent?.id ?? null- )- })-- const [teamCollUpdated$, teamCollUpdatedSub] = runGQLSubscription({- query: TeamCollectionUpdatedDocument,- variables: {- teamID: this.teamID,- },- })-- this.teamCollectionUpdatedSub = teamCollUpdatedSub- this.teamCollectionUpdated$ = teamCollUpdated$.subscribe((result) => {- if (E.isLeft(result))- throw new Error(- `Team Collection Updated Error: ${JSON.stringify(result.left)}`- )-- this.updateCollection({- id: result.right.teamCollectionUpdated.id,- title: result.right.teamCollectionUpdated.title,- data: result.right.teamCollectionUpdated.data,- })- })-- const [teamCollRemoved$, teamCollRemovedSub] = runGQLSubscription({- query: TeamCollectionRemovedDocument,- variables: {- teamID: this.teamID,- },- })-- this.teamCollectionRemovedSub = teamCollRemovedSub- this.teamCollectionRemoved$ = teamCollRemoved$.subscribe((result) => {- if (E.isLeft(result))- throw new Error(- `Team Collection Removed Error: ${JSON.stringify(result.left)}`- )-- this.removeCollection(result.right.teamCollectionRemoved)- })-- const [teamReqAdded$, teamReqAddedSub] = runGQLSubscription({- query: TeamRequestAddedDocument,- variables: {- teamID: this.teamID,- },- })-- this.teamRequestAddedSub = teamReqAddedSub- this.teamRequestAdded$ = teamReqAdded$.subscribe((result) => {- if (E.isLeft(result))- throw new Error(- `Team Request Added Error: ${JSON.stringify(result.left)}`- )-- this.addRequest({- id: result.right.teamRequestAdded.id,- collectionID: result.right.teamRequestAdded.collectionID,- request: translateToNewRequest(- JSON.parse(result.right.teamRequestAdded.request)- ),- title: result.right.teamRequestAdded.title,- })- })-- const [teamReqUpdated$, teamReqUpdatedSub] = runGQLSubscription({- query: TeamRequestUpdatedDocument,- variables: {- teamID: this.teamID,- },- })-- this.teamRequestUpdatedSub = teamReqUpdatedSub- this.teamRequestUpdated$ = teamReqUpdated$.subscribe((result) => {- if (E.isLeft(result))- throw new Error(- `Team Request Updated Error: ${JSON.stringify(result.left)}`- )-- this.updateRequest({- id: result.right.teamRequestUpdated.id,- collectionID: result.right.teamRequestUpdated.collectionID,- request: JSON.parse(result.right.teamRequestUpdated.request),- title: result.right.teamRequestUpdated.title,- })- })-- const [teamReqDeleted$, teamReqDeleted] = runGQLSubscription({- query: TeamRequestDeletedDocument,- variables: {- teamID: this.teamID,- },- })-- this.teamRequestDeletedSub = teamReqDeleted- this.teamRequestDeleted$ = teamReqDeleted$.subscribe((result) => {- if (E.isLeft(result))- throw new Error(- `Team Request Deleted Error ${JSON.stringify(result.left)}`- )-- this.removeRequest(result.right.teamRequestDeleted)- })-- const [teamRequestMoved$, teamRequestMoved] = runGQLSubscription({- query: TeamRequestMovedDocument,- variables: {- teamID: this.teamID,- },- })-- this.teamRequestMovedSub = teamRequestMoved- this.teamRequestMoved$ = teamRequestMoved$.subscribe((result) => {- if (E.isLeft(result))- throw new Error(- `Team Request Move Error ${JSON.stringify(result.left)}`- )-- const { requestMoved } = result.right-- const request = {- id: requestMoved.id,- collectionID: requestMoved.collectionID,- title: requestMoved.title,- request: JSON.parse(requestMoved.request),- }-- this.moveRequest(request)- })-- const [teamCollectionMoved$, teamCollectionMoved] = runGQLSubscription({- query: TeamCollectionMovedDocument,- variables: {- teamID: this.teamID,- },- })-- this.teamCollectionMovedSub = teamCollectionMoved- this.teamCollectionMoved$ = teamCollectionMoved$.subscribe((result) => {- if (E.isLeft(result))- throw new Error(- `Team Collection Move Error ${JSON.stringify(result.left)}`- )-- const { teamCollectionMoved } = result.right- const { id, parent, title, data } = teamCollectionMoved-- const parentID = parent?.id ?? null-- this.moveCollection(id, parentID, title, data)- })-- const [teamRequestOrderUpdated$, teamRequestOrderUpdated] =- runGQLSubscription({- query: TeamRequestOrderUpdatedDocument,- variables: {- teamID: this.teamID,- },- })-- this.teamRequestOrderUpdatedSub = teamRequestOrderUpdated- this.teamRequestOrderUpdated$ = teamRequestOrderUpdated$.subscribe(- (result) => {- if (E.isLeft(result))- throw new Error(- `Team Request Order Update Error ${JSON.stringify(result.left)}`- )-- const { requestOrderUpdated } = result.right- const { request } = requestOrderUpdated- const { nextRequest } = requestOrderUpdated-- this.updateRequestOrder(- request.id,- nextRequest ? nextRequest.id : null,- nextRequest ? nextRequest.collectionID : request.collectionID- )- }- )-- const [teamCollectionOrderUpdated$, teamCollectionOrderUpdated] =- runGQLSubscription({- query: TeamCollectionOrderUpdatedDocument,- variables: {- teamID: this.teamID,- },- })-- this.teamCollectionOrderUpdatedSub = teamCollectionOrderUpdated- this.teamCollectionOrderUpdated$ = teamCollectionOrderUpdated$.subscribe(- (result) => {- if (E.isLeft(result))- throw new Error(- `Team Collection Order Update Error ${JSON.stringify(result.left)}`- )-- const { collectionOrderUpdated } = result.right- const { collection } = collectionOrderUpdated- const { nextCollection } = collectionOrderUpdated-- this.updateCollectionOrder(- collection.id,- nextCollection ? nextCollection.id : null- )- }- )- }-- private async getCollectionChildren(- collection: TeamCollection- ): Promise<TeamCollection[]> {- const collections: TeamCollection[] = []-- while (true) {- const data = await runGQLQuery({- query: GetCollectionChildrenDocument,- variables: {- collectionID: collection.id,- cursor:- collections.length > 0- ? collections[collections.length - 1].id- : undefined,- },- })-- if (E.isLeft(data)) {- throw new Error(- `Child Collection Fetch Error for ${collection.id}: ${data.left}`- )- }-- collections.push(- ...data.right.collection!.children.map(- (el) =>- <TeamCollection>{- id: el.id,- title: el.title,- data: el.data,- children: null,- requests: null,- }- )- )-- if (data.right.collection!.children.length !== TEAMS_BACKEND_PAGE_SIZE)- break- }-- return collections- }-- private async getCollectionRequests(- collection: TeamCollection- ): Promise<TeamRequest[]> {- const requests: TeamRequest[] = []-- while (true) {- const data = await runGQLQuery({- query: GetCollectionRequestsDocument,- variables: {- collectionID: collection.id,- cursor:- requests.length > 0 ? requests[requests.length - 1].id : undefined,- },- })-- if (E.isLeft(data)) {- throw new Error(`Child Request Fetch Error for ${data}: ${data.left}`)- }-- requests.push(- ...data.right.requestsInCollection.map<TeamRequest>((el) => {- return {- id: el.id,- collectionID: collection.id,- title: el.title,- request: translateToNewRequest(JSON.parse(el.request)),- }- })- )-- if (data.right.requestsInCollection.length !== TEAMS_BACKEND_PAGE_SIZE)- break- }-- return requests- }-- /**- * Expands a collection on the tree- *- * When a collection is loaded initially in the adapter, children and requests are not loaded (they will be set to null)- * Upon expansion those two fields will be populated- *- * @param {string} collectionID - The ID of the collection to expand- */- async expandCollection(collectionID: string): Promise<void> {- // TODO: While expanding one collection, block (or queue) the expansion of the other, to avoid race conditions- const tree = this.collections$.value-- const collection = findCollInTree(tree, collectionID)-- if (!collection) return-- if (collection.children !== null) return-- this.loadingCollections$.next([- ...this.loadingCollections$.getValue(),- collectionID,- ])-- try {- const [collections, requests] = await Promise.all([- this.getCollectionChildren(collection),- this.getCollectionRequests(collection),- ])-- collection.children = collections- collection.requests = requests-- // Add to the entity ids set- collections.forEach((coll) => this.entityIDs.add(`collection-${coll.id}`))- requests.forEach((req) => this.entityIDs.add(`request-${req.id}`))-- this.collections$.next(tree)- } finally {- this.loadingCollections$.next(- this.loadingCollections$.getValue().filter((x) => x !== collectionID)- )- }- }-- private getCurrentValue = (- env: HoppCollectionVariable,- varIndex: number,- collectionID: string- ) => {- if (env && env.secret) {- return this.secretEnvironmentService.getSecretEnvironmentVariable(- collectionID,- varIndex- )?.value- }- return this.currentEnvironmentValueService.getEnvironmentVariable(- collectionID,- varIndex- )?.currentValue- }-- /**- * This function populates the values of the variables with the current values or secrets.- * @param variables Variables to populate- * @returns Populated variables with current values or secrets- */- private populateValues(- variables: HoppCollectionVariable[],- parentID: string- ) {- return variables.map((v, index) => ({- ...v,- currentValue: this.getCurrentValue(v, index, parentID) ?? v.currentValue,- }))- }-- /**- * Used to obtain the inherited auth and headers for a given folder path, used for both REST and GraphQL team collections- * @param folderPath the path of the folder to cascade the auth from- * @returns the inherited auth and headers for the given folder path- */- public cascadeParentCollectionForProperties(folderPath: string) {- let auth: HoppInheritedProperty["auth"] = {- parentID: folderPath ?? "",- parentName: "",- inheritedAuth: {- authType: "none",- authActive: true,- },- }- const headers: HoppInheritedProperty["headers"] = []-- const variables: HoppInheritedProperty["variables"] = []-- const scripts: HoppInheritedProperty["scripts"] = []-- if (!folderPath) return { auth, headers, variables, scripts }-- const path = folderPath.split("/")-- // Check if the path is empty or invalid- if (!path || path.length === 0) {- console.error("Invalid path:", folderPath)- return { auth, headers, variables, scripts }- }-- // Loop through the path and get the last parent folder with authType other than 'inherit'- for (let i = 0; i < path.length; i++) {- const parentFolder = findCollInTree(this.collections$.value, path[i])-- // Check if parentFolder is undefined or null- if (!parentFolder) {- console.error("Parent folder not found for path:", path)- return { auth, headers, variables, scripts }- }-- const data: Partial<CollectionDataProps> = parentFolder.data- ? JSON.parse(parentFolder.data)- : {}-- if (!data.auth) {- data.auth = {- authType: "inherit",- authActive: true,- }- auth.parentID = path.slice(0, i + 1).join("/")- auth.parentName = parentFolder.title- }-- if (!data.headers) data.headers = []-- if (!data.variables) data.variables = []-- const parentFolderAuth = data.auth- const parentFolderHeaders = data.headers- const parentFolderVariables = data.variables- const parentFolderPreRequestScript = data.preRequestScript ?? ""- const parentFolderTestScript = data.testScript ?? ""-- if (- parentFolderAuth?.authType === "inherit" &&- path.slice(0, i + 1).length === 1- ) {- auth = {- parentID: path.slice(0, i + 1).join("/"),- parentName: parentFolder.title,- inheritedAuth: auth.inheritedAuth,- }- }-- if (parentFolderAuth?.authType !== "inherit") {- auth = {- parentID: path.slice(0, i + 1).join("/"),- parentName: parentFolder.title,- inheritedAuth: parentFolderAuth,- }- }-- // Update headers, overwriting duplicates by key- if (parentFolderHeaders) {- const activeHeaders = parentFolderHeaders.filter((h) => h.active)- activeHeaders.forEach((header) => {- const index = headers.findIndex(- (h) => h.inheritedHeader?.key === header.key- )- const currentPath = path.slice(0, i + 1).join("/")- if (index !== -1) {- // Replace the existing header with the same key- headers[index] = {- parentID: currentPath,- parentName: parentFolder.title,- inheritedHeader: header,- }- } else {- headers.push({- parentID: currentPath,- parentName: parentFolder.title,- inheritedHeader: header,- })- }- })- }-- // Update variables, overwriting duplicates by key- if (parentFolderVariables) {- const currentPath = [...path.slice(0, i + 1)].join("/")-- variables.push({- parentPath: path.slice(0, i + 1).join("/"),- parentID: parentFolder.id ?? currentPath,- parentName: parentFolder.title,- inheritedVariables: this.populateValues(- parentFolderVariables,- parentFolder.id ?? currentPath- ),- })- }-- // Update scripts- if (- hasActualScript(parentFolderPreRequestScript) ||- hasActualScript(parentFolderTestScript)- ) {- const currentPath = [...path.slice(0, i + 1)].join("/")-- scripts.push({- parentID: parentFolder.id ?? currentPath,- parentName: parentFolder.title,- preRequestScript: parentFolderPreRequestScript,- testScript: parentFolderTestScript,- })- }- }-- return { auth, headers, variables, scripts }- }-}diff --git a/packages/hoppscotch-common/src/helpers/teams/TeamRequest.ts b/packages/hoppscotch-common/src/helpers/teams/TeamRequest.tsindex 5fcdbe218..d3052532e 100644--- a/packages/hoppscotch-common/src/helpers/teams/TeamRequest.ts+++ b/packages/hoppscotch-common/src/helpers/teams/TeamRequest.ts@@ -1,4 +1,10 @@-import { HoppRESTRequest } from "@hoppscotch/data"+import {+ HoppGQLRequest,+ HoppRESTRequest,+ isGQLRequest,+ translateToGQLRequest,+ translateToNewRequest,+} from "@hoppscotch/data"import { runGQLQuery } from "../backend/GQLClient"import {GetCollectionChildrenDocument,@@ -7,13 +13,45 @@ import {} from "../backend/graphql"/**- * Defines how a Teams request is represented in TeamCollectionAdapter+ * Defines how a Teams request is represented in the team-collection service.+ * Unified collection: a single team collection holds REST and GQL requests.*/export interface TeamRequest {id: stringcollectionID: stringtitle: string- request: HoppRESTRequest+ request: HoppRESTRequest | HoppGQLRequest+}++/**+ * Normalize the JSON `request` string from a team request row into the+ * canonical REST or GQL shape. Both branches go through their respective+ * `translateTo*` migrators so legacy schema versions get carried up to the+ * latest (e.g. v9 GQL rows pick up the `description` field added in v10).+ *+ * Defensive against:+ * - Malformed JSON (parse error → default REST request, doesn't throw).+ * - `null` / non-object payloads — `isGQLRequest` would otherwise throw+ * `TypeError` on a non-object via the `in` operator.+ */+export function normalizeTeamRequestBody(+ raw: string+): HoppRESTRequest | HoppGQLRequest {+ let parsed: unknown+ try {+ parsed = JSON.parse(raw)+ } catch {+ return translateToNewRequest(undefined)+ }++ if (+ parsed !== null &&+ typeof parsed === "object" &&+ isGQLRequest(parsed as HoppRESTRequest | HoppGQLRequest)+ ) {+ return translateToGQLRequest(parsed)+ }+ return translateToNewRequest(parsed)}export const getCollectionChildRequests = (collectionID: string) =>diff --git a/packages/hoppscotch-common/src/helpers/teams/TeamsSearch.service.ts b/packages/hoppscotch-common/src/helpers/teams/TeamsSearch.service.tsindex 9a95ffc59..6cb02dbde 100644--- a/packages/hoppscotch-common/src/helpers/teams/TeamsSearch.service.ts+++ b/packages/hoppscotch-common/src/helpers/teams/TeamsSearch.service.ts@@ -1,7 +1,10 @@import {+ HoppGQLRequest,HoppRESTAuth,HoppRESTRequest,+ getDefaultGQLRequest,getDefaultRESTRequest,+ isGQLRequest,} from "@hoppscotch/data"import axios from "axios"import { Service } from "dioc"@@ -68,9 +71,12 @@ type _SearchRequest = {id: stringcollectionID: stringtitle: string+ // Search hits store a display stub; rows inserted while expanding store the+ // full parsed request. Team collections hold both protocols and GQL+ // requests have no `method` — readers fall back to a "GQL" badge.request: {name: string- method: string+ method?: string}meta?: CollectionSearchMeta}@@ -170,14 +176,18 @@ function convertToTeamTree(if (isAlreadyInserted) returnif (parentCollection) {- const requestSchemaParsedResult = HoppRESTRequest.safeParse(- request.request- )-- const effectiveRequest =- requestSchemaParsedResult.type === "ok"- ? requestSchemaParsedResult.value- : getDefaultRESTRequest()+ // Unified collection: a single team collection can hold REST and GQL requests.+ // Discriminate by shape so GQL search hits don't get clobbered into a blank REST request.+ let effectiveRequest: HoppRESTRequest | HoppGQLRequest+ if (isGQLRequest(request.request)) {+ const gqlParsed = HoppGQLRequest.safeParse(request.request)+ effectiveRequest =+ gqlParsed.type === "ok" ? gqlParsed.value : getDefaultGQLRequest()+ } else {+ const restParsed = HoppRESTRequest.safeParse(request.request)+ effectiveRequest =+ restParsed.type === "ok" ? restParsed.value : getDefaultRESTRequest()+ }parentCollection.requests = parentCollection.requests || []parentCollection.requests.push({@@ -342,7 +352,9 @@ export class TeamSearchService extends Service {{collectionID: request.collectionID,name: request.title,- method: request.request.method,+ // GQL rows have no `method` — badge them as GQL instead of+ // rendering an undefined method chip+ method: request.request.method ?? "GQL",id: request.id,},Object.values(this.searchResultsCollections)diff --git a/packages/hoppscotch-common/src/helpers/utils/EffectiveURL.ts b/packages/hoppscotch-common/src/helpers/utils/EffectiveURL.tsindex 9b5a07655..a8e284404 100644--- a/packages/hoppscotch-common/src/helpers/utils/EffectiveURL.ts+++ b/packages/hoppscotch-common/src/helpers/utils/EffectiveURL.ts@@ -1,6 +1,9 @@import {Environment,FormDataKeyValue,+ GQLHeader,+ HoppGQLAuth,+ HoppGQLRequest,HoppRESTAuth,HoppRESTHeader,HoppRESTHeaders,@@ -28,6 +31,7 @@ import { stripComments } from "../editor/linting/jsonc"import { arrayFlatMap, arraySort } from "../functional/array"import { toFormData } from "../functional/formData"import { tupleWithSameKeysToRecord } from "../functional/record"+import { getDefaultRESTRequest } from "../rest/default"import { isJSONContentType } from "./contenttypes"export interface EffectiveHoppRESTRequest extends HoppRESTRequest {@@ -75,6 +79,47 @@ export const getComputedAuthHeaders = async ()}+/**+ * GraphQL counterpart of `getComputedAuthHeaders`.+ *+ * A GQL request carries no method/params/body, so the signing auth types (AWS,+ * digest, HAWK) are handed the same synthetic `POST <url>` request the send path+ * signs (see `gql-tab-connection.service`) — that keeps the headers preview and+ * the wire in agreement. GQL auth is a structural subset of REST auth, and+ * inherited collection auth can legitimately be a REST-only type (digest, HAWK,+ * JWT…), all of which the shared generators cover.+ *+ * @param envVars Currently active environment variables+ * @param req Request to check+ * @param auth Authorization config to check, overriding the one on `req`+ * @returns The list of headers+ */+export const getComputedGQLAuthHeaders = async (+ envVars: Environment["variables"],+ req: HoppGQLRequest | { auth: HoppGQLAuth; headers: GQLHeader[] },+ auth?: HoppGQLAuth | HoppRESTAuth+): Promise<GQLHeader[]> => {+ // Request headers are applied last on the wire, so an explicit Authorization+ // header supersedes anything auth would generate — active rows only,+ // matching what execution actually sends+ if (+ req.headers.some((h) => h.active && h.key.toLowerCase() === "authorization")+ )+ return []++ const effectiveAuth = (auth ?? req.auth) as HoppRESTAuth++ if (!effectiveAuth?.authActive) return []++ const syntheticRESTRequest: HoppRESTRequest = {+ ...getDefaultRESTRequest(),+ method: "POST",+ endpoint: "url" in req ? req.url : "",+ }++ return generateAuthHeaders(effectiveAuth, syntheticRESTRequest, envVars)+}+/*** Get headers that can be generated by body config of the request* @param req Request to check@@ -256,7 +301,10 @@ export const resolvesEnvsInBody = (export function getFinalBodyFromRequest(request: HoppRESTRequest,envVariables: Environment["variables"],- showKeyIfSecret = false+ showKeyIfSecret = false,+ // Isolated runs (embeds) resolve missing body vars to "" — consistent+ // with how the URL/headers template them+ keepMissingBodyVars = true): FormData | Blob | string | null {if (request.body.contentType === null) return null@@ -346,7 +394,7 @@ export function getFinalBodyFromRequest(bodyContent = stripComments(request.body.body ?? "")// body can be null if the content-type is not set- return parseBodyEnvVariables(bodyContent, envVariables)+ return parseBodyEnvVariables(bodyContent, envVariables, keepMissingBodyVars)}/**@@ -356,6 +404,9 @@ export function getFinalBodyFromRequest(* @param environment The environment to apply* @param showKeyIfSecret Whether to show the key if the value is a secret* @param showKeyIfNotFound Whether to show the key if the value is not found+ * @param keepMissingBodyVars Whether missing body vars stay as literal+ * `<<key>>` (long-standing default); isolated embed runs pass false so the+ * body resolves them to "" like the URL/headers** @returns An object with extra fields defining a complete request*/@@ -363,7 +414,8 @@ export async function getEffectiveRESTRequest(request: HoppRESTRequest,environment: Environment,showKeyIfSecret = false,- showKeyIfNotFound = false+ showKeyIfNotFound = false,+ keepMissingBodyVars = true): Promise<EffectiveHoppRESTRequest> {const effectiveFinalHeaders = pipe((@@ -426,7 +478,8 @@ export async function getEffectiveRESTRequest(const effectiveFinalBody = getFinalBodyFromRequest(request,environment.variables,- showKeyIfSecret+ showKeyIfSecret,+ keepMissingBodyVars)return {@@ -462,3 +515,157 @@ export function getEffectiveRESTRequestStream(map(async ([request, env]) => await getEffectiveRESTRequest(request, env)))}++// ---------- GraphQL ----------++/**+ * The "effective" GraphQL request — derived from a `HoppGQLRequest` by:+ * - merging inherited collection headers with request headers (request wins on conflicts at send time)+ * - resolving auth (request auth wins; if request says "inherit" and active, inherited auth is used)+ * - template-resolving env variables in URL, header keys/values, query, variables JSON, and every auth field+ *+ * Mirrors `EffectiveHoppRESTRequest` for the REST flow. Consumers (the unified+ * `WorkspaceTabsService` GQL runner and the standalone `/graphql` page runner)+ * use the `effectiveFinal*` fields verbatim when building the kernel request /+ * subscription payload, so raw `<<envVar>>` strings cannot leak over the wire.+ */+export interface EffectiveHoppGQLRequest extends HoppGQLRequest {+ effectiveFinalURL: string+ /**+ * Inherited + request headers merged (in that order, request wins on intra-list+ * collisions), with every active key/value template-resolved.+ */+ effectiveFinalHeaders: GQLHeader[]+ /**+ * The request-level headers only (no inherited), template-resolved.+ * Runners re-apply this AFTER computed auth headers so that a header the user+ * sets explicitly on the Headers tab always wins over the same key produced by+ * the Auth tab — preserves the long-standing precedence rule+ * `request > auth > inherited`.+ */+ effectiveFinalRequestHeaders: GQLHeader[]+ effectiveFinalQuery: string+ effectiveFinalVariables: string+ effectiveFinalAuth: HoppGQLAuth+}++/**+ * Template-resolve env variables in every field of a `HoppGQLAuth` value that+ * carries user-provided text. Inactive auth or unknown auth types pass through.+ */+export function applyTemplateToGQLAuth(+ auth: HoppGQLAuth,+ envVars: Environment["variables"]+): HoppGQLAuth {+ if (!auth.authActive) return auth++ switch (auth.authType) {+ case "basic":+ return {+ ...auth,+ username: parseTemplateString(auth.username, envVars),+ password: parseTemplateString(auth.password, envVars),+ }+ case "bearer":+ return {+ ...auth,+ token: parseTemplateString(auth.token, envVars),+ }+ case "oauth-2":+ return {+ ...auth,+ grantTypeInfo: {+ ...auth.grantTypeInfo,+ token: parseTemplateString(auth.grantTypeInfo.token, envVars),+ },+ }+ case "api-key":+ return {+ ...auth,+ key: parseTemplateString(auth.key, envVars),+ value: parseTemplateString(auth.value, envVars),+ }+ case "aws-signature":+ return {+ ...auth,+ accessKey: parseTemplateString(auth.accessKey, envVars),+ secretKey: parseTemplateString(auth.secretKey, envVars),+ region: auth.region+ ? parseTemplateString(auth.region, envVars)+ : auth.region,+ serviceName: parseTemplateString(auth.serviceName, envVars),+ serviceToken: auth.serviceToken+ ? parseTemplateString(auth.serviceToken, envVars)+ : auth.serviceToken,+ }+ default:+ return auth+ }+}++/**+ * Produces an `EffectiveHoppGQLRequest` with envs templated through every+ * user-provided field. Pass the per-tab inherited headers/auth via `options`;+ * `options.query` / `options.variables` / `options.url` override the request's+ * own fields when the caller wants to template a transient value (e.g. the+ * editor's current unsaved text).+ */+export function getEffectiveHoppGQLRequest(+ request: HoppGQLRequest,+ envVars: Environment["variables"],+ options?: {+ inheritedHeaders?: GQLHeader[]+ inheritedAuth?: HoppGQLAuth | null+ url?: string+ query?: string+ variables?: string+ }+): EffectiveHoppGQLRequest {+ const rawURL = options?.url ?? request.url+ const rawQuery = options?.query ?? request.query+ const rawVariables = options?.variables ?? request.variables++ // Resolve auth: request auth wins unless it's "inherit" and active, in which+ // case fall back to inherited auth (if any was passed).+ const baseAuth: HoppGQLAuth =+ request.auth.authType === "inherit" &&+ request.auth.authActive &&+ options?.inheritedAuth+ ? options.inheritedAuth+ : request.auth++ const effectiveFinalAuth = applyTemplateToGQLAuth(baseAuth, envVars)++ // Template inherited and request headers separately (request needs to be+ // re-applied AFTER auth headers in the runner — see effectiveFinalRequestHeaders).+ // Filter out inactive/empty before templating (matches REST behavior in+ // getEffectiveRESTRequest).+ const templateHeader = (h: GQLHeader) => ({+ ...h,+ key: parseTemplateString(h.key, envVars),+ value: parseTemplateString(h.value, envVars),+ })++ const effectiveFinalRequestHeaders = request.headers+ .filter((h) => h.active && h.key !== "")+ .map(templateHeader)++ const effectiveInheritedHeaders = (options?.inheritedHeaders ?? [])+ .filter((h) => h.active && h.key !== "")+ .map(templateHeader)++ const effectiveFinalHeaders: GQLHeader[] = [+ ...effectiveInheritedHeaders,+ ...effectiveFinalRequestHeaders,+ ]++ return {+ ...request,+ effectiveFinalURL: parseTemplateString(rawURL, envVars),+ effectiveFinalHeaders,+ effectiveFinalRequestHeaders,+ effectiveFinalQuery: parseTemplateString(rawQuery, envVars),+ effectiveFinalVariables: parseTemplateString(rawVariables, envVars),+ effectiveFinalAuth,+ }+}diff --git a/packages/hoppscotch-common/src/helpers/utils/__tests__/effectiveURLGQLAuth.spec.ts b/packages/hoppscotch-common/src/helpers/utils/__tests__/effectiveURLGQLAuth.spec.tsnew file mode 100644index 000000000..c8ec1ed4d--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/utils/__tests__/effectiveURLGQLAuth.spec.ts@@ -0,0 +1,126 @@+import type {+ Environment,+ HoppGQLAuth,+ HoppGQLRequest,+ HoppRESTAuth,+} from "@hoppscotch/data"+import { beforeEach, describe, expect, test, vi } from "vitest"++vi.mock("@hoppscotch/data", async () => {+ const actual =+ await vi.importActual<typeof import("@hoppscotch/data")>("@hoppscotch/data")+ return {+ ...actual,+ generateJWTToken: vi.fn(),+ }+})++const { generateJWTToken } = await import("@hoppscotch/data")+const { getDefaultGQLRequest } = await import("~/helpers/graphql/default")+const { getComputedGQLAuthHeaders } = await import("../EffectiveURL")++const envVars: Environment["variables"] = [+ {+ key: "TOKEN",+ secret: false,+ initialValue: "env-token",+ currentValue: "env-token",+ },+]++const makeRequest = (+ auth: HoppGQLAuth,+ headers: HoppGQLRequest["headers"] = []+) =>+ ({+ ...getDefaultGQLRequest(),+ url: "https://api.example.com/graphql",+ auth,+ headers,+ }) as HoppGQLRequest++describe("getComputedGQLAuthHeaders", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ test("returns nothing when auth is inactive", async () => {+ const headers = await getComputedGQLAuthHeaders(+ envVars,+ makeRequest({ authType: "bearer", authActive: false, token: "abc" })+ )++ expect(headers).toEqual([])+ })++ test("an explicit Authorization header supersedes generated auth", async () => {+ const headers = await getComputedGQLAuthHeaders(+ envVars,+ makeRequest({ authType: "bearer", authActive: true, token: "abc" }, [+ {+ key: "authorization",+ value: "Bearer manual",+ active: true,+ description: "",+ },+ ])+ )++ expect(headers).toEqual([])+ })++ test("resolves environment variables in the generated header", async () => {+ const headers = await getComputedGQLAuthHeaders(+ envVars,+ makeRequest({+ authType: "bearer",+ authActive: true,+ token: "<<TOKEN>>",+ })+ )++ expect(headers).toEqual([+ {+ active: true,+ key: "Authorization",+ value: "Bearer env-token",+ description: "",+ },+ ])+ })++ // JWT/HAWK/digest are REST-only auth types a GQL request can still pick up+ // through collection inheritance+ test("supports inherited JWT auth", async () => {+ vi.mocked(generateJWTToken).mockResolvedValue("jwt-token")++ const inheritedAuth: HoppRESTAuth = {+ authType: "jwt",+ authActive: true,+ secret: "my-secret",+ privateKey: "",+ algorithm: "HS256",+ payload: "{}",+ addTo: "HEADERS",+ isSecretBase64Encoded: false,+ headerPrefix: "Bearer ",+ paramName: "token",+ jwtHeaders: "{}",+ }++ const headers = await getComputedGQLAuthHeaders(+ envVars,+ makeRequest({ authType: "inherit", authActive: true }),+ inheritedAuth+ )++ expect(headers).toEqual([+ {+ active: true,+ key: "Authorization",+ value: "Bearer jwt-token",+ description: "",+ },+ ])+ })+})diff --git a/packages/hoppscotch-common/src/helpers/workers/documentation.worker.ts b/packages/hoppscotch-common/src/helpers/workers/documentation.worker.tsindex 6aeef70fb..1ef562f2b 100644--- a/packages/hoppscotch-common/src/helpers/workers/documentation.worker.ts+++ b/packages/hoppscotch-common/src/helpers/workers/documentation.worker.ts@@ -1,4 +1,8 @@-import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data"+import {+ HoppCollection,+ HoppGQLRequest,+ HoppRESTRequest,+} from "@hoppscotch/data"import { DocumentationItem } from "~/composables/useDocumentationWorker"interface GatherDocumentationMessage {@@ -147,7 +151,7 @@ async function gatherAllItems(items.push({type: "request",- item: request as HoppRESTRequest,+ item: request as HoppRESTRequest | HoppGQLRequest,parentPath: parentPath? `${parentPath} / ${folder.name}`: folder.name,diff --git a/packages/hoppscotch-common/src/helpers/workers/sandbox.worker.ts b/packages/hoppscotch-common/src/helpers/workers/sandbox.worker.tsindex cee659c5b..de6f54e4b 100644--- a/packages/hoppscotch-common/src/helpers/workers/sandbox.worker.ts+++ b/packages/hoppscotch-common/src/helpers/workers/sandbox.worker.ts@@ -53,12 +53,10 @@ interface PostRequestScriptErrorMessage {}export type OutgoingSandboxPreRequestWorkerMessage =- | PreRequestScriptResultMessage- | PreRequestScriptErrorMessage+ PreRequestScriptResultMessage | PreRequestScriptErrorMessageexport type OutgoingSandboxPostRequestWorkerMessage =- | PostRequestScriptResultMessage- | PostRequestScriptErrorMessage+ PostRequestScriptResultMessage | PostRequestScriptErrorMessageself.addEventListener("message",diff --git a/packages/hoppscotch-common/src/kernel/store.ts b/packages/hoppscotch-common/src/kernel/store.tsindex eced46a06..17bbf5fdd 100644--- a/packages/hoppscotch-common/src/kernel/store.ts+++ b/packages/hoppscotch-common/src/kernel/store.ts@@ -49,8 +49,7 @@ diag("store", "window.location.href:", window.location.href)// the init step and the loaded modules. Web mode never resolves these// because `isInitd` returns early outside desktop.let invoke:- | (<T>(cmd: string, args?: Record<string, unknown>) => Promise<T>)- | undefined+ (<T>(cmd: string, args?: Record<string, unknown>) => Promise<T>) | undefinedlet join: ((...paths: string[]) => Promise<string>) | undefined// Single init promise to avoid multiple imports and race conditionsdiff --git a/packages/hoppscotch-common/src/lib/sync/collections/index.ts b/packages/hoppscotch-common/src/lib/sync/collections/index.tsindex a1a04ff74..080537c6a 100644--- a/packages/hoppscotch-common/src/lib/sync/collections/index.ts+++ b/packages/hoppscotch-common/src/lib/sync/collections/index.ts@@ -25,6 +25,7 @@ import {HoppRESTHeaders,HoppRESTParam,HoppRESTRequest,+ isGQLRequest,makeCollection,} from "@hoppscotch/data"import * as E from "fp-ts/Either"@@ -128,6 +129,70 @@ function addDescriptionField(}))}+// Unified collections can hold cross-type requests, so try both schemas before rebuilding.+function normalizeCollectionRequest(+ request: HoppRESTRequest | HoppGQLRequest,+ collectionType: "REST" | "GQL"+): HoppRESTRequest | HoppGQLRequest {+ if (collectionType === "REST") {+ const restParsed = HoppRESTRequest.safeParse(request)+ if (restParsed.type === "ok") return restParsed.value++ if (isGQLRequest(request)) {+ const gqlParsed = HoppGQLRequest.safeParse(request)+ return gqlParsed.type === "ok"+ ? gqlParsed.value+ : (request as HoppGQLRequest)+ }++ const r = request as HoppRESTRequest+ return {+ v: r.v,+ id: r.id,+ name: r.name,+ endpoint: r.endpoint,+ method: r.method,+ params: addDescriptionField(r.params) as HoppRESTParam[],+ requestVariables: r.requestVariables,+ auth: r.auth,+ headers: addDescriptionField(r.headers) as HoppRESTHeaders,+ body: r.body,+ preRequestScript: r.preRequestScript,+ testScript: r.testScript,+ responses: r.responses,+ description: r.description ?? null,+ _ref_id: r._ref_id ?? generateUniqueRefId("req"),+ }+ }++ const gqlParsed = HoppGQLRequest.safeParse(request)+ if (gqlParsed.type === "ok") return gqlParsed.value++ if (!isGQLRequest(request)) {+ const restParsed = HoppRESTRequest.safeParse(request)+ return restParsed.type === "ok"+ ? restParsed.value+ : (request as HoppRESTRequest)+ }++ const g = request as HoppGQLRequest+ return {+ id: g.id,+ v: g.v,+ auth: g.auth,+ headers: addDescriptionField(g.headers) as GQLHeader[],+ name: g.name,+ query: g.query,+ url: g.url,+ variables: g.variables,+ description: g.description ?? null,+ _ref_id: g._ref_id ?? generateUniqueRefId("req"),+ responses: g.responses ?? {},+ preRequestScript: g.preRequestScript ?? "",+ testScript: g.testScript ?? "",+ }+}+export function exportedCollectionToHoppCollection(collection: ExportedUserCollectionREST | ExportedUserCollectionGQL,collectionType: "REST" | "GQL"@@ -153,51 +218,9 @@ export function exportedCollectionToHoppCollection(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"),- }- }),+ requests: restCollection.requests.map((request) =>+ normalizeCollectionRequest(request, "REST")+ ),description: data.description ?? null,auth: data.auth,headers: addDescriptionField(data.headers),@@ -226,27 +249,9 @@ export function exportedCollectionToHoppCollection(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,- }- }),+ requests: gqlCollection.requests.map((request) =>+ normalizeCollectionRequest(request, "GQL")+ ),auth: data.auth,headers: addDescriptionField(data.headers),variables: data.variables ?? [],@@ -809,10 +814,14 @@ function setupUserCollectionDuplicatedSubscription() {// Duplicated collection will have a unique ref idconst _ref_id = generateUniqueRefId("coll")- const folders = transformDuplicatedCollections(childCollectionsJSONStr)+ const folders = transformDuplicatedCollections(+ childCollectionsJSONStr,+ collectionType+ )const requests = transformDuplicatedCollectionRequests(- userRequests as UserRequest[]+ userRequests as UserRequest[],+ collectionType)// New collection to be added to store with the transformed data@@ -996,10 +1005,12 @@ function setupUserRequestCreatedSubscription() {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 request = normalizeCollectionRequest(+ JSON.parse(res.right.userRequestCreated.request),+ requestType+ )+ const requestID = res.right.userRequestCreated.idconst { collectionStore } = getStoreByCollectionType(requestType)@@ -1021,7 +1032,7 @@ function setupUserRequestCreatedSubscription() {runDispatchWithOutSyncing(() => {requestType == "REST"? saveRESTRequestAs(collectionPath, request)- : saveGraphqlRequestAs(collectionPath, request)+ : saveGraphqlRequestAs(collectionPath, request as HoppGQLRequest)const target = navigateToFolderWithIndexPath(collectionStore.value.state,@@ -1059,19 +1070,20 @@ function setupUserRequestUpdatedSubscription() {const collectionPath = requestPath?.collectionPathconst requestIndex = requestPath?.requestIndex+ const updatedRequest = normalizeCollectionRequest(+ JSON.parse(res.right.userRequestUpdated.request),+ requestType+ )+;(requestIndex || requestIndex == 0) &&collectionPath &&runDispatchWithOutSyncing(() => {requestType == "REST"- ? editRESTRequest(- collectionPath,- requestIndex,- JSON.parse(res.right.userRequestUpdated.request)- )+ ? editRESTRequest(collectionPath, requestIndex, updatedRequest): editGraphqlRequest(collectionPath,requestIndex,- JSON.parse(res.right.userRequestUpdated.request)+ updatedRequest as HoppGQLRequest)})}@@ -1164,8 +1176,9 @@ function setupUserRequestMovedSubscription() {): undefined+ // `!== undefined` (not truthy) so cross-tab reorders to position 0+ // still dispatch; `!== -1` guards a getRequestIndex findIndex miss.nextRequestIndex !== undefined &&- nextRequestIndex !== -1 &&nextCollectionPath &&sourceRequestPath &&runDispatchWithOutSyncing(() => {@@ -1317,7 +1330,8 @@ function getRequestIndex(}function transformDuplicatedCollections(- collectionsJSONStr: string+ collectionsJSONStr: string,+ collectionType: "REST" | "GQL"): HoppCollection[] {const parsedCollections: UserCollectionDuplicatedData[] =JSON.parse(collectionsJSONStr)@@ -1351,9 +1365,15 @@ function transformDuplicatedCollections(const _ref_id = generateUniqueRefId("coll")- const folders = transformDuplicatedCollections(childCollectionsJSONStr)+ const folders = transformDuplicatedCollections(+ childCollectionsJSONStr,+ collectionType+ )- const requests = transformDuplicatedCollectionRequests(userRequests)+ const requests = transformDuplicatedCollectionRequests(+ userRequests,+ collectionType+ )return makeCollection({id,@@ -1373,14 +1393,18 @@ function transformDuplicatedCollections(}function transformDuplicatedCollectionRequests(- requests: UserRequest[]+ requests: UserRequest[],+ collectionType: "REST" | "GQL"): HoppRESTRequest[] | HoppGQLRequest[] {return requests.map(({ id, request }) => {- const parsedRequest = JSON.parse(request)+ const normalized = normalizeCollectionRequest(+ JSON.parse(request),+ collectionType+ )return {- ...parsedRequest,+ ...normalized,id,}- })+ }) as HoppRESTRequest[] | HoppGQLRequest[]}diff --git a/packages/hoppscotch-common/src/lib/sync/collections/sync.ts b/packages/hoppscotch-common/src/lib/sync/collections/sync.tsindex ea6d0d61f..bb8ffe257 100644--- a/packages/hoppscotch-common/src/lib/sync/collections/sync.ts+++ b/packages/hoppscotch-common/src/lib/sync/collections/sync.ts@@ -1,8 +1,8 @@import {generateUniqueRefId,HoppCollection,+ HoppGQLRequest,HoppRESTRequest,- makeCollection,} from "@hoppscotch/data"import {@@ -77,43 +77,6 @@ type ExportedCollectionFolder = {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,@@ -188,8 +151,7 @@ export function applyDuplicatedCollectionResult(exportedCollectionJSON: string) {const parsed = JSON.parse(exportedCollectionJSON) as- | ExportedCollectionFolder- | ExportedCollectionFolder[]+ ExportedCollectionFolder | ExportedCollectionFolder[]// The backend may return either the duplicated collection directly or wrapped// in an array — normalize to the single duplicated collection.@@ -724,17 +686,16 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const request = folder.requests[requestIndex]if (!request) return+ // Unified workspace: REST mutation handles both kinds — backend stores the request as opaque JSON in a REST row.+ const typed = requestNew as HoppRESTRequest | HoppGQLRequest+if (request.id) {- editUserRequest(- request.id,- (requestNew as HoppRESTRequest).name,- JSON.stringify(requestNew)- )+ editUserRequest(request.id, typed.name, JSON.stringify(typed))} else {if (isSynced && folder.id) {const res = await createRESTUserRequest(- (requestNew as HoppRESTRequest).name,- JSON.stringify(requestNew),+ typed.name,+ JSON.stringify(typed),folder.id)if (res && E.isRight(res)) {@@ -762,9 +723,11 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const parentCollectionBackendID = folder?.idif (parentCollectionBackendID) {+ // See `editRequest` above — REST mutation handles both kinds.+ const typed = request as HoppRESTRequest | HoppGQLRequestconst res = await createRESTUserRequest(- (request as HoppRESTRequest).name,- JSON.stringify(request),+ typed.name,+ JSON.stringify(typed),parentCollectionBackendID)@@ -945,7 +908,7 @@ export async function moveOrReorderRequests(let nextRequestBackendID: string | undefined- // we only need this for reordering requests, not for moving requests+ // `!== undefined` (not truthy) so position-0 drops still take the reorder path.if (nextRequestIndex !== undefined) {// reorderingconst [newRequestIndex, newDestinationIndex] = getIndexesAfterReorder(diff --git a/packages/hoppscotch-common/src/newstore/collections.ts b/packages/hoppscotch-common/src/newstore/collections.tsindex 9e7a073c0..1086a6fe9 100644--- a/packages/hoppscotch-common/src/newstore/collections.ts+++ b/packages/hoppscotch-common/src/newstore/collections.ts@@ -17,7 +17,7 @@ import { resolveSaveContextOnRequestReorder } from "~/helpers/collection/requestimport { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"import { getService } from "~/modules/dioc"import { getI18n } from "~/modules/i18n"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import DispatchingStore, { defineDispatchers } from "./DispatchingStore"import { SecretEnvironmentService } from "~/services/secret-environment.service"import { CurrentValueService } from "~/services/current-environment-value.service"@@ -124,7 +124,11 @@ function populateValues(/*** Used to obtain the inherited auth and headers for a given folder path, used for both REST and GraphQL personal collections* @param folderPath the path of the folder to cascade the auth from- * @param type the type of collection+ * @param type Names the COLLECTION STORE the `folderPath` indexes — NOT the+ * protocol of the request being opened. "rest" is the unified store+ * (`restCollectionStore`), which also holds GQL requests as embedded rows, so+ * a GQL request opened from a unified collection cascades with "rest".+ * "graphql" is the legacy GQL-only store backing the standalone /graphql page.* @param showSecret whether to show secret values in the collection variables* @returns the inherited auth and headers for the given folder path*/@@ -175,8 +179,7 @@ export function cascadeParentCollectionForProperties(const parentFolderAuth = parentFolder.auth as HoppRESTAuth | HoppGQLAuthconst parentFolderHeaders = parentFolder.headers as- | HoppRESTHeaders- | GQLHeader[]+ HoppRESTHeaders | GQLHeader[]const parentFolderVariables =parentFolder.variables as HoppCollectionVariable[]@@ -858,7 +861,7 @@ const restCollectionDispatchers = defineDispatchers({// Deal with situations where a tab with the given thing is deleted// We are just going to dissociate the save context of the tab and mark it dirty- const tabService = getService(RESTTabService)+ const tabService = getService(WorkspaceTabsService)const tab = tabService.getTabRefWithSaveContext({originLocation: "user-collection",@@ -866,7 +869,7 @@ const restCollectionDispatchers = defineDispatchers({requestIndex: requestIndex,})- if (tab) {+ if (tab && tab.value.document.type !== "test-runner") {tab.value.document.saveContext = undefinedtab.value.document.isDirty = true}@@ -918,14 +921,14 @@ const restCollectionDispatchers = defineDispatchers({destLocation.requests.push(req)targetLocation.requests.splice(requestIndex, 1)- const tabService = getService(RESTTabService)+ const tabService = getService(WorkspaceTabsService)const possibleTab = tabService.getTabRefWithSaveContext({originLocation: "user-collection",folderPath: path,requestIndex,})- if (possibleTab) {+ if (possibleTab && possibleTab.value.document.type !== "test-runner") {possibleTab.value.document.saveContext = {originLocation: "user-collection",folderPath: destinationPath,@@ -1966,7 +1969,7 @@ export function removeDuplicateRESTCollectionOrFolder(export function editRESTRequest(path: string,requestIndex: number,- requestNew: HoppRESTRequest+ requestNew: HoppRESTRequest | HoppGQLRequest) {const indexPaths = path.split("/").map((x) => parseInt(x))if (@@ -1984,7 +1987,10 @@ export function editRESTRequest(})}-export function saveRESTRequestAs(path: string, request: HoppRESTRequest) {+export function saveRESTRequestAs(+ path: string,+ request: HoppRESTRequest | HoppGQLRequest+) {// For calculating the insertion request indexconst targetLocation = navigateToFolderWithIndexPath(restCollectionStore.value.state,diff --git a/packages/hoppscotch-common/src/newstore/settings.ts b/packages/hoppscotch-common/src/newstore/settings.tsindex cb05f924a..c00b25392 100644--- a/packages/hoppscotch-common/src/newstore/settings.ts+++ b/packages/hoppscotch-common/src/newstore/settings.ts@@ -85,6 +85,7 @@ export type SettingsDef = {EXPERIMENTAL_SCRIPTING_SANDBOX: booleanENABLE_EXPERIMENTAL_MOCK_SERVERS: booleanENABLE_EXPERIMENTAL_DOCUMENTATION: boolean+ ENABLE_GQL_IN_REST_WORKSPACE: boolean}export const getDefaultSettings = (): SettingsDef => {@@ -144,6 +145,7 @@ export const getDefaultSettings = (): SettingsDef => {EXPERIMENTAL_SCRIPTING_SANDBOX: true,ENABLE_EXPERIMENTAL_MOCK_SERVERS: true,ENABLE_EXPERIMENTAL_DOCUMENTATION: true,+ ENABLE_GQL_IN_REST_WORKSPACE: true,}}diff --git a/packages/hoppscotch-common/src/pages/e/_id.vue b/packages/hoppscotch-common/src/pages/e/_id.vueindex 149ac0063..9b218786f 100644--- a/packages/hoppscotch-common/src/pages/e/_id.vue+++ b/packages/hoppscotch-common/src/pages/e/_id.vue@@ -21,8 +21,15 @@</div><Embeds- v-else-if="tab"- v-model:model-tab="tab"+ v-else-if="protocol === 'rest' && restTab"+ v-model:model-tab="restTab"+ :properties="properties"+ :shared-request-i-d="sharedRequestID"+ />++ <EmbedsGQLIndex+ v-else-if="protocol === 'gql' && gqlTab"+ v-model:model-tab="gqlTab":properties="properties":shared-request-i-d="sharedRequestID"/>@@ -30,8 +37,7 @@</template><script setup lang="ts">-import { ref } from "vue"-import { watch } from "vue"+import { ref, watch, onMounted, onBeforeUnmount } from "vue"import { useRoute } from "vue-router"import { useGQLQuery } from "~/composables/graphql"import {@@ -40,23 +46,58 @@ import {ResolveShortcodeQueryVariables,} from "~/helpers/backend/graphql"import * as E from "fp-ts/Either"-import { onMounted } from "vue"import {+ HoppGQLRequest,+ HoppRESTRequest,getDefaultRESTRequest,+ isGQLRequest,+ makeGQLRequest,safelyExtractRESTRequest,+ translateToGQLRequest,} from "@hoppscotch/data"import { HoppTab } from "~/services/tab"-import { HoppRequestDocument } from "~/helpers/rest/document"-import { applySetting } from "~/newstore/settings"+import {+ HoppGQLRequestDocument,+ HoppRequestDocument,+} from "~/helpers/tab/document"import { useI18n } from "~/composables/i18n"+// Sharer-controlled theme — apply to this embed document only; persisting+// it via applySetting would write into the viewer's settings store.+// "system" tracks later OS color-scheme changes via a media listener.+let systemThemeQuery: MediaQueryList | null = null+const onSystemThemeChange = (e: MediaQueryListEvent) => {+ document.documentElement.setAttribute("class", e.matches ? "dark" : "light")+}+const applyEmbedTheme = (theme: "dark" | "light" | "system") => {+ systemThemeQuery?.removeEventListener("change", onSystemThemeChange)+ systemThemeQuery = null+ if (theme === "system") {+ systemThemeQuery = window.matchMedia("(prefers-color-scheme: dark)")+ systemThemeQuery.addEventListener("change", onSystemThemeChange)+ document.documentElement.setAttribute(+ "class",+ systemThemeQuery.matches ? "dark" : "light"+ )+ return+ }+ document.documentElement.setAttribute("class", theme)+}+onBeforeUnmount(() => {+ systemThemeQuery?.removeEventListener("change", onSystemThemeChange)+})+const t = useI18n()const route = useRoute()const sharedRequestID = ref("")const invalidLink = ref(false)-const properties = ref([])+const properties = ref<string[]>([])++// Discriminator for which embed shell to render. Set when the shortcode+// payload is parsed; null until then (loading state).+const protocol = ref<"rest" | "gql" | null>(null)const sharedRequestDetails = useGQLQuery<ResolveShortcodeQuery,@@ -69,8 +110,16 @@ const sharedRequestDetails = useGQLQuery<},})-const tab = ref<HoppTab<HoppRequestDocument>>({- id: "0",+// Tab ids unique per page mount so two embeds opened back-to-back via SPA+// navigation don't share connection-service state (the GQL connection+// service keys schema/socket/subscription by tabId). `crypto.randomUUID`+// is available in all evergreen browsers and the desktop renderer.+const embedTabId = `embed-${crypto.randomUUID()}`++// One tab ref per protocol so each child component gets a tightly-typed+// model and we don't need to widen the embed components themselves.+const restTab = ref<HoppTab<HoppRequestDocument>>({+ id: embedTabId,document: {request: getDefaultRESTRequest(),response: null,@@ -79,6 +128,32 @@ const tab = ref<HoppTab<HoppRequestDocument>>({},})+const gqlTab = ref<HoppTab<HoppGQLRequestDocument>>({+ id: embedTabId,+ document: {+ request: makeGQLRequest({+ name: "Untitled Request",+ url: "",+ headers: [],+ query: "",+ variables: "",+ auth: { authType: "none", authActive: true },+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",+ }),+ response: null,+ isDirty: false,+ type: "gql-request",+ },+})++const isGQLShortcodePayload = (req: unknown): boolean =>+ !!req &&+ typeof req === "object" &&+ isGQLRequest(req as HoppRESTRequest | HoppGQLRequest)+watch(() => sharedRequestDetails.data,() => {@@ -96,19 +171,23 @@ watch(data.right.shortcode?.request as string)- tab.value.document.request = safelyExtractRESTRequest(- request,- getDefaultRESTRequest()- )+ if (isGQLShortcodePayload(request)) {+ // Versioned parser (safeParse + migrations, default fallback) — same+ // as `share/Request.vue` / `PublishedDocs.ts` for identical payloads+ gqlTab.value.document.request = translateToGQLRequest(request)+ protocol.value = "gql"+ } else {+ restTab.value.document.request = safelyExtractRESTRequest(+ request,+ getDefaultRESTRequest()+ )+ protocol.value = "rest"+ }if (data.right.shortcode && data.right.shortcode.properties) {const parsedProperties = JSON.parse(data.right.shortcode.properties)- if (parsedProperties.theme === "dark") {- applySetting("BG_COLOR", "dark")- } else if (parsedProperties.theme === "light") {- applySetting("BG_COLOR", "light")- } else if (parsedProperties.theme === "system") {- applySetting("BG_COLOR", "system")+ if (["dark", "light", "system"].includes(parsedProperties.theme)) {+ applyEmbedTheme(parsedProperties.theme)}properties.value = parsedProperties.options}diff --git a/packages/hoppscotch-common/src/pages/graphql.vue b/packages/hoppscotch-common/src/pages/graphql.vueindex 44679995e..f453560f1 100644--- a/packages/hoppscotch-common/src/pages/graphql.vue+++ b/packages/hoppscotch-common/src/pages/graphql.vue@@ -87,7 +87,7 @@import { usePageHead } from "@composables/head"import { useI18n } from "@composables/i18n"import { useService } from "dioc/vue"-import { computed, onBeforeUnmount, ref } from "vue"+import { computed, onBeforeUnmount, onMounted, ref } from "vue"import { defineActionHandler } from "~/helpers/actions"import { connection, disconnect } from "~/helpers/graphql/connection"import { getDefaultGQLRequest } from "~/helpers/graphql/default"@@ -101,6 +101,12 @@ const t = useI18n()const tabs = useService(GQLTabService)const { reset } = useExplorer()+// `useExplorer`'s nav stack is a module-level singleton shared with the GraphQL+// panes in the unified workspace, so arriving here could otherwise show a+// breadcrumb describing that workspace's schema. Reset on entry, mirroring the+// reset this page already does on every tab switch.+onMounted(() => reset())+const currentTabID = computed(() => tabs.currentTabID.value)const inspectionService = useService(InspectionService)diff --git a/packages/hoppscotch-common/src/pages/index.vue b/packages/hoppscotch-common/src/pages/index.vueindex bfcb216a9..dda279d10 100644--- a/packages/hoppscotch-common/src/pages/index.vue+++ b/packages/hoppscotch-common/src/pages/index.vue@@ -18,8 +18,12 @@:is-removable="activeTabs.length > 1":close-visibility="'hover'">- <template v-if="tab.document.type === 'request'" #tabhead>+ <template #tabhead><HttpTabHead+ v-if="+ tab.document.type === 'request' ||+ tab.document.type === 'example-response'+ ":tab="tab":is-removable="activeTabs.length > 1"@open-rename-modal="openReqRenameModal(tab.id)"@@ -28,6 +32,26 @@@duplicate-tab="duplicateTab(tab.id)"@share-tab-request="shareTabRequest(tab.id)"/>+ <GqlTabHead+ v-else-if="+ tab.document.type === 'gql-request' ||+ tab.document.type === 'gql-example-response'+ "+ :tab="tab"+ :is-removable="activeTabs.length > 1"+ @open-rename-modal="openReqRenameModal(tab.id)"+ @close-tab="removeTab(tab.id)"+ @close-other-tabs="closeOtherTabsAction(tab.id)"+ @duplicate-tab="duplicateTab(tab.id)"+ @share-tab-request="shareTabRequest(tab.id)"+ />+ <!-- Fallback for document types without a dedicated head+ (test-runner) — providing the #tabhead slot suppresses the+ Window's own `label`, so an unmatched type would otherwise+ render a blank tab head. -->+ <span v-else class="flex items-center truncate px-2">+ <span class="truncate">{{ getTabName(tab) }}</span>+ </span></template><template #suffix><span@@ -44,8 +68,26 @@</svg></span></template>+ <HttpProtocolSwitcher+ v-if="+ isGqlWorkspaceEnabled &&+ (tab.document.type === 'request' ||+ tab.document.type === 'gql-request')+ "+ /><HttpExampleResponseTab- v-if="tab.document.type === 'example-response'"+ v-if="+ tab.document.type === 'example-response' &&+ tab.document.response+ "+ :model-value="tab"+ @update:model-value="onTabUpdate"+ />+ <GqlExampleResponseTab+ v-if="+ tab.document.type === 'gql-example-response' &&+ tab.document.response+ ":model-value="tab"@update:model-value="onTabUpdate"/>@@ -61,6 +103,12 @@:model-value="tab"@update:model-value="onTabUpdate"/>+ <!-- When document.type === 'gql-request' render GQL tab -->+ <GqlRequestTab+ v-if="tab.document.type === 'gql-request'"+ :model-value="tab"+ @update:model-value="onTabUpdate"+ /><!-- END Render TabContents --></HoppSmartWindow><template #actions>@@ -118,7 +166,7 @@</HoppSmartModal><CollectionsSaveRequestv-if="savingRequest"- mode="rest"+ :mode="saveRequestMode":show="savingRequest"@hide-modal="onSaveModalClose"/>@@ -133,7 +181,7 @@</template><script lang="ts" setup>-import { ref, onMounted, computed } from "vue"+import { ref, onMounted, onBeforeUnmount, computed, nextTick } from "vue"import { generateUniqueRefId, safelyExtractRESTRequest } from "@hoppscotch/data"import { translateExtURLParams } from "~/helpers/RESTExtURLParams"import { useRoute } from "vue-router"@@ -149,12 +197,27 @@ import { EnvironmentInspectorService } from "~/services/inspection/inspectors/enimport { ResponseInspectorService } from "~/services/inspection/inspectors/response.inspector"import { ScriptingInterceptorInspectorService } from "~/services/inspection/inspectors/scripting-interceptor.inspector"import { cloneDeep } from "lodash-es"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { HoppTab } from "~/services/tab"-import { HoppRequestDocument, HoppTabDocument } from "~/helpers/rest/document"+import { HoppTabDocument } from "~/helpers/tab/document"import { ScrollService } from "~/services/scroll.service"+import { GQLTabConnectionService } from "~/services/gql-tab-connection.service"+import { useGqlWorkspaceVisibility } from "~/composables/gqlWorkspaceVisibility"const scrollService = useService(ScrollService)+const gqlTabConn = useService(GQLTabConnectionService)++// Tear down every GQL tab's poll timer and subscription socket when the user+// navigates away from the REST workspace. Per-tab cleanup on close covers+// tab-by-tab removal, but nothing fires when the whole page unmounts — so+// without this each gql-request tab's 7s schema poll keeps running for the+// rest of the app session. `disconnectAllTabs` clears the per-tab contexts;+// each tab re-establishes a fresh connection when the page is revisited.+onBeforeUnmount(() => {+ gqlTabConn.disconnectAllTabs()+})++const { isGqlWorkspaceEnabled } = useGqlWorkspaceVisibility()const savingRequest = ref(false)const confirmingCloseForTabID = ref<string | null>(null)@@ -167,7 +230,7 @@ const renameTabID = ref<string | null>(null)const t = useI18n()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const currentTabID = tabs.currentTabID@@ -216,10 +279,14 @@ function bindRequestToURLParams() {})}-const onTabUpdate = (tab: HoppTab<HoppRequestDocument>) => {+const onTabUpdate = (tab: HoppTab<HoppTabDocument>) => {tabs.updateTab(tab)}+// Always "workspace" — on the unified page every save goes through+// WorkspaceTabsService, for both REST and GQL documents.+const saveRequestMode = computed(() => "workspace" as const)+const addNewTab = () => {const tab = tabs.createNewTab({type: "request",@@ -235,11 +302,15 @@ const sortTabs = (e: { oldIndex: number; newIndex: number }) => {const getTabName = (tab: HoppTab<HoppTabDocument>) => {if (tab.document.type === "request") {- return tab.document.request.name+ return tab.document.request?.name ?? "Untitled"+ } else if (tab.document.type === "gql-request") {+ return tab.document.request?.name ?? "Untitled"} else if (tab.document.type === "test-runner") {- return tab.document.collection.name+ return tab.document.collection?.name ?? "Untitled"} else if (tab.document.type === "example-response") {- return tab.document.response.name+ return tab.document.response?.name ?? "Untitled"+ } else if (tab.document.type === "gql-example-response") {+ return tab.document.response?.name ?? "Untitled"}return "Unnamed tab"@@ -253,9 +324,30 @@ const removeTab = (tabID: string) => {if (tabState.document.isDirty) {confirmingCloseForTabID.value = tabID} else {- scrollService.cleanupScrollForTab(tabState.id)- tabs.closeTab(tabState.id)- inspectionService.deleteTabInspectorResult(tabState.id)+ // closeTab refuses to close the last open tab — only tear down when it+ // actually closed, or a live connection dies under a still-open tab+ if (tabs.closeTab(tabState.id)) {+ scrollService.cleanupScrollForTab(tabState.id)+ if (tabState.document.type === "gql-request") {+ gqlTabConn.cleanupTab(tabState.id)+ }+ inspectionService.deleteTabInspectorResult(tabState.id)+ }+ }+}++// Tear down GQL connections (the 7s schema-poll timer, any open subscription+// socket, and the per-tab context maps) for every tab `closeOtherTabs` is+// about to discard — it only removes them from the tab map, so without this+// each dropped gql-request tab leaks its poll loop and socket. Mirrors the+// single-tab cleanup in `removeTab`; `cleanupTab` is idempotent.+const cleanupDiscardedTabs = (keepTabID: string) => {+ for (const tab of tabs.getTabs()) {+ if (tab.id === keepTabID) continue+ if (tab.document.type === "gql-request") {+ gqlTabConn.cleanupTab(tab.id)+ }+ inspectionService.deleteTabInspectorResult(tab.id)}}@@ -272,6 +364,7 @@ const closeOtherTabsAction = (tabID: string) => {exceptedTabID.value = tabID} else {scrollService.cleanupAllScroll(tabID)+ cleanupDiscardedTabs(tabID)tabs.closeOtherTabs(tabID)}}@@ -288,12 +381,28 @@ const duplicateTab = (tabID: string) => {isDirty: true,})tabs.setActiveTab(newTab.id)+ } else if (tab.value && tab.value.document.type === "gql-request") {+ const doc = tab.value.document+ const newTab = tabs.createNewTab({+ type: "gql-request",+ request: {+ ...cloneDeep(doc.request),+ _ref_id: generateUniqueRefId("req"),+ },+ isDirty: true,+ cursorPosition: doc.cursorPosition ?? 0,+ // Like REST duplicates: no inheritedProperties (the copy is detached+ // from the source collection, `inherit` resolves to none until saved)+ // and no response/sub-tab preference+ })+ tabs.setActiveTab(newTab.id)}}const onResolveConfirmCloseAllTabs = () => {if (exceptedTabID.value) {scrollService.cleanupAllScroll(exceptedTabID.value)+ cleanupDiscardedTabs(exceptedTabID.value)tabs.closeOtherTabs(exceptedTabID.value)}confirmingCloseAllTabs.value = false@@ -303,23 +412,27 @@ const requestToRename = computed(() => {if (!renameTabID.value) return nullconst tab = tabs.getTabRef(renameTabID.value)- return tab.value.document.type === "request"- ? tab.value.document.request- : null+ if (tab.value.document.type === "request") {+ return tab.value.document.request+ } else if (tab.value.document.type === "gql-request") {+ return tab.value.document.request+ }+ return null})const openReqRenameModal = (tabID?: string) => {if (tabID) {const tab = tabs.getTabRef(tabID)+ const docType = tab.value.document.type- if (tab.value.document.type !== "request") return+ if (docType !== "request" && docType !== "gql-request") returnreqName.value = tab.value.document.request.namerenameTabID.value = tabID} else {const { id, document } = tabs.currentActiveTab.value- if (document.type !== "request") return+ if (document.type !== "request" && document.type !== "gql-request") returnreqName.value = document.request.namerenameTabID.value = id@@ -329,7 +442,11 @@ const openReqRenameModal = (tabID?: string) => {const renameReqName = () => {const tab = tabs.getTabRef(renameTabID.value ?? currentTabID.value)- if (tab.value && tab.value.document.type === "request") {+ if (+ tab.value &&+ (tab.value.document.type === "request" ||+ tab.value.document.type === "gql-request")+ ) {tab.value.document.request.name = reqName.valuetabs.updateTab(tab.value)}@@ -341,8 +458,15 @@ const renameReqName = () => {*/const onCloseConfirmSaveTab = () => {if (!savingRequest.value && confirmingCloseForTabID.value) {- tabs.closeTab(confirmingCloseForTabID.value)- inspectionService.deleteTabInspectorResult(confirmingCloseForTabID.value)+ const tabState = tabs.getTabRef(confirmingCloseForTabID.value).value+ // Only tear down when the tab actually closed (see removeTab)+ if (tabs.closeTab(confirmingCloseForTabID.value)) {+ scrollService.cleanupScrollForTab(confirmingCloseForTabID.value)+ if (tabState?.document.type === "gql-request") {+ gqlTabConn.cleanupTab(confirmingCloseForTabID.value)+ }+ inspectionService.deleteTabInspectorResult(confirmingCloseForTabID.value)+ }confirmingCloseForTabID.value = null}}@@ -350,17 +474,44 @@ const onCloseConfirmSaveTab = () => {/*** Called when the user confirms they want to save the tab*/-const onResolveConfirmSaveTab = () => {- if (tabs.currentActiveTab.value.document.saveContext) {- invokeAction("request-response.save")+const onResolveConfirmSaveTab = async () => {+ const closingTabID = confirmingCloseForTabID.value+ if (!closingTabID) return++ const tabState = tabs.getTabRef(closingTabID).value++ // Both save paths (the `request-response.save` handler and the Save As+ // modal) act on the active tab, so the tab being closed has to be focused+ // first — closing a dirty background tab would otherwise save the active+ // one. `nextTick` lets the newly active tab mount and bind its handler.+ if (currentTabID.value !== closingTabID) {+ tabs.setActiveTab(closingTabID)+ await nextTick()+ }- if (confirmingCloseForTabID.value) {- tabs.closeTab(confirmingCloseForTabID.value)- confirmingCloseForTabID.value = null- }- } else {+ // `HoppTabDocument` is a union — test-runner documents carry no+ // `saveContext`, so probe for the key instead of assuming it exists.+ const saveContext =+ "saveContext" in tabState.document+ ? tabState.document.saveContext+ : undefined++ if (!saveContext) {savingRequest.value = true+ return+ }++ invokeAction("request-response.save")++ // Only tear down when the tab actually closed (see removeTab)+ if (tabs.closeTab(closingTabID)) {+ scrollService.cleanupScrollForTab(closingTabID)+ if (tabState.document.type === "gql-request") {+ gqlTabConn.cleanupTab(closingTabID)+ }+ inspectionService.deleteTabInspectorResult(closingTabID)}+ confirmingCloseForTabID.value = null}/**@@ -369,14 +520,26 @@ const onResolveConfirmSaveTab = () => {const onSaveModalClose = () => {savingRequest.value = falseif (confirmingCloseForTabID.value) {- tabs.closeTab(confirmingCloseForTabID.value)+ const tabState = tabs.getTabRef(confirmingCloseForTabID.value).value+ // Only tear down when the tab actually closed (see removeTab)+ if (tabs.closeTab(confirmingCloseForTabID.value)) {+ scrollService.cleanupScrollForTab(confirmingCloseForTabID.value)+ if (tabState?.document.type === "gql-request") {+ gqlTabConn.cleanupTab(confirmingCloseForTabID.value)+ }+ inspectionService.deleteTabInspectorResult(confirmingCloseForTabID.value)+ }confirmingCloseForTabID.value = null}}const shareTabRequest = (tabID: string) => {const tab = tabs.getTabRef(tabID)- if (tab.value && tab.value.document.type === "request") {+ if (+ tab.value &&+ (tab.value.document.type === "request" ||+ tab.value.document.type === "gql-request")+ ) {if (currentUser.value) {invokeAction("share.request", {request: tab.value.document.request,@@ -409,8 +572,13 @@ defineActionHandler("rest.request.open", ({ doc }) => {tabs.createNewTab(doc)})+defineActionHandler("rest.gql-request.open", ({ doc }) => {+ tabs.createNewTab(doc)+})+defineActionHandler("request.rename", () => {- if (tabs.currentActiveTab.value.document.type === "request")+ const docType = tabs.currentActiveTab.value.document.type+ if (docType === "request" || docType === "gql-request")openReqRenameModal(tabs.currentActiveTab.value.id)})@@ -423,7 +591,10 @@ defineActionHandler("tab.close-current", () => {})defineActionHandler("tab.close-other", () => {- tabs.closeOtherTabs(currentTabID.value)+ // Route through closeOtherTabsAction so the keyboard shortcut gets the same+ // dirty-tab confirmation (and scroll/GQL cleanup) as the tab context menu,+ // instead of force-closing unsaved tabs.+ closeOtherTabsAction(currentTabID.value)})defineActionHandler("tab.open-new", addNewTab)diff --git a/packages/hoppscotch-common/src/pages/oauth.vue b/packages/hoppscotch-common/src/pages/oauth.vueindex 6b2f7a2e3..0d9cbf1c5 100644--- a/packages/hoppscotch-common/src/pages/oauth.vue+++ b/packages/hoppscotch-common/src/pages/oauth.vue@@ -11,7 +11,7 @@ import { useToast } from "~/composables/toast"import { useService } from "dioc/vue"import * as E from "fp-ts/Either"import { onMounted } from "vue"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { useRouter } from "vue-router"@@ -29,7 +29,7 @@ const toast = useToast()const gqlTabs = useService(GQLTabService)const persistenceService = useService(PersistenceService)-const restTabs = useService(RESTTabService)+const workspaceTabs = useService(WorkspaceTabsService)function translateOAuthRedirectError(error: string) {switch (error) {@@ -114,7 +114,7 @@ onMounted(async () => {}const routeToRedirect = source === "GraphQL" ? "/graphql" : "/"- const tabService = source === "GraphQL" ? gqlTabs : restTabs+ const tabService = source === "GraphQL" ? gqlTabs : workspaceTabsif (tabService.currentActiveTab.value.document.request.auth.authType ===diff --git a/packages/hoppscotch-common/src/pages/r/_id.vue b/packages/hoppscotch-common/src/pages/r/_id.vueindex a14698b7c..c78d14025 100644--- a/packages/hoppscotch-common/src/pages/r/_id.vue+++ b/packages/hoppscotch-common/src/pages/r/_id.vue@@ -197,7 +197,13 @@import { computed, onMounted, ref, watch } from "vue"import { useRoute, useRouter } from "vue-router"import * as E from "fp-ts/Either"-import { safelyExtractRESTRequest } from "@hoppscotch/data"+import {+ HoppGQLRequest,+ HoppRESTRequest,+ isGQLRequest,+ safelyExtractRESTRequest,+ translateToGQLRequest,+} from "@hoppscotch/data"import { useGQLQuery } from "@composables/graphql"import { useI18n } from "@composables/i18n"import {@@ -210,19 +216,24 @@ import IconHome from "~icons/lucide/home"import IconRefreshCW from "~icons/lucide/refresh-cw"import { getDefaultRESTRequest } from "~/helpers/rest/default"import { platform } from "~/platform"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { useService } from "dioc/vue"import { invokeAction } from "~/helpers/actions"import { useColorMode } from "~/composables/theming"import { useReadonlyStream } from "~/composables/stream"import { until } from "@vueuse/core"+const isGQLShortcodePayload = (req: unknown): boolean =>+ !!req &&+ typeof req === "object" &&+ isGQLRequest(req as HoppRESTRequest | HoppGQLRequest)+const route = useRoute()const router = useRouter()const t = useI18n()-const tabs = useService(RESTTabService)+const tabs = useService(WorkspaceTabsService)const invalidLink = ref(false)const sharedRequestID = ref("")@@ -288,11 +299,22 @@ const addRequestToTab = () => {const request: unknown = JSON.parse(data.right.shortcode?.request as string)- tabs.createNewTab({- type: "request",- request: safelyExtractRESTRequest(request, getDefaultRESTRequest()),- isDirty: false,- })+ if (isGQLShortcodePayload(request)) {+ // Versioned parser (safeParse + migrations, default fallback) — same+ // as `share/Request.vue` / `PublishedDocs.ts` for identical payloads+ tabs.createNewTab({+ type: "gql-request",+ request: translateToGQLRequest(request),+ isDirty: false,+ cursorPosition: 0,+ })+ } else {+ tabs.createNewTab({+ type: "request",+ request: safelyExtractRESTRequest(request, getDefaultRESTRequest()),+ isDirty: false,+ })+ }router.push({ path: "/" })}diff --git a/packages/hoppscotch-common/src/pages/settings.vue b/packages/hoppscotch-common/src/pages/settings.vueindex 091a5abee..00954afe3 100644--- a/packages/hoppscotch-common/src/pages/settings.vue+++ b/packages/hoppscotch-common/src/pages/settings.vue@@ -182,6 +182,14 @@{{ t("settings.enable_experimental_documentation") }}</HoppSmartToggle></div>+ <div class="flex items-center">+ <HoppSmartToggle+ :on="ENABLE_GQL_IN_REST_WORKSPACE"+ @change="toggleSetting('ENABLE_GQL_IN_REST_WORKSPACE')"+ >+ {{ t("settings.enable_gql_in_rest_workspace") }}+ </HoppSmartToggle>+ </div></div></section></div>@@ -334,6 +342,7 @@ const ENABLE_EXPERIMENTAL_MOCK_SERVERS = useSetting(const ENABLE_EXPERIMENTAL_DOCUMENTATION = useSetting("ENABLE_EXPERIMENTAL_DOCUMENTATION")+const ENABLE_GQL_IN_REST_WORKSPACE = useSetting("ENABLE_GQL_IN_REST_WORKSPACE")const supportedNamingStyles = [{diff --git a/packages/hoppscotch-common/src/pages/view/_id/_version.vue b/packages/hoppscotch-common/src/pages/view/_id/_version.vueindex 40374dbb7..0f499aa94 100644--- a/packages/hoppscotch-common/src/pages/view/_id/_version.vue+++ b/packages/hoppscotch-common/src/pages/view/_id/_version.vue@@ -49,6 +49,7 @@ import IconAlertCircle from "~icons/lucide/alert-circle"import {Environment,HoppCollection,+ HoppGQLRequest,HoppRESTRequest,translateToNewEnvironmentVariables,} from "@hoppscotch/data"@@ -108,7 +109,7 @@ const environmentEnabled = ref(true)type DocumentationItem = {id: stringtype: "folder" | "request"- item: HoppCollection | HoppRESTRequest+ item: HoppCollection | HoppRESTRequest | HoppGQLRequestinheritedProperties: HoppInheritedProperty}@@ -185,14 +186,17 @@ const flattenCollection = (// collectionFolderToHoppCollection ensures all requests are converted to the latest versionif (collection.requests && collection.requests.length > 0) {- ;(collection.requests as HoppRESTRequest[]).forEach((request) => {- items.push({- id: request.id || (request as any)._ref_id || `request-${request.name}`,- type: "request",- item: request,- inheritedProperties: currentInheritedProps,- })- })+ ;(collection.requests as (HoppRESTRequest | HoppGQLRequest)[]).forEach(+ (request) => {+ items.push({+ id:+ request.id || (request as any)._ref_id || `request-${request.name}`,+ type: "request",+ item: request,+ inheritedProperties: currentInheritedProps,+ })+ }+ )}return itemsdiff --git a/packages/hoppscotch-common/src/platform/backend.ts b/packages/hoppscotch-common/src/platform/backend.tsindex bdbf011df..5b8cb4c42 100644--- a/packages/hoppscotch-common/src/platform/backend.ts+++ b/packages/hoppscotch-common/src/platform/backend.ts@@ -1,4 +1,4 @@-import { HoppRESTRequest } from "@hoppscotch/data"+import { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"import * as TE from "fp-ts/TaskEither"import * as E from "fp-ts/lib/Either"@@ -75,7 +75,7 @@ export type BackendPlatformDef = {>createShortcode: (- request: HoppRESTRequest,+ request: HoppRESTRequest | HoppGQLRequest,properties?: string) => TE.TaskEither<GQLError<string>, CreateShortcodeMutation>diff --git a/packages/hoppscotch-common/src/platform/std/backend.ts b/packages/hoppscotch-common/src/platform/std/backend.tsindex f90bc8ecb..fbbb52c33 100644--- a/packages/hoppscotch-common/src/platform/std/backend.ts+++ b/packages/hoppscotch-common/src/platform/std/backend.ts@@ -2,7 +2,7 @@ import { useGQLQuery } from "~/composables/graphql"import { TeamName } from "~/helpers/backend/types/TeamName"import { BackendPlatformDef } from "~/platform/backend"-import { HoppRESTRequest } from "@hoppscotch/data"+import { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"import { runGQLQuery, runMutation } from "~/helpers/backend/GQLClient"import { Email } from "~/helpers/backend/types/Email"@@ -133,7 +133,7 @@ export const acceptTeamInvitation = <AcceptTeamInvitationErrors extends string>(}export const createShortcode = (- request: HoppRESTRequest,+ request: HoppRESTRequest | HoppGQLRequest,properties?: string) => {return runMutation<diff --git a/packages/hoppscotch-common/src/platform/std/kernel-interceptors/proxy/index.ts b/packages/hoppscotch-common/src/platform/std/kernel-interceptors/proxy/index.tsindex e331abb36..e5aa67c75 100644--- a/packages/hoppscotch-common/src/platform/std/kernel-interceptors/proxy/index.ts+++ b/packages/hoppscotch-common/src/platform/std/kernel-interceptors/proxy/index.ts@@ -215,8 +215,7 @@ export class ProxyKernelInterceptorServicelet innerCancel: (() => Promise<void>) | null = nulllet cancelled = falselet resolveCancelled:- | ((result: E.Either<RelayError, RelayResponse>) => void)- | null = null+ ((result: E.Either<RelayError, RelayResponse>) => void) | null = nullconst cancelledResult: E.Either<RelayError, RelayResponse> = E.left({kind: "abort",diff --git a/packages/hoppscotch-common/src/platform/tab.ts b/packages/hoppscotch-common/src/platform/tab.tsindex 83e6a6677..5b0b35f82 100644--- a/packages/hoppscotch-common/src/platform/tab.ts+++ b/packages/hoppscotch-common/src/platform/tab.ts@@ -1,6 +1,6 @@import { PersistableTabState } from "~/services/tab"import { HoppUser } from "./auth"-import { HoppTabDocument } from "~/helpers/rest/document"+import { HoppTabDocument } from "~/helpers/tab/document"export type TabStatePlatformDef = {loadTabStateFromSync: () => Promise<PersistableTabState<HoppTabDocument> | null>diff --git a/packages/hoppscotch-common/src/services/__tests__/workspace.service.spec.ts b/packages/hoppscotch-common/src/services/__tests__/workspace.service.spec.tsindex 4f8c974c1..0524f1d67 100644--- a/packages/hoppscotch-common/src/services/__tests__/workspace.service.spec.ts+++ b/packages/hoppscotch-common/src/services/__tests__/workspace.service.spec.ts@@ -2,6 +2,10 @@ import { describe, expect, vi, it, beforeEach, afterEach } from "vitest"import { TestContainer } from "dioc/testing"import { WorkspaceService } from "../workspace.service"import { setPlatformDef } from "~/platform"+import {+ getSelectedEnvironmentIndex,+ setSelectedEnvironmentIndex,+} from "~/newstore/environments"import { BehaviorSubject } from "rxjs"import { effectScope, nextTick } from "vue"@@ -49,6 +53,18 @@ vi.mock("../documentation.service", () => ({},}))+// Mock WorkspaceTabsService — it indirectly pulls in PersistenceService which+// triggers an i18n getService() call at module init, breaking this test's setup.+vi.mock("../tab/workspace-tabs", () => ({+ WorkspaceTabsService: class MockWorkspaceTabsService {+ static readonly ID = "WORKSPACE_TABS_SERVICE"++ attachToWorkspace = vi.fn()++ onServiceInit = vi.fn()+ },+}))+describe("WorkspaceService", () => {const platformMock = {auth: {@@ -137,6 +153,149 @@ describe("WorkspaceService", () => {role: null,})})++ it("is a no-op when re-selecting the current workspace", () => {+ const container = new TestContainer()+ const service = container.bind(WorkspaceService)++ service.changeWorkspace({+ type: "team",+ teamID: "test",+ teamName: "test",+ role: null,+ })+ const before = service.currentWorkspace.value++ // Fresh-but-identical object must not retrigger workspace watchers+ service.changeWorkspace({+ type: "team",+ teamID: "test",+ teamName: "test",+ role: null,+ })++ expect(service.currentWorkspace.value).toBe(before)+ })++ it("resets a selected team environment when switching to the personal workspace", () => {+ const container = new TestContainer()+ const service = container.bind(WorkspaceService)++ service.changeWorkspace({+ type: "team",+ teamID: "team-a",+ teamName: "Team A",+ role: null,+ })+ setSelectedEnvironmentIndex({+ type: "TEAM_ENV",+ teamID: "team-a",+ teamEnvID: "env-1",+ environment: { v: 2, id: "env-1", name: "Team Env", variables: [] },+ })++ service.changeWorkspace({ type: "personal" })++ expect(getSelectedEnvironmentIndex()).toEqual({+ type: "NO_ENV_SELECTED",+ })+ })++ it("resets a selected team environment when switching to a different team", () => {+ const container = new TestContainer()+ const service = container.bind(WorkspaceService)++ setSelectedEnvironmentIndex({+ type: "TEAM_ENV",+ teamID: "team-a",+ teamEnvID: "env-1",+ environment: { v: 2, id: "env-1", name: "Team Env", variables: [] },+ })++ service.changeWorkspace({+ type: "team",+ teamID: "team-b",+ teamName: "Other Team",+ role: null,+ })++ expect(getSelectedEnvironmentIndex()).toEqual({+ type: "NO_ENV_SELECTED",+ })+ })++ it("keeps the selected team environment when switching within the same team", () => {+ const container = new TestContainer()+ const service = container.bind(WorkspaceService)++ setSelectedEnvironmentIndex({+ type: "TEAM_ENV",+ teamID: "team-a",+ teamEnvID: "env-1",+ environment: { v: 2, id: "env-1", name: "Team Env", variables: [] },+ })++ service.changeWorkspace({+ type: "team",+ teamID: "team-a",+ teamName: "Same Team",+ role: null,+ })++ expect(getSelectedEnvironmentIndex().type).toBe("TEAM_ENV")+ })++ it("keeps a selected personal environment when switching workspaces", () => {+ const container = new TestContainer()+ const service = container.bind(WorkspaceService)++ setSelectedEnvironmentIndex({ type: "MY_ENV", index: 0 })++ service.changeWorkspace({ type: "personal" })++ expect(getSelectedEnvironmentIndex()).toEqual({+ type: "MY_ENV",+ index: 0,+ })+ })+ })++ describe("logout", () => {+ it("falls back to the personal workspace when the user logs out of a team", async () => {+ const userStream = new BehaviorSubject<unknown>({ uid: "user-1" })+ platformMock.auth.getCurrentUserStream.mockReturnValue(userStream)+ platformMock.auth.getCurrentUser.mockReturnValue({ uid: "user-1" })++ const container = new TestContainer()+ const service = container.bind(WorkspaceService)++ service.changeWorkspace({+ type: "team",+ teamID: "team-a",+ teamName: "Team A",+ role: null,+ })+ expect(service.currentWorkspace.value.type).toBe("team")++ userStream.next(null)+ await nextTick()++ expect(service.currentWorkspace.value).toEqual({ type: "personal" })+ })++ it("leaves a personal workspace untouched on logout", async () => {+ const userStream = new BehaviorSubject<unknown>({ uid: "user-1" })+ platformMock.auth.getCurrentUserStream.mockReturnValue(userStream)+ platformMock.auth.getCurrentUser.mockReturnValue({ uid: "user-1" })++ const container = new TestContainer()+ const service = container.bind(WorkspaceService)++ userStream.next(null)+ await nextTick()++ expect(service.currentWorkspace.value).toEqual({ type: "personal" })+ })})describe("acquireTeamListAdapter", () => {diff --git a/packages/hoppscotch-common/src/services/context-menu/menu/__tests__/url.menu.spec.ts b/packages/hoppscotch-common/src/services/context-menu/menu/__tests__/url.menu.spec.tsindex 80496db5a..684fc8278 100644--- a/packages/hoppscotch-common/src/services/context-menu/menu/__tests__/url.menu.spec.ts+++ b/packages/hoppscotch-common/src/services/context-menu/menu/__tests__/url.menu.spec.ts@@ -1,6 +1,6 @@import { TestContainer } from "dioc/testing"import { describe, expect, it, vi } from "vitest"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { ContextMenuService } from "../.."import { URLMenuService } from "../url.menu"import { getDefaultRESTRequest } from "~/helpers/rest/default"@@ -57,7 +57,7 @@ describe("URLMenuService", () => {it("should call the openNewTab function when action is called and a new hoppscotch tab is opened", () => {const container = new TestContainer()const createNewTabFn = vi.fn()- container.bindMock(RESTTabService, {+ container.bindMock(WorkspaceTabsService, {createNewTab: createNewTabFn,})const url = container.bind(URLMenuService)diff --git a/packages/hoppscotch-common/src/services/context-menu/menu/parameter.menu.ts b/packages/hoppscotch-common/src/services/context-menu/menu/parameter.menu.tsindex dfb03a2eb..d89dca356 100644--- a/packages/hoppscotch-common/src/services/context-menu/menu/parameter.menu.ts+++ b/packages/hoppscotch-common/src/services/context-menu/menu/parameter.menu.ts@@ -8,7 +8,7 @@ import {import { markRaw, ref } from "vue"import IconArrowDownRight from "~icons/lucide/arrow-down-right"import { getI18n } from "~/modules/i18n"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { getService } from "~/modules/dioc"//regex containing both url and parameter@@ -87,15 +87,17 @@ export class ParameterMenuService extends Service implements ContextMenu {queryParams.push({ key, value, active: true })}- const tabService = getService(RESTTabService)-- if (tabService.currentActiveTab.value.document.type === "test-runner")- return+ const tabService = getService(WorkspaceTabsService)+ const doc = tabService.currentActiveTab.value.documentconst currentActiveRequest =- tabService.currentActiveTab.value.document.type === "request"- ? tabService.currentActiveTab.value.document.request- : tabService.currentActiveTab.value.document.response.originalRequest+ doc.type === "request"+ ? doc.request+ : doc.type === "example-response"+ ? doc.response?.originalRequest+ : null++ if (!currentActiveRequest) return// add the parameters to the current request parameterscurrentActiveRequest.params = [diff --git a/packages/hoppscotch-common/src/services/context-menu/menu/url.menu.ts b/packages/hoppscotch-common/src/services/context-menu/menu/url.menu.tsindex 9d6c5f28d..8676cba1f 100644--- a/packages/hoppscotch-common/src/services/context-menu/menu/url.menu.ts+++ b/packages/hoppscotch-common/src/services/context-menu/menu/url.menu.ts@@ -2,7 +2,7 @@ import { Service } from "dioc"import { markRaw, ref } from "vue"import { getDefaultRESTRequest } from "~/helpers/rest/default"import { getI18n } from "~/modules/i18n"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import IconCopyPlus from "~icons/lucide/copy-plus"import IconLock from "~icons/lucide/lock"import IconUnlock from "~icons/lucide/unlock"@@ -60,7 +60,7 @@ export class URLMenuService extends Service implements ContextMenu {public readonly menuID = "url"private readonly contextMenu = this.bind(ContextMenuService)- private readonly restTab = this.bind(RESTTabService)+ private readonly workspaceTab = this.bind(WorkspaceTabsService)override onServiceInit() {this.contextMenu.registerMenu(this)@@ -77,7 +77,7 @@ export class URLMenuService extends Service implements ContextMenu {endpoint: url,}- this.restTab.createNewTab({+ this.workspaceTab.createNewTab({type: "request",request: request,isDirty: false,@@ -90,7 +90,7 @@ export class URLMenuService extends Service implements ContextMenu {* @param replacement The replacement text (encoded or decoded)*/private replaceSelectedText(selectedText: string, replacement: string) {- const currentTab = this.restTab.currentActiveTab.value+ const currentTab = this.workspaceTab.currentActiveTab.valueif (!currentTab || currentTab.document.type !== "request") {returndiff --git a/packages/hoppscotch-common/src/services/documentation.service.ts b/packages/hoppscotch-common/src/services/documentation.service.tsindex 8008197ab..771cbacea 100644--- a/packages/hoppscotch-common/src/services/documentation.service.ts+++ b/packages/hoppscotch-common/src/services/documentation.service.ts@@ -1,6 +1,10 @@import { Service } from "dioc"import { reactive, computed, ref } from "vue"-import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data"+import {+ HoppCollection,+ HoppGQLRequest,+ HoppRESTRequest,+} from "@hoppscotch/data"import * as E from "fp-ts/Either"import { platform } from "~/platform"@@ -55,12 +59,11 @@ export interface RequestDocumentationItem extends BaseDocumentationItem {folderPath: stringrequestID?: string // For team requestsrequestIndex?: number // For personal requests- requestData: HoppRESTRequest+ requestData: HoppRESTRequest | HoppGQLRequest}export type DocumentationItem =- | CollectionDocumentationItem- | RequestDocumentationItem+ CollectionDocumentationItem | RequestDocumentationItem/*** Base options for setting documentation@@ -89,7 +92,7 @@ export interface SetRequestDocumentationOptions extends BaseDocumentationOptionsfolderPath: stringrequestID?: string // For team requestsrequestIndex?: number // For personal requests- requestData: HoppRESTRequest+ requestData: HoppRESTRequest | HoppGQLRequest}/**diff --git a/packages/hoppscotch-common/src/services/gql-query-builder.service.ts b/packages/hoppscotch-common/src/services/gql-query-builder.service.tsnew file mode 100644index 000000000..d170d43bc--- /dev/null+++ b/packages/hoppscotch-common/src/services/gql-query-builder.service.ts@@ -0,0 +1,457 @@+import { Service } from "dioc"+import {+ ArgumentNode,+ DocumentNode,+ FieldNode,+ getNamedType,+ GraphQLArgument,+ GraphQLField,+ GraphQLInterfaceType,+ GraphQLObjectType,+ GraphQLType,+ isInterfaceType,+ isLeafType,+ isNonNullType,+ isObjectType,+ Kind,+ OperationDefinitionNode,+ OperationTypeNode,+ print,+ SelectionNode,+ ValueNode,+} from "graphql"+import { ref } from "vue"+import { WorkspaceTabsService } from "./tab/workspace-tabs"+import {+ ExplorerFieldDef,+ ExplorerNavStackItem,+ useExplorer,+} from "~/helpers/graphql/explorer"++type Mutable<T> = {+ -readonly [K in keyof T]: T[K]+}++type OperationResult = {+ append?: boolean+ document: DocumentNode | null+ fieldLocation?: {+ start: number+ end: number+ }+}++/**+ * Schema-explorer → query-editor insertion logic for the unified workspace's+ * GraphQL flow.+ *+ * Mirrors the legacy `useQuery()` composable in `helpers/graphql/query.ts`+ * (which still backs the standalone `/graphql` page unchanged), but:+ * - reads/writes the active tab via `WorkspaceTabsService` instead of+ * `GQLTabService`, so the "+" button on a field writes into the unified+ * workspace's `gql-request` tab;+ * - emits **required** arguments only (no `(filter: "null")` placeholders+ * for optional args);+ * - auto-expands the field's return-type leaves so clicking `+` on+ * `countries` produces `countries { code name capital ... }` instead of+ * a bare `countries` with no selection set;+ * - emits `ValueNode`s of the correct kind for default values+ * (`Int → IntValue`, `Boolean → BooleanValue`, unknown → `NullValue`)+ * rather than stringifying everything as `StringValue`.+ */+export class GQLQueryBuilderService extends Service {+ public static readonly ID = "GQL_QUERY_BUILDER_SERVICE"++ private readonly workspaceTabs = this.bind(WorkspaceTabsService)++ public readonly updatedQuery = ref("")+ public readonly cursorPosition = ref({ line: 0, ch: 1 })+ public readonly operations = ref<OperationDefinitionNode[]>([])++ private getActiveGQLDoc() {+ const tab = this.workspaceTabs.currentActiveTab.value+ return tab?.document.type === "gql-request" ? tab.document : undefined+ }++ private createDefaultValueNode(type: GraphQLType): ValueNode {+ const namedType = getNamedType(type)+ switch (namedType.name) {+ case "String":+ case "ID":+ return { kind: Kind.STRING, value: "" }+ case "Int":+ return { kind: Kind.INT, value: "0" }+ case "Float":+ return { kind: Kind.FLOAT, value: "0.0" }+ case "Boolean":+ return { kind: Kind.BOOLEAN, value: false }+ default:+ return { kind: Kind.NULL }+ }+ }++ private getOperationTypeNode(name: string): OperationTypeNode {+ const operationTypes: Record<string, OperationTypeNode> = {+ Query: OperationTypeNode.QUERY,+ Mutation: OperationTypeNode.MUTATION,+ Subscription: OperationTypeNode.SUBSCRIPTION,+ }+ return operationTypes[name] || OperationTypeNode.QUERY+ }++ private getOperation(cursor: number) {+ return this.operations.value.find(+ ({ loc }) => loc && cursor >= loc.start && cursor <= loc.end+ )+ }++ private createArgumentNode(argName: string, type: GraphQLType): ArgumentNode {+ return {+ kind: Kind.ARGUMENT,+ name: { kind: Kind.NAME, value: argName },+ value: this.createDefaultValueNode(type),+ }+ }++ /**+ * Expand the scalar/enum (leaf) children of an object/interface return type+ * into a default selection set. Nested object children are intentionally+ * skipped — users drill in via the explorer to add them.+ */+ private buildDefaultSelections(type: GraphQLType): SelectionNode[] {+ const namedType = getNamedType(type)+ if (!isObjectType(namedType) && !isInterfaceType(namedType)) return []+ const fields = (+ namedType as GraphQLObjectType | GraphQLInterfaceType+ ).getFields()+ return Object.values(fields)+ .filter((f) => isLeafType(getNamedType(f.type)))+ .map((f) => this.createFieldNode(f.name, undefined))+ }++ private createFieldNode(+ name: string,+ args: readonly GraphQLArgument[] | undefined,+ returnType?: GraphQLType,+ forceEmptySelectionSet = false+ ): Mutable<FieldNode> {+ const requiredArgs = args?.filter((arg) => isNonNullType(arg.type)) ?? []+ const selections = returnType ? this.buildDefaultSelections(returnType) : []++ return {+ kind: Kind.FIELD,+ name: { kind: Kind.NAME, value: name },+ arguments: requiredArgs.map((arg) =>+ this.createArgumentNode(arg.name, arg.type)+ ),+ directives: [],+ selectionSet:+ selections.length > 0 || forceEmptySelectionSet+ ? { kind: Kind.SELECTION_SET, selections }+ : undefined,+ }+ }++ private processOperation(+ navItems: ExplorerNavStackItem[],+ existingOperation?: OperationDefinitionNode,+ isArgument = false+ ): OperationResult {+ const queryPath = navItems.slice(2, isArgument ? -1 : undefined)+ const argumentItem = isArgument ? navItems[navItems.length - 1] : null+ const lastItem = queryPath[queryPath.length - 1]+ const requestedOperationType = this.getOperationTypeNode(navItems[1].name)++ if (+ !existingOperation ||+ existingOperation.operation !== requestedOperationType+ ) {+ const lastFieldDef = lastItem.def as+ GraphQLField<unknown, unknown> | undefined+ let currentSelection = this.createFieldNode(+ lastItem.name,+ isArgument && argumentItem+ ? [argumentItem.def as GraphQLArgument]+ : lastFieldDef?.args,+ lastFieldDef?.type+ )++ for (let i = queryPath.length - 2; i >= 0; i--) {+ const item = queryPath[i]+ const parentField = this.createFieldNode(+ item.name,+ (item.def as GraphQLField<unknown, unknown> | undefined)?.args,+ undefined,+ true+ )+ parentField.selectionSet!.selections = [currentSelection]+ currentSelection = parentField+ }++ return {+ document: {+ kind: Kind.DOCUMENT,+ definitions: [+ {+ kind: Kind.OPERATION_DEFINITION,+ operation: requestedOperationType,+ name: { kind: Kind.NAME, value: queryPath[0].name },+ variableDefinitions: [],+ directives: [],+ selectionSet: {+ kind: Kind.SELECTION_SET,+ selections: [currentSelection],+ },+ },+ ],+ },+ }+ }++ let currentSelectionSet = existingOperation.selectionSet+ let fieldLocation: { start: number; end: number } | undefined+ let append = false++ if (+ requestedOperationType === OperationTypeNode.SUBSCRIPTION &&+ requestedOperationType === existingOperation?.operation+ ) {+ // Selections can be inline fragments or fragment spreads, which carry no+ // `name` — only a FieldNode is comparable against the query path.+ const [firstSelection] = existingOperation.selectionSet.selections+ const existingTopField =+ firstSelection?.kind === Kind.FIELD ? firstSelection : undefined++ if (+ existingTopField?.name.value !==+ (queryPath && queryPath[0] && queryPath[0]?.name)+ ) {+ append = true+ currentSelectionSet.selections = []+ }+ }++ for (let i = 0; i < queryPath.length; i++) {+ const item = queryPath[i]+ const isLastItem = i === queryPath.length - 1++ const existingFieldIndex = currentSelectionSet.selections.findIndex(+ (selection): selection is FieldNode =>+ selection.kind === Kind.FIELD && selection.name.value === item.name+ )++ if (existingFieldIndex !== -1) {+ const existingField = currentSelectionSet.selections[+ existingFieldIndex+ ] as Mutable<FieldNode> & { arguments?: ArgumentNode[] }++ if (isLastItem) {+ if (isArgument && argumentItem) {+ const argIndex =+ existingField.arguments?.findIndex(+ (arg) => arg.name.value === argumentItem.name+ ) ?? -1++ if (argIndex !== -1) {+ existingField.arguments?.splice(argIndex, 1)+ } else {+ const newArg = this.createArgumentNode(+ argumentItem.name,+ (argumentItem.def as any)?.type+ )+ existingField.arguments = existingField.arguments || []+ existingField.arguments.push(newArg)+ }+ } else {+ ;(+ currentSelectionSet.selections as Mutable<SelectionNode>[]+ ).splice(existingFieldIndex, 1)+ }++ if (existingField.loc) {+ fieldLocation = {+ start: existingField.loc.start,+ end: existingField.loc.end,+ }+ }+ break+ }++ if (!existingField.selectionSet) {+ existingField.selectionSet = {+ kind: Kind.SELECTION_SET,+ selections: [],+ }+ }++ currentSelectionSet = existingField.selectionSet ?? {+ kind: Kind.SELECTION_SET,+ selections: [],+ }+ } else {+ const itemFieldDef = item.def as+ GraphQLField<unknown, unknown> | undefined+ const newField = this.createFieldNode(+ item.name,+ isLastItem && isArgument && argumentItem+ ? [argumentItem.def as GraphQLArgument]+ : itemFieldDef?.args,+ isLastItem ? itemFieldDef?.type : undefined,+ !isLastItem+ )++ if (currentSelectionSet.loc) {+ fieldLocation = {+ start: currentSelectionSet.loc.end - 1,+ end: currentSelectionSet.loc.end - 1,+ }+ }++ if (!isLastItem) {+ newField.selectionSet = {+ kind: Kind.SELECTION_SET,+ selections: [],+ }+ }++ ;(currentSelectionSet.selections as Mutable<FieldNode[]>).push(newField)++ if (!isLastItem) {+ currentSelectionSet = newField.selectionSet!+ }+ }+ }++ return {+ document:+ existingOperation.selectionSet.selections.length === 0+ ? null+ : {+ kind: Kind.DOCUMENT,+ definitions: [existingOperation],+ },+ fieldLocation,+ append,+ }+ }++ private handleOperation(item: ExplorerFieldDef, isArgument = false) {+ const activeDoc = this.getActiveGQLDoc()+ if (!activeDoc) return++ const { navStack } = useExplorer()+ const currentQuery = activeDoc.request.query || ""+ const selectedOperation = this.getOperation(activeDoc.cursorPosition || 0)+ const navItems = [...navStack.value, { name: item.name, def: item }]++ const result = this.processOperation(+ navItems as ExplorerNavStackItem[],+ selectedOperation,+ isArgument+ )++ const newQuery = result.document+ ? print(result.document.definitions[0])+ : "\n"++ if (+ !selectedOperation ||+ selectedOperation.operation !==+ this.getOperationTypeNode(navItems[1].name) ||+ result.append+ ) {+ this.updatedQuery.value = currentQuery.trim()+ ? `${currentQuery}\n\n${newQuery}`+ : newQuery+ this.cursorPosition.value = {+ line: currentQuery.split("\n").length + (currentQuery.trim() ? 2 : 1),+ ch: -1,+ }+ return+ }++ this.updatedQuery.value = currentQuery.replace(+ currentQuery.substring(+ selectedOperation.loc!.start,+ selectedOperation.loc!.end+ ),+ newQuery+ )++ if (result.fieldLocation) {+ const precedingText = currentQuery.substring(+ 0,+ result.fieldLocation.start+ )+ const lines = precedingText.split("\n")+ this.cursorPosition.value = {+ line: lines.length - 1,+ ch: -1,+ }+ }+ }++ public handleAddField(field: ExplorerFieldDef) {+ this.handleOperation(field)+ }++ public handleAddArgument(arg: ExplorerFieldDef) {+ this.handleOperation(arg, true)+ }++ public isFieldInOperation(item: ExplorerFieldDef): boolean {+ const { navStack } = useExplorer()+ const operation = this.getOperation(+ this.getActiveGQLDoc()?.cursorPosition || 0+ )+ if (!operation) return false++ const navPath = navStack.value.slice(2)+ let currentSelections = operation.selectionSet.selections++ for (let i = 0; i < navPath.length; i++) {+ const pathItem = navPath[i]+ const foundField = currentSelections.find(+ (selection) =>+ selection.kind === Kind.FIELD &&+ selection.name.value === pathItem.name+ ) as FieldNode | undefined++ if (!foundField?.selectionSet) return false++ currentSelections = foundField.selectionSet.selections+ }++ return currentSelections.some((selection) => {+ if (selection.kind !== Kind.FIELD) return false+ return selection.name.value === item.name+ })+ }++ public isArgumentInOperation(item: ExplorerFieldDef): boolean {+ const activeDoc = this.getActiveGQLDoc()+ if (!activeDoc) return false+ const cursor = activeDoc.cursorPosition ?? 0+ const operation = this.getOperation(cursor)+ if (!operation) return false++ let args: ArgumentNode[] = []++ operation.selectionSet.selections.forEach((selection) => {+ if (selection.kind === Kind.FIELD) {+ const fieldNode = selection as FieldNode+ if (+ fieldNode.loc &&+ fieldNode.loc.start <= cursor &&+ fieldNode.loc.end >= cursor+ ) {+ args = [...(fieldNode.arguments || [])]+ }+ }+ })++ if (args.length === 0) return false++ return args.some((arg) => arg.name.value === item.name)+ }+}diff --git a/packages/hoppscotch-common/src/services/gql-tab-connection.service.ts b/packages/hoppscotch-common/src/services/gql-tab-connection.service.tsnew file mode 100644index 000000000..31246ad2c--- /dev/null+++ b/packages/hoppscotch-common/src/services/gql-tab-connection.service.ts@@ -0,0 +1,1759 @@+import {+ HoppGQLAuth,+ HoppGQLRequest,+ HoppRESTAuth,+ HoppRESTHeaders,+ HoppRESTRequest,+ makeGQLRequest,+} from "@hoppscotch/data"+import { OperationType } from "@urql/core"+import * as E from "fp-ts/Either"+import {+ generateAuthHeaders,+ generateAuthParams,+} from "~/helpers/auth/auth-types"+import { getDefaultRESTRequest } from "~/helpers/rest/default"+import {+ GraphQLSchema,+ buildClientSchema,+ getIntrospectionQuery,+ printSchema,+} from "graphql"+import { Service } from "dioc"+import {+ Component,+ ComputedRef,+ Ref,+ computed,+ effectScope,+ ref,+ shallowReactive,+ watch,+} from "vue"+import { useToast } from "~/composables/toast"+import { getI18n } from "~/modules/i18n"++import { addGraphqlHistoryEntry, makeGQLHistoryEntry } from "~/newstore/history"++import { KernelInterceptorService } from "~/services/kernel-interceptor.service"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"++import { MediaType, content, Method, RelayRequest } from "@hoppscotch/kernel"+import { GQLRequest } from "~/helpers/kernel/gql/request"+import { GQLResponse } from "~/helpers/kernel/gql/response"++import { useExplorer } from "~/helpers/graphql/explorer"++import { getEffectiveHoppGQLRequest } from "~/helpers/utils/EffectiveURL"+import { getAggregateEnvsWithCurrentValue } from "~/newstore/environments"+import { transformInheritedCollectionVariablesToAggregateEnv } from "~/helpers/utils/inheritedCollectionVarTransformer"+import {+ captureInitialEnvironmentState,+ emptyInitialEnvironmentState,+ combineEnvVariables,+ delegatePreRequestScriptRunner,+ filterNonEmptyEnvironmentVariables,+ hasEnvironmentChanges,+ runPostRequestScript,+ translateToSandboxTestResults,+ updateEnvsAfterTestScript,+} from "~/helpers/RequestRunner"+import { SandboxTestResult } from "@hoppscotch/js-sandbox"+import { hasActualScript } from "@hoppscotch/js-sandbox/scripting"+import { HoppTestResult } from "~/helpers/types/HoppTestResult"+import type { Environment } from "@hoppscotch/data"+import type { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"++// --- Types (defined locally so new-flow consumers don't depend on connection.ts) ---++export type ConnectionState =+ "CONNECTING" | "CONNECTED" | "DISCONNECTED" | "ERROR"++export type SubscriptionState = "SUBSCRIBING" | "SUBSCRIBED" | "UNSUBSCRIBED"++export type GQLResponseEvent =+ | {+ type: "response"+ time: number+ operationName: string | undefined+ operationType: OperationType+ data: string+ rawQuery?: RunQueryOptions+ document?: {+ type: string+ statusCode: number+ statusText: string+ meta: {+ responseSize: number+ responseDuration: number+ }+ }+ }+ | {+ type: "error"+ /**+ * Operation type of the run this error belongs to — lets the response+ * panel decide replace-vs-append on the event's own identity instead+ * of inferring it from the panel's current contents. Absent on+ * connection-level errors, which always replace.+ */+ operationType?: OperationType+ error: {+ type: string+ message: string+ component?: Component+ }+ }++const GQL_SCHEMA_POLL_INTERVAL = 7000++/**+ * Empty `HoppTestResult` sentinel — written when a run completes without+ * producing real test results so the Results tab's loading state (which keys+ * off `testResults === null`) always terminates.+ */+export const emptyTestResults = (scriptError: boolean): HoppTestResult => ({+ description: "",+ expectResults: [],+ tests: [],+ envDiff: {+ global: { additions: [], deletions: [], updations: [] },+ selected: { additions: [], deletions: [], updations: [] },+ },+ scriptError,+ consoleEntries: [],+})++export type ConnectionRequestOptions = {+ url: string+ request: HoppGQLRequest+ inheritedHeaders: HoppGQLRequest["headers"]+ inheritedAuth?: HoppGQLAuth+ /**+ * Inherited collection-level variables cascaded from parent folders+ * (typically `tab.document.inheritedProperties.variables`). When present,+ * these are merged into the env list used to template URL/headers/auth/etc.+ * — `<<myCollectionVar>>` defined on a team folder resolves here.+ */+ inheritedVariables?: HoppInheritedProperty["variables"]+ // Embeds: empty env set for templating/auth/scripts, no store writeback+ isolatedEnvs?: boolean+}++export type RunQueryOptions = {+ name?: string+ url: string+ request: HoppGQLRequest+ inheritedHeaders: HoppGQLRequest["headers"]+ inheritedAuth?: HoppGQLAuth+ /**+ * Inherited collection-level variables cascaded from parent folders+ * (typically `tab.document.inheritedProperties.variables`). When present,+ * these are merged into the env list used to template the GraphQL request.+ */+ inheritedVariables?: HoppInheritedProperty["variables"]+ /**+ * Collection-level scripts cascaded from parent folders (root → request+ * order, from `tab.document.inheritedProperties.scripts`). Combined with+ * the request's own scripts: pre-request runs root → request, test runs+ * request → root, mirroring REST.+ */+ inheritedScripts?: HoppInheritedProperty["scripts"]+ query: string+ variables: string+ operationName: string | undefined+ operationType: OperationType+ // Embeds: empty env set for templating/auth/scripts, no store writeback+ isolatedEnvs?: boolean+}++type WSGraphQLProtocol = "graphql-transport-ws" | "graphql-ws"++/**+ * GraphQL-over-WebSocket message types. Covers both the modern+ * `graphql-transport-ws` protocol and the legacy `subscriptions-transport-ws`+ * (a.k.a. `graphql-ws`) one — we negotiate either at handshake time, so the+ * same dispatcher has to handle frames from both.+ *+ * Modern spec: https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md+ * Legacy spec: https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md+ */+const GQL_WS_MSG = {+ // Both protocols+ CONNECTION_INIT: "connection_init",+ CONNECTION_ACK: "connection_ack",+ ERROR: "error",+ // Modern only+ PING: "ping",+ PONG: "pong",+ SUBSCRIBE: "subscribe",+ NEXT: "next",+ COMPLETE: "complete",+ // Legacy only+ CONNECTION_ERROR: "connection_error",+ CONNECTION_KEEP_ALIVE: "ka",+ START: "start",+ STOP: "stop",+ DATA: "data",+} as const++type ConnectionError = {+ type: string+ message: (t: ReturnType<typeof getI18n>) => string+ component?: Component+}++type TabConnectionContext = {+ state: ConnectionState+ schema: GraphQLSchema | null+ error: ConnectionError | null+ socket: WebSocket | undefined+ /**+ * Direct reactive field (not a nested Map) so shallowReactive on the+ * context picks up assignments. A previous design wrapped this in a Map+ * keyed by tabId, which made `Map.set(...)` mutations invisible to Vue's+ * reactivity since shallowReactive doesn't deep-wrap.+ */+ subscriptionState?: SubscriptionState+ /** Negotiated WS subprotocol for the current subscription socket */+ wsProtocol?: WSGraphQLProtocol+ /** ID of the in-flight subscription on the current socket */+ activeSubId?: string+ /** Timer that fires if the server never sends connection_ack */+ initAckTimer?: ReturnType<typeof setTimeout>+ /**+ * Promise of an in-flight `connectTab` call. Used to dedupe concurrent+ * connect requests so we don't stack polling loops while a fetchSchema+ * is still resolving.+ */+ connectingPromise?: Promise<void>+ /**+ * Ownership token for the schema-poll loop. Every connect/disconnect claims+ * a fresh service-unique epoch; in-flight fetches and pending retry timers+ * captured under an older epoch bail at their next check instead of writing+ * state or re-arming. Recreated contexts start at 0, which never matches a+ * claimed epoch.+ */+ pollEpoch: number+}++/**+ * Public, read-only projection of {@link TabConnectionContext}. Consumers get+ * exactly the fields they need to render UI state without being able to mutate+ * the live context or hold a reference to the WebSocket / timers.+ */+export type TabConnectionView = Readonly<{+ state: ConnectionState+ schema: GraphQLSchema | null+ error: ConnectionError | null+ subscriptionState: SubscriptionState | undefined+}>++/**+ * DIOC service that manages independent GraphQL connections per tab.+ *+ * Each GQL tab on the REST page gets its own connection state, schema,+ * polling timer, WebSocket, and response event stream. Completely+ * independent from connection.ts — the old GQL page (pages/graphql.vue)+ * uses connection.ts directly without interference.+ */+export class GQLTabConnectionService extends Service {+ public static readonly ID = "GQL_TAB_CONNECTION_SERVICE"++ private readonly interceptorService = this.bind(KernelInterceptorService)+ private readonly workspaceTabsService = this.bind(WorkspaceTabsService)++ // Active GQL tab ID — tracks which GQL tab is currently focused+ private _activeGQLTabId = ref<string>("")++ // Per-tab connection state — shallowReactive so the Map tracks key add/delete+ // but doesn't deeply unwrap values (which would strip GraphQLSchema class properties)+ private tabContexts = shallowReactive(new Map<string, TabConnectionContext>())++ // Per-tab schema polling timers (non-reactive, just timeouts)+ private tabPollingTimers = new Map<string, ReturnType<typeof setTimeout>>()++ // Monotonic source for poll epochs — service-level so epochs stay unique+ // even across context deletion/recreation (cleanupTab → getOrCreateContext)+ private pollEpochCounter = 0++ // Monotonic counter for subscription IDs. graphql-transport-ws lets you+ // multiplex multiple subscriptions on one socket; even though we run one+ // at a time per tab today, using a fresh ID per subscribe avoids server+ // "subscriber already exists" errors (close code 4409) if the server is+ // slow to release the prior id after a complete/close.+ private subIdCounter = 0++ // How long to wait for connection_ack after sending connection_init.+ // Both protocols expect ack to be prompt; the spec's de facto upper bound+ // is single-digit seconds — we use 10s to be lenient on slow networks.+ private static readonly CONNECTION_ACK_TIMEOUT_MS = 10_000++ // Per-tab response event refs+ private tabMessageEvents = new Map<+ string,+ Ref<GQLResponseEvent | "reset" | undefined>+ >()++ override onServiceInit() {+ // Detached scope: `onServiceInit` runs synchronously inside whichever+ // component first binds this singleton, so an un-scoped watcher would be+ // disposed when that component unmounts and never re-created+ effectScope(true).run(() => {+ this.setupActiveTabTracking()+ })+ }++ /**+ * Mirrors the active tab's id into `_activeGQLTabId` (empty for non-GQL+ * tabs) and resets the explorer on change, so the docs pane never shows the+ * previous tab's schema. Runs in a detached scope (see `onServiceInit`);+ * per-tab teardown stays caller-driven — every close path calls+ * {@link cleanupTab} explicitly rather than relying on a watcher.+ *+ * The source must depend on BOTH the tab reference AND `document.type` so an+ * in-place protocol flip (REST → GQL on the same tab, via ProtocolSwitcher)+ * is detected — that path reassigns `tab.document` but keeps the same tab+ * object, so watching `currentActiveTab.value` alone would never fire.+ */+ private setupActiveTabTracking() {+ const { reset: resetExplorer } = useExplorer()++ const computedActiveGQLTabId = computed(() => {+ const tab = this.workspaceTabsService.currentActiveTab.value+ return tab?.document.type === "gql-request" ? tab.id : ""+ })++ watch(+ computedActiveGQLTabId,+ (newId, oldId) => {+ if (newId !== oldId) {+ resetExplorer()+ }+ this._activeGQLTabId.value = newId+ },+ { immediate: true }+ )+ }++ // --- Lazy initialization helpers ---++ private getOrCreateContext(tabId: string): TabConnectionContext {+ if (!this.tabContexts.has(tabId)) {+ // Use shallowReactive so property assignments (ctx.state, ctx.schema)+ // are tracked, but values like GraphQLSchema aren't deeply unwrapped+ // (which would strip class-private properties and break the type)+ this.tabContexts.set(+ tabId,+ shallowReactive<TabConnectionContext>({+ state: "DISCONNECTED",+ schema: null,+ error: null,+ socket: undefined,+ subscriptionState: undefined,+ pollEpoch: 0,+ })+ )+ }+ return this.tabContexts.get(tabId)!+ }++ /**+ * Get the per-tab message event ref.+ * Components should watch this to receive responses for a specific tab.+ */+ public getTabMessageEvent(+ tabId: string+ ): Ref<GQLResponseEvent | "reset" | undefined> {+ if (!this.tabMessageEvents.has(tabId)) {+ this.tabMessageEvents.set(+ tabId,+ ref<GQLResponseEvent | "reset" | undefined>()+ )+ }+ return this.tabMessageEvents.get(tabId)!+ }++ /**+ * Writes a tab's test results straight to its document.+ *+ * Must live here, not in the run's calling component: `null` is the+ * in-flight sentinel driving the Results pane's loading state, and+ * `HoppSmartWindows` unmounts a tab as soon as it isn't the active one. A+ * terminal value emitted from the component is therefore lost whenever the+ * run finishes in the background, stranding the sentinel and leaving the+ * pane spinning until the next run on that tab.+ */+ private setTabTestResults(tabId: string, results: HoppTestResult | null) {+ const tab = this.workspaceTabsService.getTabs().find((t) => t.id === tabId)+ if (!tab || tab.document.type !== "gql-request") return+ tab.document.testResults = results+ }++ /**+ * Read-only view of a tab's connection state. Returns a reactive proxy that+ * exposes only the UI-relevant fields — consumers can't accidentally mutate+ * the live context or hold a reference to the live WebSocket / timers.+ */+ public getTabConnectionState(tabId: string): TabConnectionView {+ const ctx = this.getOrCreateContext(tabId)+ // The proxy is computed-like; each property read goes through the live ctx+ // so reactivity is preserved without exposing assignment.+ return {+ get state() {+ return ctx.state+ },+ get schema() {+ return ctx.schema+ },+ get error() {+ return ctx.error+ },+ get subscriptionState() {+ return ctx.subscriptionState+ },+ } as TabConnectionView+ }++ // Cache of per-tab subscription-state computeds. Without this every call to+ // `getTabSubscriptionState(tabId)` allocates a fresh ComputedRef — wasteful+ // when the result is read inside another computed (e.g. `subscriptionPending`+ // in GqlResponse.vue) which re-evaluates on every change.+ private tabSubscriptionStateRefs = new Map<+ string,+ ComputedRef<SubscriptionState | undefined>+ >()++ /**+ * Reactive subscription state for a specific tab — undefined until a+ * subscription has been initiated. Components read this to toggle+ * Run / Stop buttons and to gate "already subscribed" actions.+ */+ public getTabSubscriptionState(+ tabId: string+ ): ComputedRef<SubscriptionState | undefined> {+ let cached = this.tabSubscriptionStateRefs.get(tabId)+ if (!cached) {+ cached = computed(() => this.getOrCreateContext(tabId).subscriptionState)+ this.tabSubscriptionStateRefs.set(tabId, cached)+ }+ return cached+ }++ /**+ * Stop the active subscription for a tab. Sends a protocol-correct stop+ * frame (`complete` for graphql-transport-ws, `stop` for graphql-ws) so+ * the server can release resources for that operation, then closes the+ * socket. Safe to call when there is no active subscription.+ */+ public unsubscribeTab(tabId: string) {+ const ctx = this.tabContexts.get(tabId)+ if (!ctx) return++ if (+ ctx.socket &&+ ctx.socket.readyState === WebSocket.OPEN &&+ ctx.activeSubId+ ) {+ const isModern = ctx.wsProtocol === "graphql-transport-ws"+ try {+ ctx.socket.send(+ JSON.stringify({+ type: isModern ? GQL_WS_MSG.COMPLETE : GQL_WS_MSG.STOP,+ id: ctx.activeSubId,+ })+ )+ } catch (_e) {+ // swallow — socket may have closed between the readyState check+ // and the send call (race window is small but possible)+ }+ }++ this.teardownSubscriptionSocket(ctx)+ ctx.subscriptionState = "UNSUBSCRIBED"+ }++ private teardownSubscriptionSocket(ctx: TabConnectionContext) {+ if (ctx.initAckTimer) {+ clearTimeout(ctx.initAckTimer)+ ctx.initAckTimer = undefined+ }+ if (ctx.socket) {+ try {+ ctx.socket.close()+ } catch (_e) {+ // swallow+ }+ ctx.socket = undefined+ }+ ctx.activeSubId = undefined+ ctx.wsProtocol = undefined+ }++ /**+ * Maps a WebSocket close code to a human-readable reason.+ * Values come from the `graphql-transport-ws` spec (CloseCode enum); see+ * https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md+ */+ private static readonly WS_CLOSE_CODES: Readonly<Record<number, string>> = {+ 4004: "Bad response",+ 4005: "Internal client error",+ 4400: "Bad request",+ 4401: "Unauthorized (connection_init missing or rejected)",+ 4403: "Forbidden",+ 4406: "Subprotocol not acceptable",+ 4408: "Connection initialization timeout",+ 4409: "Subscriber for this ID already exists",+ 4429: "Too many initialization requests",+ 4499: "Connection terminated",+ 4500: "Internal server error",+ 4504: "Connection acknowledgement timeout",+ }++ private describeWSCloseCode(code: number): string {+ return GQLTabConnectionService.WS_CLOSE_CODES[code] ?? "Connection closed"+ }++ /**+ * The active GQL tab's ID (if the current REST tab is a GQL tab).+ */+ public activeGQLTabId = computed(() => this._activeGQLTabId.value)++ /**+ * Computed schema for the active GQL tab.+ * Sidebar components should use this instead of connection.ts's schema.+ */+ public activeTabSchema = computed(() => {+ const tabId = this._activeGQLTabId.value+ if (!tabId) return null+ const ctx = this.tabContexts.get(tabId)+ return ctx?.schema ?? null+ })++ /**+ * Computed schema string (SDL) for the active GQL tab.+ */+ public activeTabSchemaString = computed(() => {+ const schema = this.activeTabSchema.value+ if (!schema || !(schema instanceof GraphQLSchema)) return ""+ return printSchema(schema)+ })++ // --- Connection management ---++ /**+ * Connect a specific tab — starts introspection and schema polling.+ */+ public async connectTab(+ tabId: string,+ options: ConnectionRequestOptions,+ isRunGQLOperation = false+ ) {+ const ctx = this.getOrCreateContext(tabId)++ // Already connected — no-op to avoid crashing callers+ if (ctx.state === "CONNECTED") {+ return+ }++ // De-dupe concurrent connectTab calls. Two near-simultaneous callers+ // (user click + auto-connect from runTabGQLOperation) would otherwise each+ // start their own polling loop, double-firing introspection requests and+ // racing to write ctx.schema.+ if (ctx.connectingPromise) {+ return ctx.connectingPromise+ }++ const toast = useToast()+ const t = getI18n()++ ctx.state = "CONNECTING"+ // Fresh attempt, fresh slate — a failure that doesn't set its own error+ // must not surface the previous attempt's+ ctx.error = null++ // Claim the poll loop: the fresh epoch invalidates any in-flight fetch or+ // scheduled poll from a previous attempt, and the eager timer clear stops+ // the pending-retry case before it fires+ const epoch = (ctx.pollEpoch = ++this.pollEpochCounter)+ const pendingTimer = this.tabPollingTimers.get(tabId)+ if (pendingTimer) clearTimeout(pendingTimer)+ this.tabPollingTimers.delete(tabId)++ // Run-initiated connects stay silent only for their INITIAL failure+ // (execution proceeds without a schema); failures after a successful+ // connect are genuine and must toast+ let hasConnected = false++ const poll = async () => {+ try {+ await this.fetchSchema(tabId, options, epoch)+ // `.get`, not getOrCreate — a closed tab's context must stay deleted+ const currentCtx = this.tabContexts.get(tabId)+ if (!currentCtx) return+ // Superseded by a newer connect/disconnect while the fetch ran+ if (currentCtx.pollEpoch !== epoch) return+ // Belt-and-suspenders — every DISCONNECTED write also bumps the epoch+ if (currentCtx.state === "DISCONNECTED") return+ // Only promote to CONNECTED when we actually have a schema in hand.+ // Without this guard, a silently-failed introspection would leave the+ // UI showing "Disconnect" while the docs/schema panel sees `null` and+ // renders the empty placeholder.+ if (!currentCtx.schema) return+ if (currentCtx.state !== "CONNECTED") currentCtx.state = "CONNECTED"+ hasConnected = true++ const timer = setTimeout(() => {+ poll()+ }, GQL_SCHEMA_POLL_INTERVAL)+ this.tabPollingTimers.set(tabId, timer)+ } catch (error) {+ // `.get`, not getOrCreate — a closed tab's context must stay deleted+ const currentCtx = this.tabContexts.get(tabId)+ if (!currentCtx) return+ // Superseded by a newer connect/disconnect while the fetch ran+ if (currentCtx.pollEpoch !== epoch) return+ // Belt-and-suspenders — every DISCONNECTED write also bumps the epoch+ if (currentCtx.state === "DISCONNECTED") return+ // Toast only on the ERROR transition, not on every retry below+ const firstFailure = currentCtx.state !== "ERROR"+ currentCtx.state = "ERROR"++ if (firstFailure && !(isRunGQLOperation && !hasConnected)) {+ // Use the underlying error message when we have one (e.g.+ // "Introspection response was not valid JSON") so the toast tells+ // the user the actual cause instead of a generic "network error".+ const reason =+ error instanceof Error && error.message+ ? error.message+ : t("graphql.connection_error_http")+ toast.error(reason)+ }++ // Keep polling while a subscription is live so a transient failure+ // self-heals — a later success promotes back to CONNECTED+ if (currentCtx.socket) {+ const timer = setTimeout(() => {+ poll()+ }, GQL_SCHEMA_POLL_INTERVAL)+ this.tabPollingTimers.set(tabId, timer)+ }+ }+ }++ const pending = poll()+ ctx.connectingPromise = pending+ try {+ await pending+ } finally {+ if (ctx.connectingPromise === pending) {+ ctx.connectingPromise = undefined+ }+ }+ }++ /**+ * Disconnect a specific tab — stops polling, closes any subscription+ * socket, clears schema.+ */+ public disconnectTab(tabId: string) {+ const ctx = this.getOrCreateContext(tabId)++ // Release resources unconditionally, before the already-disconnected+ // short-circuit below. The poll timer and any open subscription socket must+ // be torn down on every disconnect regardless of state — a subscription can+ // hold an open socket while the tab is not CONNECTED (introspection may fail+ // while the WS subscribe still succeeds), so gating teardown on state would+ // leak it. Every reset here is idempotent.+ const timer = this.tabPollingTimers.get(tabId)+ if (timer) clearTimeout(timer)+ this.tabPollingTimers.delete(tabId)++ // Close any active subscription socket. An explicit disconnect must not+ // leave the WS open — otherwise the server keeps pushing events and+ // subscriptionState stays "SUBSCRIBED" while the tab shows DISCONNECTED.+ if (ctx.socket) {+ this.teardownSubscriptionSocket(ctx)+ ctx.subscriptionState = "UNSUBSCRIBED"+ }++ // Clear the connect dedup guard as part of the reset. `connectTab` returns+ // an existing `connectingPromise` instead of starting a fresh connect, so a+ // stale one left here would make an immediate reconnect dedupe against the+ // now-dead attempt and silently no-op. The `=== pending` check in+ // `connectTab`'s finally keeps the in-flight attempt from later clobbering+ // a newer promise.+ ctx.connectingPromise = undefined+ // Invalidate any in-flight fetch or scheduled poll for this tab+ ctx.pollEpoch = ++this.pollEpochCounter++ // Already disconnected — the teardown above is idempotent, so skip the+ // redundant state writes.+ if (ctx.state === "DISCONNECTED") return++ ctx.state = "DISCONNECTED"+ ctx.schema = null+ }++ /**+ * Reset a specific tab's connection — disconnect (tearing down the poll timer+ * and any open subscription socket) and clear its schema. Thin wrapper over+ * {@link disconnectTab}, which is idempotent when the tab is already idle.+ */+ public resetTab(tabId: string) {+ this.disconnectTab(tabId)+ }++ // --- Schema fetching ---++ private async fetchSchema(+ tabId: string,+ options: ConnectionRequestOptions,+ epoch: number+ ) {+ // `.get`, not getOrCreate — a poll timer that fired just before+ // cleanupTab cleared it can still execute afterwards, and creating here+ // would resurrect a phantom context for the closed tab+ const ctx = this.tabContexts.get(tabId)+ if (!ctx) return++ // Superseded-attempt guard — mirrors isCurrentSubscription on the WS side.+ // A fetch from an older connect must not write state onto a newer attempt.+ const isCurrent = () => ctx.pollEpoch === epoch++ try {+ const {+ url,+ request,+ inheritedHeaders,+ inheritedAuth,+ inheritedVariables,+ } = options++ // Template env vars before introspection — URL, headers, auth.+ // Merge inherited collection variables (cascaded from parent team/personal+ // folders) at the head of the env list so they outrank selected/global+ // env vars when keys collide (matches REST precedence).+ const inheritedVarsEnv = inheritedVariables+ ? transformInheritedCollectionVariablesToAggregateEnv(+ inheritedVariables+ )+ : []+ // `filterNonEmptyEnvironmentVariables` also applies the current→initial+ // fallback — a variable with only an initial value must not template to ""+ const envVars = filterNonEmptyEnvironmentVariables([+ ...inheritedVarsEnv,+ ...(options.isolatedEnvs ? [] : getAggregateEnvsWithCurrentValue()),+ ] as Environment["variables"]) as Environment["variables"]+ const effective = getEffectiveHoppGQLRequest(request, envVars, {+ inheritedHeaders,+ inheritedAuth,+ url,+ })++ const finalHeaders: Record<string, string> = {}++ const { authHeaders, authParams } = await this.generateAuthHeader(+ effective.effectiveFinalURL,+ effective.effectiveFinalAuth,+ envVars+ )++ // Superseded while auth resolved — bail before firing the request+ if (!isCurrent()) return++ // Query-param auth (api-key/oauth2 in query, AWS query signing) must+ // reach introspection too — mirrors runTabGQLOperation+ let introspectionUrl = effective.effectiveFinalURL+ if (Object.keys(authParams).length > 0) {+ try {+ const urlObj = new URL(introspectionUrl)+ for (const [key, value] of Object.entries(authParams)) {+ urlObj.searchParams.append(key, value)+ }+ introspectionUrl = urlObj.toString()+ } catch (_e) {+ // Unparseable URL — let the network layer surface the real error+ }+ }++ // Precedence (matches the original behavior): request > auth > inherited.+ effective.effectiveFinalHeaders.forEach((header) => {+ finalHeaders[header.key] = header.value+ })+ Object.assign(finalHeaders, authHeaders)+ effective.effectiveFinalRequestHeaders.forEach((header) => {+ finalHeaders[header.key] = header.value+ })++ const kernelRequest: RelayRequest = {+ id: Date.now(),+ url: introspectionUrl,+ method: "POST" as Method,+ version: "HTTP/1.1",+ headers: {+ ...finalHeaders,+ "content-type": "application/json",+ },+ content: content.json(+ { query: getIntrospectionQuery() },+ MediaType.APPLICATION_JSON+ ),+ // Isolated runs opt out of the interceptor-level cookie jar+ ...(options.isolatedEnvs+ ? { meta: { options: { cookies: false } } }+ : {}),+ }++ const { response } = this.interceptorService.execute(kernelRequest)++ const res = await response++ if (E.isLeft(res)) {+ // No state write here — state transitions belong to poll()'s catch /+ // disconnectTab, and poll's firstFailure toast depends on seeing the+ // pre-failure state.+ if (+ isCurrent() &&+ res.left !== "cancellation" &&+ typeof res.left === "object"+ ) {+ ctx.error = {+ type: res.left.error?.kind || "error",+ message: (t: ReturnType<typeof getI18n>) => {+ if (res.left !== "cancellation" && typeof res.left === "object") {+ return (+ res.left.humanMessage?.description(t) ||+ t("graphql.connection_error_http")+ )+ }+ return "Unknown"+ },+ component: res.left.component,+ }+ }++ throw new Error(+ typeof res.left === "string" ? res.left : res.left.error.message+ )+ }++ const data = res.right++ const decoder = new TextDecoder("utf-8")+ // Strip trailing NUL bytes — some kernel transports return a body+ // buffer slightly oversized with `\0` padding (observed against+ // countries.trevorblades.com via the desktop relay). JSON.parse+ // rejects those as "non-whitespace characters after JSON".+ const responseText = decoder.decode(data.body.body).replace(/\0+$/g, "")++ let introspectResponse: { data?: unknown }+ try {+ introspectResponse = JSON.parse(responseText)+ } catch (_parseErr) {+ // Set `ctx.error` (like the introspection-disabled case below) so a+ // background re-poll surfaces this instead of silently dropping the+ // connection — the catch below disconnects before `poll()` can toast.+ if (isCurrent()) {+ ctx.error = {+ type: "error",+ message: (t: ReturnType<typeof getI18n>) =>+ t("graphql.connection_error_invalid_json"),+ }+ }+ throw new Error(+ "Introspection response was not valid JSON — the endpoint may not be a GraphQL server."+ )+ }++ // Introspection disabled (e.g. Hasura / Apollo with `introspection: false`):+ // the 200 body carries `errors` and no `data`. `buildClientSchema(undefined)`+ // throws a cryptic graphql-js internal error, so fail with a clear one.+ // Set `ctx.error` too — on a background re-poll the catch below disconnects+ // before `poll()` can toast, so the response-panel error watcher is the+ // only thing left to surface this to the user.+ // Shape-check up front: a 200 JSON body without an introspection result+ // (e.g. echo servers return a truthy non-introspection `data`) would+ // make buildClientSchema throw its raw multi-KB error into the toast+ if (+ !introspectResponse.data ||+ typeof introspectResponse.data !== "object" ||+ !(introspectResponse.data as Record<string, unknown>).__schema+ ) {+ if (isCurrent()) {+ ctx.error = {+ type: "error",+ message: (t: ReturnType<typeof getI18n>) =>+ t("graphql.connection_error_introspection_disabled"),+ }+ }+ throw new Error("Introspection is disabled on this server.")+ }++ const schemaData = buildClientSchema(introspectResponse.data as any)++ // A superseded fetch must not clobber the newer attempt's schema+ if (!isCurrent()) return++ ctx.schema = schemaData+ ctx.error = null+ } catch (e: any) {+ // A superseded fetch must not disconnect the newer attempt either+ if (!isCurrent()) throw e+ // Mid-poll failure on a connected tab: drop the connection — unless a+ // subscription is streaming; a schema-poll blip must not kill its WS.+ if (ctx.state === "CONNECTED" && !ctx.socket) {+ this.disconnectTab(tabId)+ }+ // Re-throw so the initial-connect path in poll() catches this and+ // surfaces the error. Without this, poll() would treat the failed+ // introspection as a success and force ctx.state to CONNECTED even+ // though ctx.schema is still null — leaving the UI "connected" but+ // with no schema for the docs explorer to render.+ throw e+ }+ }++ // --- Query/Mutation execution ---++ /**+ * Run a GQL query, mutation, or subscription. Captures the current tab ID at call time+ * and routes the response to that tab's message event — even if the user+ * switches tabs before the response arrives.+ */+ public async runTabGQLOperation(tabId: string, options: RunQueryOptions) {+ const ctx = this.getOrCreateContext(tabId)+ const messageEvent = this.getTabMessageEvent(tabId)++ // Tear down any prior subscription before starting a new operation. Even+ // a query/mutation must not coexist with an open subscription socket on+ // the same tab — leaving it open leaks the WS and confuses the UI state+ // machine (subscriptionState stuck on "SUBSCRIBED" while the user sees a+ // single-shot response).+ if (ctx.socket) {+ this.teardownSubscriptionSocket(ctx)+ ctx.subscriptionState = "UNSUBSCRIBED"+ }++ // A subscription run owns the panel from the start — mark the run+ // boundary before the awaits below so no later event of this run can+ // land in a previous run's log. It must be a flush tick ahead of those+ // events: Vue batches ref writes, so a reset assigned in the same tick+ // as an error (the stale-run bail below) collapses to just the error.+ if (options.operationType === "subscription") {+ messageEvent.value = "reset"+ }++ if (ctx.state !== "CONNECTED") {+ // Introspection failure is non-fatal — schema is for the docs explorer+ // and autocomplete, not for executing the request. Servers that disable+ // introspection (Hasura prod, Apollo with introspection: false) or+ // return non-JSON for unknown ops would otherwise prevent the user+ // from running any query/mutation/subscription at all.+ try {+ await this.connectTab(+ tabId,+ {+ url: options.url,+ request: options.request,+ inheritedHeaders: options.inheritedHeaders,+ inheritedAuth: options.inheritedAuth,+ inheritedVariables: options.inheritedVariables,+ isolatedEnvs: options.isolatedEnvs,+ },+ true+ )+ } catch (_e) {+ // Swallow — `fetchSchema` already logged the error and `disconnectTab`+ // moved the connection state out of CONNECTING. The execution path+ // below doesn't depend on the schema.+ }+ }++ // Ownership snapshot (post auto-connect): a disconnect/cleanup during the+ // awaits below bumps the epoch or replaces the context — this run must not+ // write errors or open a subscription socket past that. The DISCONNECTED+ // leg covers a disconnect landing during the auto-connect await itself+ // (epoch then matches post-disconnect); ERROR passes so runs still work on+ // introspection-less servers. Response delivery via messageEvent is+ // deliberately NOT gated (documented cross-tab routing).+ const runEpoch = ctx.pollEpoch+ const runIsCurrent = () =>+ this.tabContexts.get(tabId) === ctx &&+ ctx.pollEpoch === runEpoch &&+ ctx.state !== "DISCONNECTED"++ const {+ url,+ request,+ query,+ variables,+ operationName,+ inheritedHeaders,+ inheritedAuth,+ inheritedVariables,+ operationType,+ } = options++ // `null` = test run in flight, driving the Results pane's loading state.+ // Subscriptions never produce test results, so leave theirs untouched.+ if (operationType !== "subscription") {+ this.setTabTestResults(tabId, null)+ }++ // --- Pre-request script stage (v1: env vars + request headers) ---+ // The sandbox is REST-shaped, so the GQL request rides in as a synthetic+ // POST. The auto-connect above templated with pre-script-free envs —+ // scripts affect the run, not the schema connection.+ const initialEnvState = options.isolatedEnvs+ ? emptyInitialEnvironmentState()+ : captureInitialEnvironmentState()+ let sandboxEnvs = initialEnvState.initialEnvs+ let scriptedHeaders: HoppGQLRequest["headers"] | null = null++ const inheritedPreScripts = (options.inheritedScripts ?? []).map(+ (s) => s.preRequestScript+ )+ const inheritedTestScripts = (options.inheritedScripts ?? []).map(+ (s) => s.testScript+ )+ const syntheticScriptRequest: HoppRESTRequest = {+ ...getDefaultRESTRequest(),+ name: request.name,+ method: "POST",+ endpoint: url,+ headers: request.headers,+ // GQL auth is a strict structural subset of REST auth, so the script's+ // read-only `hopp.request.auth` view stays faithful+ auth: request.auth as HoppRESTRequest["auth"],+ preRequestScript: request.preRequestScript ?? "",+ testScript: request.testScript ?? "",+ }++ // The test stage below only carries the post-script sandbox result —+ // merge pre-script console output like the collection runner does+ let preScriptConsoleEntries: SandboxTestResult["consoleEntries"] = []++ if (+ hasActualScript(syntheticScriptRequest.preRequestScript) ||+ inheritedPreScripts.some((s) => hasActualScript(s))+ ) {+ const preResult = await delegatePreRequestScriptRunner(+ syntheticScriptRequest,+ sandboxEnvs,+ null,+ inheritedPreScripts+ )+ if (E.isLeft(preResult)) {+ // A failing pre-request script must not send the request with+ // unmutated envs — surface the failure and abort (REST's script_fail)+ messageEvent.value = {+ type: "error",+ operationType,+ error: {+ type: "script_error",+ message: `Pre-request script failed: ${preResult.left}`,+ },+ }+ this.setTabTestResults(tabId, emptyTestResults(true))+ return { testResults: emptyTestResults(true), preScriptFailed: true }+ }+ preScriptConsoleEntries = preResult.right.consoleEntries ?? []+ const updated = preResult.right.updatedEnvs as typeof sandboxEnvs+ sandboxEnvs = {+ global: updated.global,+ selected: updated.selected,+ temp: updated.temp ?? [],+ }+ // v1 request-mutation surface: headers only (hopp.request.setHeader) —+ // REST and GQL header shapes are structurally identical+ if (preResult.right.updatedRequest?.headers) {+ scriptedHeaders = preResult.right.updatedRequest.headers+ }+ }++ // Inherited collection variables outrank selected/global env vars;+ // pre-script mutations ride in via `sandboxEnvs`+ const inheritedVarsEnv = inheritedVariables+ ? transformInheritedCollectionVariablesToAggregateEnv(inheritedVariables)+ : []+ // `filterNonEmptyEnvironmentVariables` also applies the current→initial+ // fallback — a variable with only an initial value must not template to ""+ const envVars = filterNonEmptyEnvironmentVariables(+ combineEnvVariables({+ environments: sandboxEnvs,+ requestVariables: [],+ collectionVariables: inheritedVarsEnv,+ })+ ) as Environment["variables"]+ const effective = getEffectiveHoppGQLRequest(+ scriptedHeaders ? { ...request, headers: scriptedHeaders } : request,+ envVars,+ {+ inheritedHeaders,+ inheritedAuth,+ url,+ query,+ variables,+ }+ )++ const finalHeaders: Record<string, string> = {}++ const { authHeaders, authParams } = await this.generateAuthHeader(+ effective.effectiveFinalURL,+ effective.effectiveFinalAuth,+ envVars+ )++ let finalUrl = effective.effectiveFinalURL+ if (Object.keys(authParams).length > 0) {+ try {+ const urlObj = new URL(finalUrl)+ for (const [key, value] of Object.entries(authParams)) {+ urlObj.searchParams.append(key, value)+ }+ finalUrl = urlObj.toString()+ } catch (_e) {+ // Unparseable URL (e.g. unresolved env template) — let the network+ // layer surface the real error as a response event+ }+ }++ // Precedence (matches the original behavior): request > auth > inherited.+ // Apply inherited+request first, then auth (overrides), then request again+ // so user-supplied headers always beat computed auth headers.+ effective.effectiveFinalHeaders.forEach((header) => {+ finalHeaders[header.key] = header.value+ })+ Object.assign(finalHeaders, authHeaders)+ effective.effectiveFinalRequestHeaders.forEach((header) => {+ finalHeaders[header.key] = header.value+ })++ const finalHoppHeaders: HoppRESTHeaders = Object.entries(finalHeaders).map(+ ([key, value]) => ({+ active: true,+ key,+ value,+ description: "",+ })+ )++ const gqlRequest: HoppGQLRequest = {+ v: 10,+ name: options.name || "Untitled Request",+ url: finalUrl,+ headers: finalHoppHeaders,+ query: effective.effectiveFinalQuery,+ variables: effective.effectiveFinalVariables,+ auth: effective.effectiveFinalAuth,+ description: null,+ responses: {},+ // Wire-shape object only — scripts never ride the network request+ preRequestScript: "",+ testScript: "",+ }++ if (operationType === "subscription") {+ // History gets the RAW options — the resolved URL/query can carry+ // secrets and query-param auth tokens. Skipped for isolated runs.+ if (!options.isolatedEnvs) {+ this.addQueryToHistory(options, "")+ }+ // The tab was disconnected/closed while auth resolved — opening a+ // socket now would contradict the explicit teardown+ if (!runIsCurrent()) {+ messageEvent.value = {+ type: "error",+ operationType: "subscription",+ error: {+ type: "subscription_error",+ message:+ "Connection was closed before the subscription started — run again to subscribe.",+ },+ }+ return+ }+ // The HTTP path persists pre-script env writes in its post-request+ // stage, which subscriptions never reach — persist here so the same+ // script behaves identically per operation type. Skipped when isolated.+ if (+ !options.isolatedEnvs &&+ hasEnvironmentChanges(initialEnvState.initialEnvsForComparison, {+ global: sandboxEnvs.global,+ selected: sandboxEnvs.selected,+ })+ ) {+ updateEnvsAfterTestScript(+ {+ global: sandboxEnvs.global,+ selected: sandboxEnvs.selected,+ },+ initialEnvState.initialEnvironmentIndex,+ initialEnvState.initialEnvName,+ initialEnvState.initialEnvsForComparison,+ initialEnvState.initialEnvID+ )+ }+ // Test scripts don't run per-frame, so no testResults for+ // subscriptions+ this.runTabSubscription(+ tabId,+ {+ ...options,+ url: finalUrl,+ query: effective.effectiveFinalQuery,+ variables: effective.effectiveFinalVariables,+ },+ finalHeaders+ )+ return {}+ }++ try {+ const kernelRequest: RelayRequest = await GQLRequest.toRequest(gqlRequest)++ if (operationName) {+ if (kernelRequest.content?.kind === "json") {+ const jsonContent = kernelRequest.content.content as any+ jsonContent.operationName = operationName+ kernelRequest.content.content = jsonContent+ }+ }++ // Isolated runs opt out of the interceptor-level cookie jar+ if (options.isolatedEnvs) {+ kernelRequest.meta = {+ ...kernelRequest.meta,+ options: { ...kernelRequest.meta?.options, cookies: false },+ }+ }++ const { response } = this.interceptorService.execute(kernelRequest)++ const timeStart = Date.now()+ const result = await response++ if (E.isLeft(result)) {+ if (+ runIsCurrent() &&+ result.left !== "cancellation" &&+ typeof result.left === "object"+ ) {+ ctx.error = {+ type: result.left.error?.kind || "error",+ message: (t: ReturnType<typeof getI18n>) => {+ if (+ result.left !== "cancellation" &&+ typeof result.left === "object"+ ) {+ return (+ result.left.humanMessage?.description(t) ||+ t("graphql.operation_error")+ )+ }+ return "Unknown"+ },+ component: result.left.component,+ }+ }++ throw new Error(+ typeof result.left === "string"+ ? result.left+ : result.left.error.message+ )+ }++ const relayResponse = result.right++ const parsedResponse = await GQLResponse.toResponse(+ relayResponse,+ options+ )++ if (parsedResponse.type === "error") {+ throw new Error(parsedResponse.error.message)+ }++ const timeEnd = Date.now()++ // Route response to the captured tab's message event+ messageEvent.value = {+ ...parsedResponse,+ document: {+ type: "success",+ statusCode: relayResponse.status,+ statusText: relayResponse.statusText,+ meta: {+ responseSize: relayResponse.body.body.byteLength,+ responseDuration: timeEnd - timeStart,+ },+ },+ }++ // Skipped for isolated runs+ if (!options.isolatedEnvs) {+ this.addQueryToHistory(options, parsedResponse.data)+ }++ // --- Post-request (test) script stage ---+ // Always runs on the HTTP path — its env writeback is also how+ // PRE-script env mutations persist (REST does the same)+ let testResults = emptyTestResults(false)+ try {+ const testResponse = {+ status: relayResponse.status,+ statusText: relayResponse.statusText,+ headers: Object.entries(relayResponse.headers ?? {}).map(+ ([key, value]) => ({ key, value: String(value) })+ ),+ responseTime: timeEnd - timeStart,+ body: JSON.parse(parsedResponse.data),+ }+ // Test scripts observe the executed request (resolved URL, final+ // wire headers), mirroring REST runs and the GQL collection runner+ const testResult = await runPostRequestScript(+ sandboxEnvs,+ {+ ...syntheticScriptRequest,+ endpoint: finalUrl,+ headers: finalHoppHeaders,+ },+ // Runtime contract is TestResponse — the param annotation says+ // HoppRESTResponse but every REST call site passes this shape too+ testResponse as never,+ null,+ inheritedTestScripts+ )+ if (E.isRight(testResult)) {+ testResults = translateToSandboxTestResults(+ {+ ...testResult.right,+ consoleEntries: [+ ...preScriptConsoleEntries,+ ...(testResult.right.consoleEntries ?? []),+ ],+ },+ initialEnvState.initialGlobalEnvs,+ initialEnvState.initialSelectedEnvs+ )+ // Skipped for isolated runs+ if (+ !options.isolatedEnvs &&+ hasEnvironmentChanges(+ initialEnvState.initialEnvsForComparison,+ testResult.right.envs+ )+ ) {+ updateEnvsAfterTestScript(+ testResult.right.envs,+ initialEnvState.initialEnvironmentIndex,+ initialEnvState.initialEnvName,+ initialEnvState.initialEnvsForComparison,+ initialEnvState.initialEnvID+ )+ }+ } else {+ testResults = emptyTestResults(true)+ }+ } catch (_scriptError) {+ testResults = emptyTestResults(true)+ }++ this.setTabTestResults(tabId, testResults)+ return { data: parsedResponse.data, testResults }+ } catch (error: any) {+ // Route error to the captured tab's message event+ messageEvent.value = {+ type: "error",+ // Never "subscription" — that path returned above+ operationType,+ error: {+ type: "network_error",+ message: error.message || "An unknown error occurred",+ },+ }++ // Terminate the loading sentinel — the run died before the test stage+ // could produce anything, and the response pane stays hidden while+ // `testResults` is null+ this.setTabTestResults(tabId, emptyTestResults(false))++ throw error+ }+ }++ // --- Subscription execution ---++ private runTabSubscription(+ tabId: string,+ options: RunQueryOptions,+ headers?: Record<string, string>+ ) {+ const ctx = this.getOrCreateContext(tabId)+ const messageEvent = this.getTabMessageEvent(tabId)+ const { url, query, operationName, variables } = options+ const wsUrl = url.replace(/^http/, "ws")++ // Defensive — `runTabGQLOperation` already tears down on the entry path,+ // but `runTabSubscription` is logically self-contained.+ if (ctx.socket) {+ this.teardownSubscriptionSocket(ctx)+ }++ let parsedVariables: unknown+ if (variables) {+ try {+ parsedVariables = JSON.parse(variables)+ } catch {+ parsedVariables = undefined+ }+ }++ // Offer both subprotocols. Server picks one via the standard WS handshake;+ // we read `socket.protocol` after open and branch on that. Modern servers+ // (Postman default, recent Apollo, Hasura, graphql-yoga) speak+ // `graphql-transport-ws`; older `subscriptions-transport-ws` servers+ // speak `graphql-ws`.+ const socket = new WebSocket(wsUrl, ["graphql-transport-ws", "graphql-ws"])+ const subId = `${++this.subIdCounter}`++ ctx.socket = socket+ ctx.activeSubId = subId+ ctx.subscriptionState = "SUBSCRIBING"+ messageEvent.value = "reset"++ // Closure helpers — each subscription captures its own `socket` + `subId`,+ // so the staleness check works for handlers that fire after a teardown or+ // a re-subscribe. Without these, every async callback would have to repeat+ // the same guard inline and the terminal-frame paths would diverge from+ // the ack-timeout path.+ const isCurrentSubscription = () =>+ ctx.socket === socket && ctx.activeSubId === subId++ const failSubscription = (message: string) => {+ if (!isCurrentSubscription()) return+ messageEvent.value = {+ type: "error",+ operationType: "subscription",+ error: { type: "subscription_error", message },+ }+ this.teardownSubscriptionSocket(ctx)+ ctx.subscriptionState = "UNSUBSCRIBED"+ }++ // Guard against servers that accept the WS handshake but never send+ // `connection_ack` (e.g. a non-GraphQL echo endpoint that just opens a+ // socket). Without this the UI sits in SUBSCRIBING with no feedback.+ ctx.initAckTimer = setTimeout(() => {+ failSubscription(+ `GraphQL server did not acknowledge the connection within ${+ GQLTabConnectionService.CONNECTION_ACK_TIMEOUT_MS / 1000+ }s. The endpoint may not implement graphql-transport-ws or graphql-ws.`+ )+ }, GQLTabConnectionService.CONNECTION_ACK_TIMEOUT_MS)++ socket.onopen = () => {+ if (!isCurrentSubscription()) return++ ctx.wsProtocol =+ socket.protocol === "graphql-transport-ws"+ ? "graphql-transport-ws"+ : "graphql-ws"++ // Per spec, only connection_init goes out now. The subscribe/start+ // frame is held until the server returns connection_ack — sending it+ // early can be rejected with close code 4401 by strict servers.+ socket.send(+ JSON.stringify({+ type: GQL_WS_MSG.CONNECTION_INIT,+ payload: headers ?? {},+ })+ )+ }++ socket.onmessage = (event) => {+ if (!isCurrentSubscription()) return++ let data: any+ try {+ data = JSON.parse(event.data)+ } catch {+ // Non-JSON frame on a graphql-ws socket — log and ignore so we don't+ // crash the message dispatcher.+ console.warn("Discarded non-JSON WS frame on GQL subscription socket")+ return+ }++ switch (data.type) {+ case GQL_WS_MSG.CONNECTION_ACK: {+ if (ctx.initAckTimer) {+ clearTimeout(ctx.initAckTimer)+ ctx.initAckTimer = undefined+ }+ ctx.subscriptionState = "SUBSCRIBED"++ const isModern = ctx.wsProtocol === "graphql-transport-ws"+ socket.send(+ JSON.stringify({+ type: isModern ? GQL_WS_MSG.SUBSCRIBE : GQL_WS_MSG.START,+ id: subId,+ payload: { query, operationName, variables: parsedVariables },+ })+ )+ break+ }++ case GQL_WS_MSG.PING: {+ // Modern protocol heartbeat — must respond with pong or the server+ // closes the connection after its keep-alive window.+ socket.send(JSON.stringify({ type: GQL_WS_MSG.PONG }))+ break+ }++ case GQL_WS_MSG.CONNECTION_KEEP_ALIVE:+ case GQL_WS_MSG.PONG:+ // Legacy keep-alive / modern pong response — nothing to do.+ break++ case GQL_WS_MSG.DATA: // legacy+ case GQL_WS_MSG.NEXT: {+ // modern+ if (data.id && data.id !== subId) break // not our subscription+ messageEvent.value = {+ type: "response",+ time: Date.now(),+ operationName,+ data: JSON.stringify(data.payload),+ operationType: "subscription",+ }+ break+ }++ case GQL_WS_MSG.ERROR: {+ if (data.id && data.id !== subId) break+ // Terminal per spec — the subscription is dead after `error`. Route+ // through failSubscription so we close the socket, clear timers,+ // and flip UI back to Run instead of leaving stale "SUBSCRIBED"+ // state hanging around.+ failSubscription(+ typeof data.payload === "string"+ ? data.payload+ : JSON.stringify(data.payload)+ )+ break+ }++ case GQL_WS_MSG.CONNECTION_ERROR: {+ // Legacy protocol's protocol-level failure (e.g. auth in payload).+ // Terminal per spec — see `error` case.+ failSubscription(+ typeof data.payload === "string"+ ? data.payload+ : JSON.stringify(data.payload ?? "Connection error")+ )+ break+ }++ case GQL_WS_MSG.COMPLETE: {+ if (data.id && data.id !== subId) break+ // Server-initiated end of stream — fully tear down so the socket,+ // activeSubId, and wsProtocol don't outlive the subscription. Any+ // subsequent onclose for this socket short-circuits because+ // `ctx.socket` is already cleared.+ this.teardownSubscriptionSocket(ctx)+ ctx.subscriptionState = "UNSUBSCRIBED"+ break+ }+ }+ }++ socket.onclose = (event) => {+ // Strict staleness check — if `ctx.socket` was cleared (teardown) or+ // replaced (re-subscribe), this close event belongs to a defunct socket+ // and must not touch shared state. Looser checks that allowed+ // `ctx.socket === undefined` here would re-trigger error reporting for+ // sockets we already tore down.+ if (ctx.socket !== socket) return++ if (ctx.initAckTimer) {+ clearTimeout(ctx.initAckTimer)+ ctx.initAckTimer = undefined+ }++ // Fully clear so the next subscription starts from a clean context.+ ctx.socket = undefined+ ctx.activeSubId = undefined+ ctx.wsProtocol = undefined+ ctx.subscriptionState = "UNSUBSCRIBED"++ // Abnormal close codes from graphql-transport-ws spec carry real+ // diagnostic info — surface them so the user can debug auth/payload+ // issues instead of seeing a silent empty panel.+ if (+ event.code !== 1000 && // normal closure+ event.code !== 1001 && // going away+ event.code !== 1005 // no status received+ ) {+ const reason =+ event.reason || this.describeWSCloseCode(event.code) || ""+ messageEvent.value = {+ type: "error",+ operationType: "subscription",+ error: {+ type: "subscription_error",+ message: `WebSocket closed (code ${event.code})${+ reason ? `: ${reason}` : ""+ }`,+ },+ }+ }+ }++ socket.onerror = (_event) => {+ // Strict staleness check — see onclose.+ if (ctx.socket !== socket) return++ if (ctx.initAckTimer) {+ clearTimeout(ctx.initAckTimer)+ ctx.initAckTimer = undefined+ }+ ctx.subscriptionState = "UNSUBSCRIBED"+ // The browser fires `error` first then `close` — `close` carries the+ // diagnostic code, so we only set a generic message here as a fallback+ // for the rare case where `error` fires without a follow-up close.+ if (!messageEvent.value || messageEvent.value === "reset") {+ messageEvent.value = {+ type: "error",+ operationType: "subscription",+ error: {+ type: "subscription_error",+ message: `WebSocket connection to ${wsUrl} failed. Check that the endpoint accepts GraphQL over WebSocket.`,+ },+ }+ }+ }++ // History is written by the caller with raw options; `options` here is+ // the resolved wire copy.++ return socket+ }++ // --- Cleanup ---++ /**+ * Full cleanup for a specific tab: stop polling, close socket, remove state.+ * Called from every path that closes a tab or flips it away from+ * `gql-request`; idempotent.+ */+ public cleanupTab(tabId: string) {+ const timer = this.tabPollingTimers.get(tabId)+ if (timer) clearTimeout(timer)+ this.tabPollingTimers.delete(tabId)++ const ctx = this.tabContexts.get(tabId)+ if (ctx) {+ this.teardownSubscriptionSocket(ctx)+ // Invalidate in-flight fetches pinned to this context — without this an+ // orphaned fetch stays "current" and can disconnect a recreated tab+ ctx.pollEpoch = ++this.pollEpochCounter+ }++ this.tabContexts.delete(tabId)+ this.tabMessageEvents.delete(tabId)+ this.tabSubscriptionStateRefs.delete(tabId)+ }++ /**+ * Disconnect and clean up all tabs. Call this on page unmount.+ */+ public disconnectAllTabs() {+ for (const [tabId, ctx] of this.tabContexts) {+ const timer = this.tabPollingTimers.get(tabId)+ if (timer) clearTimeout(timer)++ this.teardownSubscriptionSocket(ctx)++ ctx.state = "DISCONNECTED"+ ctx.schema = null+ // Invalidate in-flight fetches pinned to this context (see cleanupTab)+ ctx.pollEpoch = ++this.pollEpochCounter+ }++ this.tabPollingTimers.clear()+ this.tabContexts.clear()+ this.tabMessageEvents.clear()+ this.tabSubscriptionStateRefs.clear()+ }++ // --- Auth header generation ---++ private async generateAuthHeader(+ url: string,+ auth: HoppGQLAuth | undefined,+ envVars: Environment["variables"] = []+ ): Promise<{+ authHeaders: Record<string, string>+ authParams: Record<string, string>+ }> {+ const authHeaders: Record<string, string> = {}+ const authParams: Record<string, string> = {}++ if (!auth?.authActive) return { authHeaders, authParams }++ // Collection-inherited auth can be a REST-only type (digest, HAWK, NTLM,+ // JWT…) — delegate to the shared REST generators via a synthetic request+ // so the full union works (mirrors helpers/graphql/testRunner.ts).+ const syntheticRESTRequest: HoppRESTRequest = {+ ...getDefaultRESTRequest(),+ method: "POST",+ endpoint: url,+ }+ const restAuth = auth as HoppRESTAuth++ for (const h of await generateAuthHeaders(+ restAuth,+ syntheticRESTRequest,+ envVars+ )) {+ authHeaders[h.key] = h.value+ }+ for (const p of await generateAuthParams(+ restAuth,+ syntheticRESTRequest,+ envVars+ )) {+ authParams[p.key] = p.value+ }++ return { authHeaders, authParams }+ }++ // --- History ---++ private addQueryToHistory(options: RunQueryOptions, response: string) {+ const { name, url, request, query, variables } = options+ addGraphqlHistoryEntry(+ makeGQLHistoryEntry({+ request: makeGQLRequest({+ name: name ?? "Untitled Request",+ url,+ query,+ headers: request.headers,+ variables,+ auth: request.auth as HoppGQLAuth,+ description: request.description ?? null,+ responses: {},+ // Snapshot scripts so reopening the history entry restores them+ preRequestScript: request.preRequestScript ?? "",+ testScript: request.testScript ?? "",+ }),+ response,+ star: false,+ })+ )+ }+}diff --git a/packages/hoppscotch-common/src/services/initialization.service.ts b/packages/hoppscotch-common/src/services/initialization.service.tsindex d2ebf5edb..8921c4f38 100644--- a/packages/hoppscotch-common/src/services/initialization.service.ts+++ b/packages/hoppscotch-common/src/services/initialization.service.ts@@ -3,7 +3,7 @@ import * as E from "fp-ts/Either"import { getService } from "~/modules/dioc"import { PersistenceService } from "~/services/persistence"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { GQLTabService } from "~/services/tab/graphql"import { KernelInterceptorService } from "~/services/kernel-interceptor.service"@@ -73,10 +73,10 @@ export class InitializationService extends Service<InitEvent> {throw new Error("Cannot initialize tabs before persistence")}- const restTabService = getService(RESTTabService)+ const workspaceTabsService = getService(WorkspaceTabsService)const gqlTabService = getService(GQLTabService)- await Promise.all([restTabService.init(), gqlTabService.init()])+ await Promise.all([workspaceTabsService.init(), gqlTabService.init()])this.initState.tabs = truethis.emit({ type: "TABS_READY" })diff --git a/packages/hoppscotch-common/src/services/inspection/__tests__/index.spec.ts b/packages/hoppscotch-common/src/services/inspection/__tests__/index.spec.tsindex 9ec138f43..674c1072e 100644--- a/packages/hoppscotch-common/src/services/inspection/__tests__/index.spec.ts+++ b/packages/hoppscotch-common/src/services/inspection/__tests__/index.spec.ts@@ -1,8 +1,9 @@import { describe, it, expect, vi } from "vitest"import { Inspector, InspectionService, InspectorResult } from "../"import { TestContainer } from "dioc/testing"-import { ref } from "vue"-import { RESTTabService } from "~/services/tab/rest"+import { computed, ref } from "vue"+import { refWithControl } from "@vueuse/core"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"vi.mock("~/modules/i18n", () => ({__esModule: true,@@ -31,38 +32,27 @@ const testInspector: Inspector = {getInspections: () => ref(inspectorResultMock),}+const mockRESTTab = {+ id: "test",+ document: {+ type: "request" as const,+ request: {},+ response: null,+ isDirty: false,+ optionTabPreference: "params" as const,+ },+}+describe("InspectionService", () => {describe("registerInspector", () => {- it("should register an inspector", () => {+ it("should register a REST inspector", () => {const container = new TestContainer()- container.bindMock(RESTTabService, {- currentActiveTab: ref({- id: "test",- document: {- type: "request",- request: {},- response: null,- isDirty: false,- optionTabPreference: "params",- },- }),- tabMap: new Map([- [- "test",- {- id: "test",- document: {- type: "request",- request: {},- isDirty: false,- optionTabPreference: "params",- },- },- ],- ]),+ container.bindMock(WorkspaceTabsService, {+ currentActiveTab: computed(() => mockRESTTab),+ tabMap: new Map([["test", mockRESTTab]]),tabOrdering: ref(["test"]),- currentTabID: ref("test"),+ currentTabID: refWithControl("test"),})const service = container.bind(InspectionService)@@ -77,33 +67,11 @@ describe("InspectionService", () => {it("should delete a tab's inspector results", () => {const container = new TestContainer()- container.bindMock(RESTTabService, {- currentActiveTab: ref({- id: "test",- document: {- type: "request",- request: {},- response: null,- isDirty: false,- optionTabPreference: "params",- },- }),- tabMap: new Map([- [- "test",- {- id: "test",- document: {- type: "request",- request: {},- isDirty: false,- optionTabPreference: "params",- },- },- ],- ]),+ container.bindMock(WorkspaceTabsService, {+ currentActiveTab: computed(() => mockRESTTab),+ tabMap: new Map([["test", mockRESTTab]]),tabOrdering: ref(["test"]),- currentTabID: ref("test"),+ currentTabID: refWithControl("test"),})const service = container.bind(InspectionService)diff --git a/packages/hoppscotch-common/src/services/inspection/index.ts b/packages/hoppscotch-common/src/services/inspection/index.tsindex c04930870..9af69afc5 100644--- a/packages/hoppscotch-common/src/services/inspection/index.ts+++ b/packages/hoppscotch-common/src/services/inspection/index.ts@@ -1,4 +1,6 @@import {+ HoppGQLRequest,+ HoppGQLResponseOriginalRequest,HoppRESTRequest,HoppRESTResponseOriginalRequest,} from "@hoppscotch/data"@@ -16,7 +18,7 @@ import {EffectScope,} from "vue"import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"-import { RESTTabService } from "../tab/rest"+import { WorkspaceTabsService } from "../tab/workspace-tabs"/*** Defines how to render the text in an Inspector Result*/@@ -88,8 +90,21 @@ export type InspectorState = {}/**- * Defines an inspector that can be registered with the inspector service- * Inspectors are used to perform checks on a request and return the results+ * The full union of request types an inspector may receive.+ * REST tabs send HoppRESTRequest or HoppRESTResponseOriginalRequest;+ * GQL tabs send HoppGQLRequest or HoppGQLResponseOriginalRequest (when+ * the active document is a `gql-example-response`).+ */+export type InspectorRequest =+ | HoppRESTRequest+ | HoppRESTResponseOriginalRequest+ | HoppGQLRequest+ | HoppGQLResponseOriginalRequest++/**+ * Defines an inspector that can be registered with the inspection service.+ * Inspectors receive the active request (REST or GQL) and may return results+ * for either protocol — or none if the request type is not applicable.*/export interface Inspector {/**@@ -98,13 +113,16 @@ export interface Inspector {inspectorID: string/*** Returns the inspector results for the request.- * NOTE: The refs passed down are readonly and are debounced to avoid performance issues+ * NOTE: The refs passed down are readonly and are debounced to avoid performance issues.+ * For GQL tabs, `req` will be a HoppGQLRequest. For REST tabs it will be+ * HoppRESTRequest or HoppRESTResponseOriginalRequest. `res` is only populated+ * for REST tabs.* @param req The ref to the request to inspect- * @param res The ref to the response to inspect+ * @param res The ref to the response to inspect (null for GQL tabs)* @returns The ref to the inspector results*/getInspections: (- req: Readonly<Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>>,+ req: Readonly<Ref<InspectorRequest>>,res: Readonly<Ref<HoppRESTResponse | null | undefined>>) => Ref<InspectorResult[]>}@@ -116,11 +134,11 @@ export interface Inspector {export class InspectionService extends Service {public static readonly ID = "INSPECTION_SERVICE"- private inspectors: Map<string, Inspector> = reactive(new Map())+ public inspectors: Map<string, Inspector> = reactive(new Map())- private tabs: Ref<Map<string, InspectorResult[]>> = ref(new Map())+ public tabs: Ref<Map<string, InspectorResult[]>> = ref(new Map())- private readonly restTab = this.bind(RESTTabService)+ private readonly workspaceTab = this.bind(WorkspaceTabsService)private watcherStopHandle: (() => void) | null = nullprivate effectScope: EffectScope | null = null@@ -131,7 +149,10 @@ export class InspectionService extends Service {// Watch for tab changes and inspector registration to reinitialize// and create new debounced refswatch(- () => [this.inspectors.entries(), this.restTab.currentActiveTab.value.id],+ () => [+ this.inspectors.entries(),+ this.workspaceTab.currentActiveTab.value.id,+ ],() => {this.initializeListeners()},@@ -140,7 +161,8 @@ export class InspectionService extends Service {}/**- * Registers a inspector with the inspection service+ * Registers an inspector with the inspection service.+ * The inspector will be called for both REST and GQL tabs.* @param inspector The inspector instance to register*/public registerInspector(inspector: Inspector) {@@ -157,19 +179,29 @@ export class InspectionService extends Service {this.effectScope = effectScope()this.effectScope.run(() => {- const currentTabRequest = computed(() => {- if (this.restTab.currentActiveTab.value.document.type === "test-runner")- return null-- return this.restTab.currentActiveTab.value.document.type === "request"- ? this.restTab.currentActiveTab.value.document.request- : this.restTab.currentActiveTab.value.document.response- .originalRequest+ // Resolves the active request for both REST and GQL tabs.+ // Returns null for tab types that are not inspectable (e.g. test-runner)+ // or when an example tab has a missing/broken `response` payload (e.g.+ // stale persisted data) — never throw on a null-deref.+ const currentTabRequest = computed((): InspectorRequest | null => {+ const doc = this.workspaceTab.currentActiveTab.value.document++ if (doc.type === "test-runner") return null+ if (doc.type === "request") return doc.request+ if (doc.type === "gql-request") return doc.request+ if (doc.type === "example-response") {+ return doc.response?.originalRequest ?? null+ }+ if (doc.type === "gql-example-response") {+ return doc.response?.originalRequest ?? null+ }+ return null})const currentTabResponse = computed(() => {- if (this.restTab.currentActiveTab.value.document.type === "request") {- return this.restTab.currentActiveTab.value.document.response+ const doc = this.workspaceTab.currentActiveTab.value.document+ if (doc.type === "request") {+ return doc.response}return null})@@ -186,9 +218,7 @@ export class InspectionService extends Service {return Array.from(this.inspectors.values()).map((inspector) =>inspector.getInspections(- debouncedReq as Readonly<- Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>- >,+ debouncedReq as Readonly<Ref<InspectorRequest>>,debouncedRes))@@ -202,7 +232,7 @@ export class InspectionService extends Service {() => [...activeInspections.value],() => {this.tabs.value.set(- this.restTab.currentActiveTab.value.id,+ this.workspaceTab.currentActiveTab.value.id,activeInspections.value)},@@ -212,7 +242,6 @@ export class InspectionService extends Service {}public deleteTabInspectorResult(tabID: string) {- // TODO: Move Tabs into a service and implement this with an event insteadthis.tabs.value.delete(tabID)}diff --git a/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/environment.inspector.spec.ts b/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/environment.inspector.spec.tsindex 4e5f9a8a0..f560b6237 100644--- a/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/environment.inspector.spec.ts+++ b/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/environment.inspector.spec.ts@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"import { EnvironmentInspectorService } from "../environment.inspector"import { InspectionService } from "../../index"import { getDefaultRESTRequest } from "~/helpers/rest/default"+import { getDefaultGQLRequest } from "@hoppscotch/data"import { ref } from "vue"import { CurrentValueService } from "~/services/current-environment-value.service"import { SecretEnvironmentService } from "~/services/secret-environment.service"@@ -68,7 +69,7 @@ describe("EnvironmentInspectorService", () => {expect(registerInspectorFn).toHaveBeenCalledWith(envInspector)})- describe("getInspectorFor", () => {+ describe("getInspections (REST)", () => {it("should return an inspector result when the URL contains undefined environment variables", () => {const container = new TestContainer()const envInspector = container.bind(EnvironmentInspectorService)@@ -409,4 +410,152 @@ describe("EnvironmentInspectorService", () => {expect(result.value).toHaveLength(1)})})++ describe("getInspections (GQL)", () => {+ it("should return a result when the GQL URL contains an undefined environment variable", () => {+ const container = new TestContainer()+ const envInspector = container.bind(EnvironmentInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "<<UNDEFINED_ENV_VAR>>",+ })++ const result = envInspector.getInspections(req)++ expect(result.value).toContainEqual(+ expect.objectContaining({+ id: "environment-not-found-0",+ isApplicable: true,+ locations: expect.objectContaining({ type: "url" }),+ })+ )+ })++ it("should not return a result when the GQL URL contains a defined environment variable", () => {+ const container = new TestContainer()+ container.bindMock(CurrentValueService, {+ hasValue: vi.fn(() => true),+ })+ const envInspector = container.bind(EnvironmentInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "<<EXISTING_ENV_VAR>>",+ })++ const result = envInspector.getInspections(req)++ expect(result.value).toHaveLength(0)+ })++ it("should return a result when a GQL header key contains an undefined environment variable", () => {+ const container = new TestContainer()+ const envInspector = container.bind(EnvironmentInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "https://example.com/graphql",+ headers: [{ key: "<<UNDEFINED_ENV_VAR>>", value: "val", active: true }],+ })++ const result = envInspector.getInspections(req)++ expect(result.value).toContainEqual(+ expect.objectContaining({+ id: "environment-not-found-0",+ isApplicable: true,+ locations: expect.objectContaining({+ type: "header",+ position: "key",+ }),+ })+ )+ })++ it("should return a result when a GQL header value contains an undefined environment variable", () => {+ const container = new TestContainer()+ const envInspector = container.bind(EnvironmentInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "https://example.com/graphql",+ headers: [+ {+ key: "Authorization",+ value: "<<UNDEFINED_ENV_VAR>>",+ active: true,+ },+ ],+ })++ const result = envInspector.getInspections(req)++ expect(result.value).toContainEqual(+ expect.objectContaining({+ id: "environment-not-found-0",+ isApplicable: true,+ locations: expect.objectContaining({+ type: "header",+ position: "value",+ }),+ })+ )+ })++ it("should not inspect inactive GQL headers", () => {+ const container = new TestContainer()+ const envInspector = container.bind(EnvironmentInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "https://example.com/graphql",+ headers: [+ { key: "<<UNDEFINED_ENV_VAR>>", value: "val", active: false },+ ],+ })++ const result = envInspector.getInspections(req)++ expect(result.value).toHaveLength(0)+ })++ it("should return a result when a GQL header key has an empty environment variable value", () => {+ const container = new TestContainer()+ const envInspector = container.bind(EnvironmentInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "https://example.com/graphql",+ headers: [+ { key: "<<EXISTING_ENV_VAR_2>>", value: "val", active: true },+ ],+ })++ const result = envInspector.getInspections(req)++ expect(result.value).toContainEqual(+ expect.objectContaining({+ id: "environment-empty-0",+ isApplicable: true,+ locations: expect.objectContaining({ type: "header" }),+ })+ )+ })++ it("should return empty results for a clean GQL request with no env vars", () => {+ const container = new TestContainer()+ const envInspector = container.bind(EnvironmentInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "https://example.com/graphql",+ headers: [],+ })++ const result = envInspector.getInspections(req)++ expect(result.value).toHaveLength(0)+ })+ })})diff --git a/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/request.inspector.spec.ts b/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/request.inspector.spec.tsindex 35c70a167..ba7136dd8 100644--- a/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/request.inspector.spec.ts+++ b/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/request.inspector.spec.ts@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"import { RequestInspectorService } from "../request.inspector"import { InspectionService } from "../../index"import { getDefaultRESTRequest } from "~/helpers/rest/default"+import { getDefaultGQLRequest } from "@hoppscotch/data"import { ref } from "vue"import { KernelInterceptorService } from "~/services/kernel-interceptor.service"@@ -301,4 +302,186 @@ describe("RequestInspectorService", () => {)})})++ describe("GQL inspection via getInspections", () => {+ describe("localhost access inspection (GQL)", () => {+ it("should return a result when GQL URL contains localhost and interceptor doesn't support localaccess", () => {+ const container = new TestContainer()++ container.bindMock(KernelInterceptorService, {+ current: ref({+ capabilities: {+ auth: new Set(),+ content: new Set(),+ advanced: new Set(),+ },+ }),+ })++ const requestInspector = container.bind(RequestInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "http://localhost:4000/graphql",+ })++ const result = requestInspector.getInspections(req)++ expect(result.value).toContainEqual(+ expect.objectContaining({+ id: "localaccess",+ isApplicable: true,+ locations: { type: "url" },+ })+ )+ })++ it("should not return a result when GQL URL contains localhost and interceptor supports localaccess", () => {+ const container = new TestContainer()++ container.bindMock(KernelInterceptorService, {+ current: ref({+ capabilities: {+ auth: new Set(),+ content: new Set(),+ advanced: new Set(["localaccess"]),+ },+ }),+ })++ const requestInspector = container.bind(RequestInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "http://localhost:4000/graphql",+ })++ const result = requestInspector.getInspections(req)++ expect(result.value).not.toContainEqual(+ expect.objectContaining({ id: "localaccess" })+ )+ })++ it("should return a result when GQL URL contains 127.0.0.1 and interceptor doesn't support localaccess", () => {+ const container = new TestContainer()++ container.bindMock(KernelInterceptorService, {+ current: ref({+ capabilities: {+ auth: new Set(),+ content: new Set(),+ advanced: new Set(),+ },+ }),+ })++ const requestInspector = container.bind(RequestInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "http://127.0.0.1:4000/graphql",+ })++ const result = requestInspector.getInspections(req)++ expect(result.value).toContainEqual(+ expect.objectContaining({ id: "localaccess" })+ )+ })+ })++ describe("cookie header inspection (GQL)", () => {+ it("should return a result when GQL headers contain Cookie and interceptor doesn't support cookies", () => {+ const container = new TestContainer()++ container.bindMock(KernelInterceptorService, {+ current: ref({+ capabilities: {+ auth: new Set(),+ content: new Set(),+ advanced: new Set(),+ },+ }),+ })++ const requestInspector = container.bind(RequestInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "https://example.com/graphql",+ headers: [{ key: "Cookie", value: "session=abc", active: true }],+ })++ const result = requestInspector.getInspections(req)++ expect(result.value).toContainEqual(+ expect.objectContaining({+ id: "cookie-header",+ isApplicable: true,+ locations: expect.objectContaining({+ type: "header",+ position: "key",+ index: 0,+ key: "Cookie",+ }),+ })+ )+ })++ it("should not return a result when GQL headers contain Cookie and interceptor supports cookies", () => {+ const container = new TestContainer()++ container.bindMock(KernelInterceptorService, {+ current: ref({+ capabilities: {+ auth: new Set(),+ content: new Set(),+ advanced: new Set(["cookies"]),+ },+ }),+ })++ const requestInspector = container.bind(RequestInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "https://example.com/graphql",+ headers: [{ key: "Cookie", value: "session=abc", active: true }],+ })++ const result = requestInspector.getInspections(req)++ expect(result.value).not.toContainEqual(+ expect.objectContaining({ id: "cookie-header" })+ )+ })+ })++ it("should return empty results for a normal GQL request", () => {+ const container = new TestContainer()++ container.bindMock(KernelInterceptorService, {+ current: ref({+ capabilities: {+ auth: new Set(),+ content: new Set(),+ advanced: new Set(["localaccess", "cookies"]),+ },+ }),+ })++ const requestInspector = container.bind(RequestInspectorService)++ const req = ref({+ ...getDefaultGQLRequest(),+ url: "https://echo.hoppscotch.io/graphql",+ headers: [],+ })++ const result = requestInspector.getInspections(req)++ expect(result.value).toHaveLength(0)+ })+ })})diff --git a/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.ts b/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.tsindex 6a23642ed..c58c3575f 100644--- a/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.ts+++ b/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.ts@@ -3,15 +3,13 @@ import {InspectionService,Inspector,InspectorLocation,+ InspectorRequest,InspectorResult,} from ".."+import { isGQLRequest } from "~/helpers/request-type"import { Service } from "dioc"import { Ref, markRaw, computed } from "vue"import IconPlusCircle from "~icons/lucide/plus-circle"-import {- HoppRESTRequest,- HoppRESTResponseOriginalRequest,-} from "@hoppscotch/data"import {aggregateEnvsWithCurrentValue$,getCurrentEnvironment,@@ -20,7 +18,7 @@ import {import { invokeAction } from "~/helpers/actions"import { useStreamStatic } from "~/composables/stream"import { SecretEnvironmentService } from "~/services/secret-environment.service"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { CurrentValueService } from "~/services/current-environment-value.service"import {getEffectiveVariablesForRequest,@@ -47,7 +45,7 @@ export class EnvironmentInspectorService extends Service implements Inspector {private readonly inspection = this.bind(InspectionService)private readonly secretEnvs = this.bind(SecretEnvironmentService)private readonly currentEnvs = this.bind(CurrentValueService)- private readonly restTabs = this.bind(RESTTabService)+ private readonly workspaceTabs = this.bind(WorkspaceTabsService)private aggregateEnvsWithValue = useStreamStatic(aggregateEnvsWithCurrentValue$,@@ -73,22 +71,27 @@ export class EnvironmentInspectorService extends Service implements Inspector {locations: InspectorLocation) => {const newErrors: InspectorResult[] = []- const currentTab = this.restTabs.currentActiveTab.value+ const currentTab = this.workspaceTabs.currentActiveTab.value++ const doc = currentTab.document- // Get the current request or example-response request+ // Get the current request (REST, example-response, or GQL)const currentTabRequest =- currentTab.document.type === "request"- ? currentTab.document.request- : currentTab.document.type === "example-response"- ? currentTab.document.response.originalRequest+ doc.type === "request"+ ? doc.request+ : doc.type === "example-response"+ ? doc.response.originalRequest: null// request → collection → environment, in the same precedence order the- // request runner uses (single source of truth)+ // request runner uses (single source of truth). Include gql-request so GQL+ // tabs also resolve inherited collection variables.const environmentVariables = getEffectiveVariablesForRequest(currentTabRequest?.requestVariables,currentTab.document.type === "request" ||- currentTab.document.type === "example-response"+ currentTab.document.type === "example-response" ||+ currentTab.document.type === "gql-request" ||+ currentTab.document.type === "gql-example-response"? currentTab.document.inheritedProperties?.variables: [],this.aggregateEnvsWithValue.value@@ -167,23 +170,27 @@ export class EnvironmentInspectorService extends Service implements Inspector {matches?.forEach((exEnv) => {const formattedExEnv = exEnv.slice(2, -2)const currentSelectedEnvironment = getCurrentEnvironment()- const currentTab = this.restTabs.currentActiveTab.value+ const currentTab = this.workspaceTabs.currentActiveTab.value+ const doc = currentTab.document- // Get current request or example+ // Get current request (REST or example-response; GQL tabs don't have requestVariables)const currentTabRequest =- currentTab.document.type === "request"- ? currentTab.document.request- : currentTab.document.type === "example-response"- ? currentTab.document.response.originalRequest+ doc.type === "request"+ ? doc.request+ : doc.type === "example-response"+ ? doc.response.originalRequest: null// request → collection → environment, matching the request runner's- // precedence and non-empty resolution (single source of truth)+ // precedence and non-empty resolution (single source of truth). Include+ // gql-request so GQL tabs also resolve inherited collection variables.const environmentVariables = filterNonEmptyEnvironmentVariables(getEffectiveVariablesForRequest(currentTabRequest?.requestVariables,currentTab.document.type === "request" ||- currentTab.document.type === "example-response"+ currentTab.document.type === "example-response" ||+ currentTab.document.type === "gql-request" ||+ currentTab.document.type === "gql-example-response"? currentTab.document.inheritedProperties?.variables: [],this.aggregateEnvsWithValue.value,@@ -294,68 +301,104 @@ export class EnvironmentInspectorService extends Service implements Inspector {}/**- * Runs all inspections for a given request and returns a computed list of results.+ * Runs all environment-variable inspections for a request.+ * Handles both REST (endpoint/headers/params) and GQL (url/headers) tabs.*/- getInspections(- req: Readonly<Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>>- ) {+ getInspections(req: Readonly<Ref<InspectorRequest>>) {return computed(() => {const results: InspectorResult[] = []if (!req.value) return results- const { endpoint, headers, params } = req.value-- // URL check- results.push(- ...this.validateEnvironmentVariables([endpoint], { type: "url" }),- ...this.validateEmptyEnvironmentVariables([endpoint], { type: "url" })- )-- // Header keys and values- const headerKeys = Object.values(headers).map((h) => h.key)- const headerValues = Object.values(headers).map((h) => h.value)-- results.push(- ...this.validateEnvironmentVariables(headerKeys, {- type: "header",- position: "key",- }),- ...this.validateEmptyEnvironmentVariables(headerKeys, {- type: "header",- position: "key",- }),- ...this.validateEnvironmentVariables(headerValues, {- type: "header",- position: "value",- }),- ...this.validateEmptyEnvironmentVariables(headerValues, {- type: "header",- position: "value",- })- )-- // Parameter keys and values- const paramKeys = Object.values(params).map((p) => p.key)- const paramValues = Object.values(params).map((p) => p.value)-- results.push(- ...this.validateEnvironmentVariables(paramKeys, {- type: "parameter",- position: "key",- }),- ...this.validateEmptyEnvironmentVariables(paramKeys, {- type: "parameter",- position: "key",- }),- ...this.validateEnvironmentVariables(paramValues, {- type: "parameter",- position: "value",- }),- ...this.validateEmptyEnvironmentVariables(paramValues, {- type: "parameter",- position: "value",- })- )+ if (isGQLRequest(req.value)) {+ // GQL: url + active headers only (no params)+ const { url, headers } = req.value++ results.push(+ ...this.validateEnvironmentVariables([url], { type: "url" }),+ ...this.validateEmptyEnvironmentVariables([url], { type: "url" })+ )++ // Preserve row positions — gql/Headers.vue matches results by the+ // UNFILTERED row index. Masking inactive rows to "" keeps indices+ // aligned while exempting them from validation.+ const headerKeys = headers.map((h) => (h.active ? h.key : ""))+ const headerValues = headers.map((h) => (h.active ? h.value : ""))++ results.push(+ ...this.validateEnvironmentVariables(headerKeys, {+ type: "header",+ position: "key",+ }),+ ...this.validateEmptyEnvironmentVariables(headerKeys, {+ type: "header",+ position: "key",+ }),+ ...this.validateEnvironmentVariables(headerValues, {+ type: "header",+ position: "value",+ }),+ ...this.validateEmptyEnvironmentVariables(headerValues, {+ type: "header",+ position: "value",+ })+ )+ } else {+ // REST: endpoint + headers + params+ const { endpoint, headers, params } = req.value as {+ endpoint: string+ headers: { key: string; value: string }[]+ params: { key: string; value: string }[]+ }++ results.push(+ ...this.validateEnvironmentVariables([endpoint], { type: "url" }),+ ...this.validateEmptyEnvironmentVariables([endpoint], { type: "url" })+ )++ const headerKeys = Object.values(headers).map((h) => h.key)+ const headerValues = Object.values(headers).map((h) => h.value)++ results.push(+ ...this.validateEnvironmentVariables(headerKeys, {+ type: "header",+ position: "key",+ }),+ ...this.validateEmptyEnvironmentVariables(headerKeys, {+ type: "header",+ position: "key",+ }),+ ...this.validateEnvironmentVariables(headerValues, {+ type: "header",+ position: "value",+ }),+ ...this.validateEmptyEnvironmentVariables(headerValues, {+ type: "header",+ position: "value",+ })+ )++ const paramKeys = Object.values(params).map((p) => p.key)+ const paramValues = Object.values(params).map((p) => p.value)++ results.push(+ ...this.validateEnvironmentVariables(paramKeys, {+ type: "parameter",+ position: "key",+ }),+ ...this.validateEmptyEnvironmentVariables(paramKeys, {+ type: "parameter",+ position: "key",+ }),+ ...this.validateEnvironmentVariables(paramValues, {+ type: "parameter",+ position: "value",+ }),+ ...this.validateEmptyEnvironmentVariables(paramValues, {+ type: "parameter",+ position: "value",+ })+ )+ }return results})diff --git a/packages/hoppscotch-common/src/services/inspection/inspectors/request.inspector.ts b/packages/hoppscotch-common/src/services/inspection/inspectors/request.inspector.tsindex a913fef6a..441dc59b7 100644--- a/packages/hoppscotch-common/src/services/inspection/inspectors/request.inspector.ts+++ b/packages/hoppscotch-common/src/services/inspection/inspectors/request.inspector.ts@@ -1,10 +1,16 @@import { Service } from "dioc"-import { InspectionService, Inspector, InspectorResult } from ".."+import {+ InspectionService,+ Inspector,+ InspectorRequest,+ InspectorResult,+} from ".."import { computed, markRaw, Ref } from "vue"import {HoppRESTRequest,HoppRESTResponseOriginalRequest,} from "@hoppscotch/data"+import { isGQLRequest } from "~/helpers/request-type"import IconAlertTriangle from "~icons/lucide/alert-triangle"import { getI18n } from "~/modules/i18n"import { KernelInterceptorService } from "~/services/kernel-interceptor.service"@@ -153,15 +159,75 @@ export class RequestInspectorService extends Service implements Inspector {return !supports ? [createInspection(match)] : []}- getInspections(- req: Readonly<Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>>- ) {- return computed(() =>- !req.value- ? []- : this.inspectionChecks.flatMap((check) =>- this.validateCapability(req.value, check)- )- )+ /**+ * Runs capability checks for a request.+ * For REST requests all checks apply; for GQL only localaccess and cookie-header+ * apply (no body or REST-specific auth types).+ */+ getInspections(req: Readonly<Ref<InspectorRequest>>) {+ return computed(() => {+ if (!req.value) return []++ if (isGQLRequest(req.value)) {+ const gqlReq = req.value+ const results: InspectorResult[] = []+ const capabilities = this.kernelInterceptor.current.value?.capabilities++ // Localhost / 127.0.0.1 check+ const localHostURLs = ["localhost", "127.0.0.1"]+ if (localHostURLs.some((host) => gqlReq.url.includes(host))) {+ if (!capabilities?.advanced.has("localaccess")) {+ results.push({+ id: "localaccess",+ icon: markRaw(IconAlertTriangle),+ text: {+ type: "text",+ text: this.t("inspections.url.localaccess_unsupported"),+ },+ severity: 2,+ isApplicable: true,+ locations: { type: "url" },+ })+ }+ }++ // Cookie header check+ const cookieIndex = gqlReq.headers.findIndex((h) =>+ h.key.toLowerCase().includes("cookie")+ )+ if (cookieIndex !== -1 && !capabilities?.advanced.has("cookies")) {+ results.push({+ id: "cookie-header",+ icon: markRaw(IconAlertTriangle),+ text: {+ type: "text",+ text: this.t("inspections.header.cookie"),+ },+ severity: 2,+ isApplicable: true,+ locations: {+ type: "header",+ position: "key",+ index: cookieIndex,+ key: gqlReq.headers[cookieIndex].key,+ },+ doc: {+ text: this.t("action.learn_more"),+ link: "https://hoppscotch.com/download",+ },+ })+ }++ return results+ }++ // REST: run all capability checks+ return this.inspectionChecks.flatMap((check) =>+ this.validateCapability(+ req.value as HoppRESTRequest | HoppRESTResponseOriginalRequest,+ check+ )+ )+ })}}diff --git a/packages/hoppscotch-common/src/services/inspection/inspectors/response.inspector.ts b/packages/hoppscotch-common/src/services/inspection/inspectors/response.inspector.tsindex d35ddb2fb..02b8a4c10 100644--- a/packages/hoppscotch-common/src/services/inspection/inspectors/response.inspector.ts+++ b/packages/hoppscotch-common/src/services/inspection/inspectors/response.inspector.ts@@ -1,10 +1,11 @@import { Service } from "dioc"-import { InspectionService, Inspector, InspectorResult } from ".."-import { getI18n } from "~/modules/i18n"import {- HoppRESTRequest,- HoppRESTResponseOriginalRequest,-} from "@hoppscotch/data"+ InspectionService,+ Inspector,+ InspectorRequest,+ InspectorResult,+} from ".."+import { getI18n } from "~/modules/i18n"import IconAlertTriangle from "~icons/lucide/alert-triangle"import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"import { computed, Ref, markRaw } from "vue"@@ -29,7 +30,7 @@ export class ResponseInspectorService extends Service implements Inspector {}getInspections(- _req: Readonly<Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>>,+ _req: Readonly<Ref<InspectorRequest>>,res: Readonly<Ref<HoppRESTResponse | null | undefined>>) {return computed(() => {diff --git a/packages/hoppscotch-common/src/services/inspection/inspectors/scripting-interceptor.inspector.ts b/packages/hoppscotch-common/src/services/inspection/inspectors/scripting-interceptor.inspector.tsindex d8364c295..c93ccc4ba 100644--- a/packages/hoppscotch-common/src/services/inspection/inspectors/scripting-interceptor.inspector.ts+++ b/packages/hoppscotch-common/src/services/inspection/inspectors/scripting-interceptor.inspector.ts@@ -2,13 +2,11 @@ import { Service } from "dioc"import {InspectionService,Inspector,+ InspectorRequest,InspectorResult,} from "~/services/inspection"import { computed, markRaw, Ref } from "vue"-import {- HoppRESTRequest,- HoppRESTResponseOriginalRequest,-} from "@hoppscotch/data"+import { HoppRESTRequest } from "@hoppscotch/data"import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"import IconAlertTriangle from "~icons/lucide/alert-triangle"import { getI18n } from "~/modules/i18n"@@ -146,7 +144,7 @@ export class ScriptingInterceptorInspectorService}getInspections(- req: Readonly<Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>>,+ req: Readonly<Ref<InspectorRequest>>,// eslint-disable-next-line @typescript-eslint/no-unused-vars_res: Readonly<Ref<HoppRESTResponse | null | undefined>>): Ref<InspectorResult[]> {diff --git a/packages/hoppscotch-common/src/services/persistence/__tests__/__mocks__/index.ts b/packages/hoppscotch-common/src/services/persistence/__tests__/__mocks__/index.tsindex e4ee651a8..89717f7d3 100644--- a/packages/hoppscotch-common/src/services/persistence/__tests__/__mocks__/index.ts+++ b/packages/hoppscotch-common/src/services/persistence/__tests__/__mocks__/index.ts@@ -2,12 +2,13 @@ import {CollectionSchemaVersion,Environment,GlobalEnvironment,+ GQL_REQ_SCHEMA_VERSION,HoppCollection,RESTReqSchemaVersion,} from "@hoppscotch/data"import { HoppGQLDocument } from "~/helpers/graphql/document"-import { HoppRequestDocument } from "~/helpers/rest/document"+import { HoppRequestDocument } from "~/helpers/tab/document"import { GQLHistoryEntry, RESTHistoryEntry } from "~/newstore/history"import { SettingsDef, getDefaultSettings } from "~/newstore/settings"import { SecretVariable } from "~/services/secret-environment.service"@@ -67,7 +68,7 @@ export const GQL_COLLECTIONS_MOCK: HoppCollection[] = [name: "Echo",requests: [{- v: 9,+ v: GQL_REQ_SCHEMA_VERSION,name: "Echo test",url: "https://echo.hoppscotch.io/graphql",headers: [],@@ -77,6 +78,11 @@ export const GQL_COLLECTIONS_MOCK: HoppCollection[] = [authType: "none",authActive: true,},+ _ref_id: "gql_req_ref_id_1",+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",},],auth: { authType: "none", authActive: true },@@ -193,13 +199,18 @@ export const GQL_HISTORY_MOCK: GQLHistoryEntry[] = [{v: 1,request: {- v: 9,+ v: GQL_REQ_SCHEMA_VERSION,name: "Untitled",url: "https://echo.hoppscotch.io/graphql",query: "query Request { url }",headers: [],variables: "",auth: { authType: "none", authActive: true },+ _ref_id: "gql_req_ref_id_2",+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",},response: '{"data":{"url":"/graphql"}}',star: false,@@ -214,13 +225,18 @@ export const GQL_TAB_STATE_MOCK: PersistableTabState<HoppGQLDocument> = {tabID: "5edbe8d4-65c9-4381-9354-5f1bf05d8ccc",doc: {request: {- v: 9,+ v: GQL_REQ_SCHEMA_VERSION,name: "Untitled",url: "https://echo.hoppscotch.io/graphql",headers: [],variables: '{\n "id": "1"\n}',query: "query Request { url }",auth: { authType: "none", authActive: true },+ _ref_id: "gql_req_ref_id_3",+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",},isDirty: true,optionTabPreference: "query",diff --git a/packages/hoppscotch-common/src/services/persistence/__tests__/index.spec.ts b/packages/hoppscotch-common/src/services/persistence/__tests__/index.spec.tsindex d5523c96f..7bbb202e5 100644--- a/packages/hoppscotch-common/src/services/persistence/__tests__/index.spec.ts+++ b/packages/hoppscotch-common/src/services/persistence/__tests__/index.spec.ts@@ -2,10 +2,7 @@import * as E from "fp-ts/Either"-import {- translateToNewGQLCollection,- translateToNewRESTCollection,-} from "@hoppscotch/data"+import { translateToNewCollection } from "@hoppscotch/data"import { watchDebounced } from "@vueuse/core"import { TestContainer } from "dioc/testing"import { cloneDeep } from "lodash-es"@@ -50,7 +47,7 @@ import {} from "~/newstore/settings"import { SecretEnvironmentService } from "~/services/secret-environment.service"import { GQLTabService } from "~/services/tab/graphql"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import {PersistenceService,STORE_KEYS,@@ -163,12 +160,12 @@ const setStoreItem = async <T>(key: string, value: T) => {const bindPersistenceService = ({mockGQLTabService = false,- mockRESTTabService = false,+ mockWorkspaceTabsService = false,mockSecretEnvironmentsService = false,mock = {},}: {mockGQLTabService?: boolean- mockRESTTabService?: boolean+ mockWorkspaceTabsService?: booleanmockSecretEnvironmentsService?: booleanmock?: Record<string, unknown>} = {}) => {@@ -178,8 +175,8 @@ const bindPersistenceService = ({container.bindMock(GQLTabService, mock)}- if (mockRESTTabService) {- container.bindMock(RESTTabService, mock)+ if (mockWorkspaceTabsService) {+ container.bindMock(WorkspaceTabsService, mock)}if (mockSecretEnvironmentsService) {@@ -1000,10 +997,7 @@ describe("PersistenceService", () => {return {...actualModule,- translateToNewGQLCollection: vi- .fn()- .mockImplementation((data: any) => data),- translateToNewRESTCollection: vi+ translateToNewCollection: vi.fn().mockImplementation((data: any) => data),}@@ -1056,8 +1050,7 @@ describe("PersistenceService", () => {expect.stringContaining('"schemaVersion":1'))- expect(translateToNewGQLCollection).toHaveBeenCalled()- expect(translateToNewRESTCollection).toHaveBeenCalled()+ expect(translateToNewCollection).toHaveBeenCalled()expect(setRESTCollections).toHaveBeenCalledWith(restCollections)expect(setGraphqlCollections).toHaveBeenCalledWith(gqlCollections)@@ -1883,7 +1876,10 @@ describe("PersistenceService", () => {const getItemSpy = spyOnGetItem()const setItemSpy = spyOnSetItem()- await invokeSetupLocalPersistence({ mockRESTTabService: true, mock })+ await invokeSetupLocalPersistence({+ mockWorkspaceTabsService: true,+ mock,+ })expect(getItemSpy).toHaveBeenCalledWith(restTabStateKey)@@ -1905,7 +1901,10 @@ describe("PersistenceService", () => {const getItemSpy = spyOnGetItem()const setItemSpy = spyOnSetItem()- await invokeSetupLocalPersistence({ mockRESTTabService: true, mock })+ await invokeSetupLocalPersistence({+ mockWorkspaceTabsService: true,+ mock,+ })expect(getItemSpy).toHaveBeenCalledWith(restTabStateKey)diff --git a/packages/hoppscotch-common/src/services/persistence/__tests__/validation-schemas.spec.ts b/packages/hoppscotch-common/src/services/persistence/__tests__/validation-schemas.spec.tsnew file mode 100644index 000000000..f7ed30e68--- /dev/null+++ b/packages/hoppscotch-common/src/services/persistence/__tests__/validation-schemas.spec.ts@@ -0,0 +1,85 @@+import { GQL_REQ_SCHEMA_VERSION } from "@hoppscotch/data"+import { describe, expect, it } from "vitest"++import { WORKSPACE_TABS_STATE_SCHEMA } from "../validation-schemas"++const originalRequest = {+ v: "1",+ name: "Stamped GQL",+ url: "https://echo.hoppscotch.io/graphql",+ headers: [],+ query: "query Hello { method }",+ variables: "{}",+ auth: { authType: "none", authActive: true },+}++const example = (stamps: Record<string, string | null>) => ({+ name: "example",+ code: 200,+ status: "OK",+ headers: [],+ body: "{}",+ originalRequest,+ ...stamps,+})++describe("WORKSPACE_TABS_STATE_SCHEMA — gql-request branch", () => {+ it("round-trips a gql-request doc with scripts, stamped examples, and the new option tabs", () => {+ const state = {+ lastActiveTabID: "gql-tab-1",+ orderedDocs: [+ {+ tabID: "gql-tab-1",+ doc: {+ type: "gql-request",+ request: {+ v: GQL_REQ_SCHEMA_VERSION,+ name: "Stamped GQL",+ url: "https://echo.hoppscotch.io/graphql",+ headers: [],+ query: "query Hello { method }",+ variables: "{}",+ auth: { authType: "none", authActive: true },+ description: null,+ responses: {+ exact: example({+ operationName: "Hello",+ operationType: "query",+ }),+ // Wildcard stamp — the mock server canonicalizes it as null;+ // a null stamp must parse, not wipe the responses record+ wildcard: example({+ operationName: null,+ operationType: "query",+ }),+ },+ preRequestScript: 'pw.env.set("a", "b")',+ testScript: 'pw.test("t", () => {})',+ },+ isDirty: false,+ optionTabPreference: "tests",+ testResults: null,+ response: null,+ },+ },+ ],+ }++ const result = WORKSPACE_TABS_STATE_SCHEMA.safeParse(state)+ expect(result.success).toBe(true)+ if (result.success) {+ const doc = result.data.orderedDocs[0].doc+ if (doc.type === "gql-request") {+ expect(doc.request.preRequestScript).toBe('pw.env.set("a", "b")')+ expect(doc.request.testScript).toBe('pw.test("t", () => {})')+ expect(Object.keys(doc.request.responses ?? {})).toEqual([+ "exact",+ "wildcard",+ ])+ expect(doc.optionTabPreference).toBe("tests")+ } else {+ throw new Error("expected a gql-request doc")+ }+ }+ })+})diff --git a/packages/hoppscotch-common/src/services/persistence/index.ts b/packages/hoppscotch-common/src/services/persistence/index.tsindex 714b0ca26..890daac28 100644--- a/packages/hoppscotch-common/src/services/persistence/index.ts+++ b/packages/hoppscotch-common/src/services/persistence/index.ts@@ -9,8 +9,7 @@ import { assign, clone, isEmpty, cloneDeep } from "lodash-es"import {GlobalEnvironmentVariable,- translateToNewGQLCollection,- translateToNewRESTCollection,+ translateToNewCollection,} from "@hoppscotch/data"import { StoreError } from "@hoppscotch/kernel"@@ -18,7 +17,7 @@ import { StoreError } from "@hoppscotch/kernel"import { Store } from "~/kernel/store"import { diag } from "~/kernel/log"import { GQLTabService } from "~/services/tab/graphql"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import {SecretEnvironmentService,SecretVariable,@@ -82,7 +81,7 @@ import {NUXT_COLOR_MODE_SCHEMA,REST_COLLECTION_SCHEMA,REST_HISTORY_ENTRY_SCHEMA,- REST_TAB_STATE_SCHEMA,+ WORKSPACE_TABS_STATE_SCHEMA,SECRET_ENVIRONMENT_VARIABLE_SCHEMA,SELECTED_ENV_INDEX_SCHEMA,SETTINGS_SCHEMA,@@ -93,7 +92,7 @@ import {WEBSOCKET_REQUEST_SCHEMA,} from "./validation-schemas"import { PersistableTabState } from "../tab"-import { HoppTabDocument } from "~/helpers/rest/document"+import { HoppTabDocument } from "~/helpers/tab/document"import { HoppGQLDocument } from "~/helpers/graphql/document"import {CurrentValueService,@@ -257,7 +256,7 @@ export class PersistenceService extends Service {// TODO: Consider swapping this with platform dependent `StoreLike` implpublic hoppLocalConfigStorage: StorageLike = localStorage- private readonly restTabService = this.bind(RESTTabService)+ private readonly workspaceTabsService = this.bind(WorkspaceTabsService)private readonly gqlTabService = this.bind(GQLTabService)private readonly secretEnvironmentService = this.bind(SecretEnvironmentService@@ -617,7 +616,7 @@ export class PersistenceService extends Service {const result = z.array(REST_COLLECTION_SCHEMA).safeParse(data)if (result.success) {- const translatedData = result.data.map(translateToNewRESTCollection)+ const translatedData = result.data.map(translateToNewCollection)diag("persistence","REST collections translated, count:",@@ -660,7 +659,7 @@ export class PersistenceService extends Service {const result = z.array(GQL_COLLECTION_SCHEMA).safeParse(data)if (result.success) {- const translatedData = result.data.map(translateToNewGQLCollection)+ const translatedData = result.data.map(translateToNewCollection)setGraphqlCollections(translatedData)} else {this.showErrorToast(STORE_KEYS.GQL_COLLECTIONS)@@ -1067,7 +1066,7 @@ export class PersistenceService extends Service {})}- private async setupRESTTabsPersistence() {+ private async setupWorkspaceTabsPersistence() {const loadResult = await Store.get<any>(STORE_NAMESPACE,STORE_KEYS.REST_TABS@@ -1084,10 +1083,10 @@ export class PersistenceService extends Service {...loadResult.right,orderedDocs,}- const result = REST_TAB_STATE_SCHEMA.safeParse(transformedTabs)+ const result = WORKSPACE_TABS_STATE_SCHEMA.safeParse(transformedTabs)if (result.success) {// SAFETY: We know the schema matches- this.restTabService.loadTabsFromPersistedState(+ this.workspaceTabsService.loadTabsFromPersistedState(result.data as PersistableTabState<HoppTabDocument>)} else {@@ -1102,7 +1101,7 @@ export class PersistenceService extends Service {JSON.stringify(loadResult.right))// NOTE: Still loading data to match legacy behavior- this.restTabService.loadTabsFromPersistedState(loadResult.right)+ this.workspaceTabsService.loadTabsFromPersistedState(loadResult.right)}}} catch (_e) {@@ -1110,7 +1109,7 @@ export class PersistenceService extends Service {}watchDebounced(- this.restTabService.persistableTabState,+ this.workspaceTabsService.persistableTabState,async (newData) => {const result = await Store.set(STORE_NAMESPACE,@@ -1202,7 +1201,7 @@ export class PersistenceService extends Service {this.setupSocketIOPersistence(),this.setupSSEPersistence(),this.setupMQTTPersistence(),- this.setupRESTTabsPersistence(),+ this.setupWorkspaceTabsPersistence(),this.setupGQLTabsPersistence(),this.setupSecretEnvironmentsPersistence(),diff --git a/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.ts b/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.tsindex e8d9523ed..2548b46f0 100644--- a/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.ts+++ b/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.ts@@ -3,6 +3,7 @@ import {GQLHeader,HoppGQLAuth,HoppGQLRequest,+ HoppGQLRequestResponse,HoppRESTAuth,HoppRESTRequest,HoppRESTHeaders,@@ -86,12 +87,32 @@ const SettingsDefSchema = z.object({EXPERIMENTAL_SCRIPTING_SANDBOX: z.optional(z.boolean()),ENABLE_EXPERIMENTAL_MOCK_SERVERS: z.optional(z.boolean()),ENABLE_EXPERIMENTAL_DOCUMENTATION: z.optional(z.boolean()),+ ENABLE_GQL_IN_REST_WORKSPACE: z.optional(z.boolean()),})const HoppRESTRequestSchema = entityReference(HoppRESTRequest)const HoppGQLRequestSchema = entityReference(HoppGQLRequest)+/**+ * A protocol-switcher draft: the snapshotted request plus the tab's dirty+ * flag at snapshot time.+ *+ * Drafts written before dirty tracking existed were bare requests, so those+ * are still accepted and normalized to `isDirty: true` — the behaviour they+ * were written under. Without this, an in-flight draft from an older build+ * would fail the tab-state schema on upgrade and take the whole persisted+ * tab list down with it.+ */+const ProtocolDraftSchema = <T extends z.ZodTypeAny>(requestSchema: T) =>+ z.union([+ z.object({ request: requestSchema, isDirty: z.boolean() }),+ requestSchema.transform((request: z.infer<T>) => ({+ request,+ isDirty: true,+ })),+ ])+const HoppRESTCollectionSchema = entityReference(HoppCollection)const HoppGQLCollectionSchema = entityReference(HoppCollection)@@ -320,6 +341,8 @@ const validGqlOperations = ["headers","variables","authorization",+ "preRequestScript",+ "tests",] as constconst HoppInheritedPropertySchema = z@@ -569,7 +592,7 @@ const HoppRESTResponseSchema = z.discriminatedUnion("type", [.strict(),])-const HoppRESTSaveContextSchema = z.nullable(+const HoppTabSaveContextSchema = z.nullable(z.discriminatedUnion("originLocation", [z.object({@@ -638,12 +661,43 @@ export const TestRunnerResultCollectionSchema = z.intersection(TestRunnerResultOverlaySchema)-export const REST_TAB_STATE_SCHEMA = z+// Persisted per-tab GQL response events (unified workspace) — mirrors+// `GQLResponseEvent` in gql-tab-connection.service. Passthrough keeps the+// optional fields (`document`, `rawQuery`) without pinning their shapes;+// the legacy `GQLResponseEventSchema` above can't be reused here — it is+// `.strict()` and models neither the `type` discriminant nor error events.+const GQLTabResponseEventSchema = z.union([+ z+ .object({+ type: z.literal("response"),+ time: z.number(),+ operationName: z.optional(z.string()),+ operationType: OperationTypeSchema,+ data: z.string(),+ })+ .passthrough(),+ z+ .object({+ type: z.literal("error"),+ error: z.object({ type: z.string(), message: z.string() }).passthrough(),+ })+ .passthrough(),+])++export const WORKSPACE_TABS_STATE_SCHEMA = z.object({lastActiveTabID: z.string(),orderedDocs: z.array(z.object({tabID: z.string(),+ // Opposite-protocol shadow drafts from the protocol switcher —+ // modeled explicitly because safeParse strips unknown keys+ protocolDrafts: z.optional(+ z.object({+ rest: z.optional(ProtocolDraftSchema(HoppRESTRequestSchema)),+ gql: z.optional(ProtocolDraftSchema(HoppGQLRequestSchema)),+ })+ ),doc: z.union([z.object({type: z.literal("test-runner").catch("test-runner"),@@ -681,7 +735,12 @@ export const REST_TAB_STATE_SCHEMA = zselectedRequestRefIds: z.optional(z.array(z.string())),environmentName: z.optional(z.string()),testRunnerMeta: TestRunnerMetaSchema,- request: z.nullable(entityReference(HoppRESTRequest)),+ request: z.nullable(+ z.union([+ entityReference(HoppRESTRequest),+ entityReference(HoppGQLRequest),+ ])+ ),response: z.nullable(HoppRESTResponseSchema),testResults: z.optional(z.nullable(HoppTestResultSchema)),isDirty: z.boolean(),@@ -692,7 +751,7 @@ export const REST_TAB_STATE_SCHEMA = zrequest: entityReference(HoppRESTRequest),type: z.literal("request").catch("request"),isDirty: z.boolean(),- saveContext: z.optional(HoppRESTSaveContextSchema),+ saveContext: z.optional(HoppTabSaveContextSchema),response: z.optional(z.nullable(HoppRESTResponseSchema)),testResults: z.optional(z.nullable(HoppTestResultSchema)),responseTabPreference: z.optional(z.string()),@@ -703,7 +762,42 @@ export const REST_TAB_STATE_SCHEMA = zz.object({type: z.literal("example-response").catch("example-response"),response: entityReference(HoppRESTRequestResponse),- saveContext: z.optional(HoppRESTSaveContextSchema),+ saveContext: z.optional(HoppTabSaveContextSchema),+ isDirty: z.boolean(),+ inheritedProperties: z.optional(HoppInheritedPropertySchema),+ }),+ z.object({+ // No `.catch()` on the new GQL literals — nothing legacy coerces+ // into them, and a `.catch()` lets a corrupt gql-request doc+ // silently morph into an empty gql-example-response doc.+ type: z.literal("gql-request"),+ request: entityReference(HoppGQLRequest),+ isDirty: z.boolean(),+ cursorPosition: z.optional(z.number()),+ saveContext: z.optional(HoppTabSaveContextSchema),+ // Field-level catch: a corrupt persisted response degrades to an+ // empty panel rather than failing the whole tabs-state parse+ response: z+ .optional(z.nullable(z.array(GQLTabResponseEventSchema)))+ .catch(null),+ responseTabPreference: z.optional(z.string()),+ optionTabPreference: z.optional(+ z.enum([+ "query",+ "headers",+ "variables",+ "authorization",+ "preRequestScript",+ "tests",+ ])+ ),+ testResults: z.optional(z.nullable(HoppTestResultSchema)),+ inheritedProperties: z.optional(HoppInheritedPropertySchema),+ }),+ z.object({+ type: z.literal("gql-example-response"),+ response: z.nullable(entityReference(HoppGQLRequestResponse)),+ saveContext: z.optional(HoppTabSaveContextSchema),isDirty: z.boolean(),inheritedProperties: z.optional(HoppInheritedPropertySchema),}),diff --git a/packages/hoppscotch-common/src/services/spotlight/searchers/__tests__/environment.searcher.spec.ts b/packages/hoppscotch-common/src/services/spotlight/searchers/__tests__/environment.searcher.spec.tsnew file mode 100644index 000000000..c5c2343b0--- /dev/null+++ b/packages/hoppscotch-common/src/services/spotlight/searchers/__tests__/environment.searcher.spec.ts@@ -0,0 +1,96 @@+import { TestContainer } from "dioc/testing"+import { beforeEach, describe, expect, it, vi } from "vitest"+import { HoppAction, HoppActionWithArgs } from "~/helpers/actions"+import { SpotlightService } from "../.."+import { EnvironmentsSpotlightSearcherService } from "../environment.searcher"++vi.mock("~/modules/i18n", () => ({+ __esModule: true,+ getI18n: () => (x: string) => x,+}))++const actionsMock = vi.hoisted(() => ({+ value: [] as (HoppAction | HoppActionWithArgs)[],+ invokeAction: vi.fn(),+}))++vi.mock("~/helpers/actions", async () => {+ const { BehaviorSubject }: any = await vi.importActual("rxjs")++ return {+ __esModule: true,+ activeActions$: new BehaviorSubject(actionsMock.value),+ invokeAction: actionsMock.invokeAction,+ }+})++const envMock = vi.hoisted(() => ({+ selectedIndex$: null as any,+ currentEnv$: null as any,+}))++vi.mock("~/newstore/environments", async () => {+ const { BehaviorSubject }: any = await vi.importActual("rxjs")++ envMock.selectedIndex$ = new BehaviorSubject({ type: "NO_ENV_SELECTED" })+ envMock.currentEnv$ = new BehaviorSubject(null)++ return {+ __esModule: true,+ selectedEnvironmentIndex$: envMock.selectedIndex$,+ currentEnvironment$: envMock.currentEnv$,+ environments$: new BehaviorSubject([]),+ globalEnv$: new BehaviorSubject([]),+ duplicateEnvironment: vi.fn(),+ getGlobalVariables: vi.fn(() => []),+ setGlobalEnvVariables: vi.fn(),+ getLegacyGlobalEnvironment: vi.fn(() => null),+ addGlobalEnvVariable: vi.fn(),+ }+})++describe("EnvironmentsSpotlightSearcherService", () => {+ beforeEach(() => {+ actionsMock.invokeAction.mockReset()+ })++ const bindSearcher = () => {+ const container = new TestContainer()+ container.bindMock(SpotlightService, { registerSearcher: vi.fn() })+ return container.bind(EnvironmentsSpotlightSearcherService)+ }++ // A personal env stays selectable inside a team workspace, and the team+ // editor resolves by NAME — branching on workspace instead of the selected+ // env's scope silently edits a same-named team environment+ it("edits the personal environment when a personal env is selected", () => {+ envMock.selectedIndex$.next({ type: "MY_ENV", index: 0 })+ envMock.currentEnv$.next({ name: "shared-name", variables: [] })++ const searcher = bindSearcher()+ searcher.onDocSelected("edit_selected_env")++ expect(actionsMock.invokeAction).toHaveBeenCalledWith(+ "modals.my.environment.edit",+ { envName: "shared-name" }+ )+ })++ it("edits the team environment when a team env is selected", () => {+ envMock.selectedIndex$.next({+ type: "TEAM_ENV",+ teamEnvID: "env-1",+ teamID: "team-a",+ environment: { name: "shared-name", variables: [] },+ })+ envMock.currentEnv$.next({ name: "shared-name", variables: [] })++ const searcher = bindSearcher()+ searcher.onDocSelected("edit_selected_env")++ expect(actionsMock.invokeAction).toHaveBeenCalledWith(+ "modals.team.environment.edit",+ { envName: "shared-name" }+ )+ })+})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 c46dea1e4..c3d4d4b8b 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@@ -5,7 +5,7 @@ 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 { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { SpotlightService } from "../.."import { HistorySpotlightSearcherService } from "../history.searcher"@@ -76,11 +76,16 @@ describe("HistorySpotlightSearcherService", () => {y = historyMock.restEntries.pop()}+ let z = historyMock.gqlEntries.pop()+ while (z) {+ z = historyMock.gqlEntries.pop()+ }+const container = new TestContainer()const createNewTabFn = vi.fn()- container.bindMock(RESTTabService, {+ container.bindMock(WorkspaceTabsService, {createNewTab: createNewTabFn,})@@ -310,6 +315,103 @@ describe("HistorySpotlightSearcherService", () => {})})+ it("selecting an entry opens that same entry when earlier entries lack updatedOn", async () => {+ actionsMock.value.push("rest.request.open")++ // Entries without `updatedOn` are filtered out of the search index, but+ // result ids must still address the unfiltered store+ historyMock.restEntries.push({+ request: {+ ...getDefaultRESTRequest(),+ endpoint: "skipped.com",+ },+ responseMeta: { duration: null, statusCode: null },+ star: false,+ v: 1,+ updatedOn: undefined,+ } as unknown as RESTHistoryEntry)++ const targetEntry: RESTHistoryEntry = {+ request: {+ ...getDefaultRESTRequest(),+ endpoint: "bla.com",+ },+ responseMeta: { duration: null, statusCode: null },+ star: false,+ v: 1,+ updatedOn: new Date(),+ }++ historyMock.restEntries.push(targetEntry)++ const container = new TestContainer()++ const history = container.bind(HistorySpotlightSearcherService)+ await flushPromises()++ const query = ref("bla")+ const [result] = history.createSearchSession(query)+ await nextTick()++ // Store index (1), not the filtered index (0)+ expect(result.value.results[0].id).toBe("rest-1")++ history.onResultSelect(result.value.results[0])++ expect(actionsMock.invokeAction).toHaveBeenCalledWith("rest.request.open", {+ doc: {+ request: targetEntry.request,+ isDirty: false,+ type: "request",+ },+ })+ })++ it("selecting a graphql entry opens that same entry when earlier entries lack updatedOn", async () => {+ actionsMock.value.push("gql.request.open")++ historyMock.gqlEntries.push({+ request: {+ ...getDefaultGQLRequest(),+ url: "skipped.com",+ },+ response: "{}",+ star: false,+ v: 1,+ updatedOn: undefined,+ } as unknown as GQLHistoryEntry)++ const targetEntry: GQLHistoryEntry = {+ request: {+ ...getDefaultGQLRequest(),+ url: "bla.com",+ },+ response: "{}",+ star: false,+ v: 1,+ updatedOn: new Date(),+ }++ historyMock.gqlEntries.push(targetEntry)++ const container = new TestContainer()++ const history = container.bind(HistorySpotlightSearcherService)+ await flushPromises()++ const query = ref("bla")+ const [result] = history.createSearchSession(query)+ await nextTick()++ expect(result.value.results[0].id).toBe("gql-1")++ history.onResultSelect(result.value.results[0])++ expect(actionsMock.invokeAction).toHaveBeenCalledWith("gql.request.open", {+ request: targetEntry.request,+ })+ })+it("rest history entries are not shown when the rest open action is not registered", async () => {actionsMock.value.push("gql.request.open")diff --git a/packages/hoppscotch-common/src/services/spotlight/searchers/collections.searcher.ts b/packages/hoppscotch-common/src/services/spotlight/searchers/collections.searcher.tsindex 63a31ffde..1bd369d9c 100644--- a/packages/hoppscotch-common/src/services/spotlight/searchers/collections.searcher.ts+++ b/packages/hoppscotch-common/src/services/spotlight/searchers/collections.searcher.ts@@ -26,7 +26,8 @@ import {} from "@hoppscotch/data"import { WorkspaceService } from "~/services/workspace.service"import { invokeAction } from "~/helpers/actions"-import { RESTTabService } from "~/services/tab/rest"+import { isGQLRequest } from "~/helpers/request-type"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { GQLTabService } from "~/services/tab/graphql"/**@@ -45,7 +46,7 @@ export class CollectionsSpotlightSearcherServicepublic searcherID = "collections"public searcherSectionTitle = this.t("collection.my_collections")- private readonly restTab = this.bind(RESTTabService)+ private readonly workspaceTab = this.bind(WorkspaceTabsService)private readonly gqlTab = this.bind(GQLTabService)private readonly spotlight = this.bind(SpotlightService)@@ -307,8 +308,8 @@ export class CollectionsSpotlightSearcherServiceconst resolvedFolderPath = folderPath.join("/")- const req = this.getRESTFolderFromFolderPath(resolvedFolderPath)- ?.requests[reqIndex] as HoppRESTRequest+ const req =+ this.getRESTFolderFromFolderPath(resolvedFolderPath)?.requests[reqIndex]if (!req) return@@ -321,34 +322,67 @@ export class CollectionsSpotlightSearcherServicerequestRefID: req._ref_id ?? req.id,} as const- const possibleTab = this.restTab.getTabRefWithSaveContext(saveContext)+ const possibleTab =+ this.workspaceTab.getTabRefWithSaveContext(saveContext)if (possibleTab) {- this.restTab.setActiveTab(possibleTab.value.id)+ this.workspaceTab.setActiveTab(possibleTab.value.id)} else {- this.restTab.createNewTab(- {- type: "request",- request: cloneDeep(req),- isDirty: false,- saveContext,- inheritedProperties: cascadeParentCollectionForProperties(- resolvedFolderPath,- "rest"- ),- },- true- )+ // Collections hold mixed types — route GQL requests to a gql tab+ if (isGQLRequest(req)) {+ this.workspaceTab.createNewTab(+ {+ type: "gql-request",+ request: cloneDeep(req) as HoppGQLRequest,+ isDirty: false,+ cursorPosition: 0,+ saveContext,+ inheritedProperties: cascadeParentCollectionForProperties(+ resolvedFolderPath,+ "rest"+ ),+ },+ true+ )+ } else {+ this.workspaceTab.createNewTab(+ {+ type: "request",+ request: cloneDeep(req) as HoppRESTRequest,+ isDirty: false,+ saveContext,+ inheritedProperties: cascadeParentCollectionForProperties(+ resolvedFolderPath,+ "rest"+ ),+ },+ true+ )+ }}} else if (type === "gql") {const folderPath = path.split("/").map((x) => parseInt(x))const reqIndex = folderPath.pop()!const req = this.getGQLFolderFromFolderPath(folderPath.join("/"))- ?.requests[reqIndex] as HoppGQLRequest+ ?.requests[reqIndex]if (!req) return+ // Mirror of the REST branch above — GQL collections can hold+ // REST-shaped requests; open those in the unified workspace+ if (!isGQLRequest(req)) {+ this.workspaceTab.createNewTab(+ {+ type: "request",+ request: req as HoppRESTRequest,+ isDirty: false,+ },+ true+ )+ return+ }+this.gqlTab.createNewTab({saveContext: {originLocation: "user-collection",@@ -356,7 +390,7 @@ export class CollectionsSpotlightSearcherServicerequestIndex: reqIndex,},cursorPosition: 0,- request: cloneDeep(req),+ request: cloneDeep(req) as HoppGQLRequest,isDirty: false,inheritedProperties: cascadeParentCollectionForProperties(folderPath.join("/"),diff --git a/packages/hoppscotch-common/src/services/spotlight/searchers/environment.searcher.ts b/packages/hoppscotch-common/src/services/spotlight/searchers/environment.searcher.tsindex 90cfb9973..d70f87b6b 100644--- a/packages/hoppscotch-common/src/services/spotlight/searchers/environment.searcher.ts+++ b/packages/hoppscotch-common/src/services/spotlight/searchers/environment.searcher.ts@@ -34,7 +34,7 @@ import MiniSearch from "minisearch"import { map } from "rxjs"import { useStreamStatic } from "~/composables/stream"import { GQLError, runGQLQuery } from "~/helpers/backend/GQLClient"-import { deleteTeamEnvironment } from "~/helpers/backend/mutations/TeamEnvironment"+import { createDuplicateEnvironment as duplicateTeamEnvironment } from "~/helpers/backend/mutations/TeamEnvironment"import {SelectedEnvironmentIndex,createEnvironment,@@ -82,10 +82,6 @@ export class EnvironmentsSpotlightSearcherService extends StaticSpotlightSearchepublic readonly searcherID = "environments"public searcherSectionTitle = this.t("spotlight.environments.title")- private readonly workspaceService = this.bind(WorkspaceService)-- private workspace = this.workspaceService.currentWorkspace-private readonly spotlight = this.bind(SpotlightService)private selectedEnvIndex = useStreamStatic(@@ -218,7 +214,7 @@ export class EnvironmentsSpotlightSearcherService extends StaticSpotlightSearcheif (this.selectedEnvIndex.value?.type === "TEAM_ENV") {pipe(- deleteTeamEnvironment(this.selectedEnvIndex.value.teamEnvID),+ duplicateTeamEnvironment(this.selectedEnvIndex.value.teamEnvID),TE.match((err: GQLError<string>) => {console.error(err)@@ -244,12 +240,16 @@ export class EnvironmentsSpotlightSearcherService extends StaticSpotlightSearchebreakcase "edit_selected_env":if (this.selectedEnv.value) {- if (this.workspace.value.type === "personal") {- invokeAction(`modals.my.environment.edit`, {+ // Branch on the SELECTED environment's scope, not the workspace —+ // a personal env can be selected inside a team workspace, and the+ // team editor resolves by name (a collision would edit the wrong,+ // team-shared environment)+ if (this.selectedEnvIndex.value?.type === "TEAM_ENV") {+ invokeAction(`modals.team.environment.edit`, {envName: this.selectedEnv.value.name,})} else {- invokeAction(`modals.team.environment.edit`, {+ invokeAction(`modals.my.environment.edit`, {envName: this.selectedEnv.value.name,})}diff --git a/packages/hoppscotch-common/src/services/spotlight/searchers/history.searcher.ts b/packages/hoppscotch-common/src/services/spotlight/searchers/history.searcher.tsindex d9717b880..68599624d 100644--- a/packages/hoppscotch-common/src/services/spotlight/searchers/history.searcher.ts+++ b/packages/hoppscotch-common/src/services/spotlight/searchers/history.searcher.ts@@ -19,7 +19,7 @@ import { shortDateTime } from "~/helpers/utils/date"import { useStreamStatic } from "~/composables/stream"import { activeActions$, invokeAction } from "~/helpers/actions"import { map } from "rxjs/operators"-import { HoppRequestDocument } from "~/helpers/rest/document"+import { HoppRequestDocument } from "~/helpers/tab/document"import { def as historySync } from "~/lib/sync/history"/**@@ -75,9 +75,17 @@ export class HistorySpotlightSearcherService})[0]+ // Openable via the legacy /graphql page OR the unified workspaceprivate gqlHistoryEntryOpenable = useStreamStatic(- activeActions$.pipe(map((actions) => actions.includes("gql.request.open"))),- activeActions$.value.includes("gql.request.open"),+ activeActions$.pipe(+ map(+ (actions) =>+ actions.includes("gql.request.open") ||+ actions.includes("rest.gql-request.open")+ )+ ),+ activeActions$.value.includes("gql.request.open") ||+ activeActions$.value.includes("rest.gql-request.open"),() => {/* noop */}@@ -120,8 +128,11 @@ export class HistorySpotlightSearcherServiceif (this.restHistoryEntryOpenable.value) {minisearch.addAll(restHistoryStore.value.state- .filter((x) => !!x.updatedOn)- .map((entry, index) => {+ // Index BEFORE filtering — the result id is used to look the entry+ // back up in the unfiltered store, so it must be the store index+ .map((entry, index) => ({ entry, index }))+ .filter(({ entry }) => !!entry.updatedOn)+ .map(({ entry, index }) => {const relTimeString = capitalize(useTimeAgo(entry.updatedOn!, {updateInterval: 0,@@ -141,8 +152,10 @@ export class HistorySpotlightSearcherServiceif (this.gqlHistoryEntryOpenable.value) {minisearch.addAll(graphqlHistoryStore.value.state- .filter((x) => !!x.updatedOn)- .map((entry, index) => {+ // Index BEFORE filtering — see the REST block above+ .map((entry, index) => ({ entry, index }))+ .filter(({ entry }) => !!entry.updatedOn)+ .map(({ entry, index }) => {const relTimeString = capitalize(useTimeAgo(entry.updatedOn!, {updateInterval: 0,@@ -262,9 +275,21 @@ export class HistorySpotlightSearcherServicegraphqlHistoryStore.value.state[parseInt(result.id.split("-")[1])].request- invokeAction("gql.request.open", {- request: req,- })+ // Legacy /graphql page handler when bound; else the unified workspace+ if (activeActions$.value.includes("gql.request.open")) {+ invokeAction("gql.request.open", {+ request: req,+ })+ } else {+ invokeAction("rest.gql-request.open", {+ doc: {+ type: "gql-request",+ request: req,+ isDirty: false,+ cursorPosition: 0,+ },+ })+ }}}}diff --git a/packages/hoppscotch-common/src/services/spotlight/searchers/request.searcher.ts b/packages/hoppscotch-common/src/services/spotlight/searchers/request.searcher.tsindex e066cff3a..1a4aedfe9 100644--- a/packages/hoppscotch-common/src/services/spotlight/searchers/request.searcher.ts+++ b/packages/hoppscotch-common/src/services/spotlight/searchers/request.searcher.ts@@ -19,7 +19,7 @@ import IconPlay from "~icons/lucide/play"import IconRotateCCW from "~icons/lucide/rotate-ccw"import IconSave from "~icons/lucide/save"import { GQLOptionTabs } from "~/components/graphql/RequestOptions.vue"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { Container } from "dioc"type Doc = {@@ -44,15 +44,22 @@ export class RequestSpotlightSearcherService extends StaticSpotlightSearcherServpublic searcherSectionTitle = this.t("shortcut.request.title")private readonly spotlight = this.bind(SpotlightService)- private readonly restTab = this.bind(RESTTabService)+ private readonly workspaceTab = this.bind(WorkspaceTabsService)private route = useRoute()private isRESTPage = computed(() =>this.route.name === "index" &&- this.restTab.currentActiveTab.value.document.type === "request"+ this.workspaceTab.currentActiveTab.value.document.type === "request"+ )+ // Legacy /graphql page OR a gql-request tab on the unified workspace+ private isGQLPage = computed(+ () =>+ this.route.name === "graphql" ||+ (this.route.name === "index" &&+ this.workspaceTab.currentActiveTab.value.document.type ===+ "gql-request"))- private isGQLPage = computed(() => this.route.name === "graphql")private isRESTOrGQLPage = computed(() => this.isRESTPage.value || this.isGQLPage.value)@@ -277,8 +284,9 @@ export class RequestSpotlightSearcherService extends StaticSpotlightSearcherServinvokeAction("request.save-as", {requestType: "rest",request:- this.restTab.currentActiveTab.value?.document.type === "request"- ? this.restTab.currentActiveTab.value?.document.request+ this.workspaceTab.currentActiveTab.value?.document.type ===+ "request"+ ? this.workspaceTab.currentActiveTab.value?.document.request: null,})breakdiff --git a/packages/hoppscotch-common/src/services/spotlight/searchers/tab.searcher.ts b/packages/hoppscotch-common/src/services/spotlight/searchers/tab.searcher.tsindex c5eec15c7..129cc0746 100644--- a/packages/hoppscotch-common/src/services/spotlight/searchers/tab.searcher.ts+++ b/packages/hoppscotch-common/src/services/spotlight/searchers/tab.searcher.ts@@ -16,7 +16,7 @@ import IconArrowRight from "~icons/lucide/arrow-right"import IconChevronsLeft from "~icons/lucide/chevrons-left"import IconChevronsRight from "~icons/lucide/chevrons-right"import { invokeAction } from "~/helpers/actions"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { GQLTabService } from "~/services/tab/graphql"import { Container } from "dioc"import { getKernelMode } from "@hoppscotch/kernel"@@ -49,13 +49,13 @@ export class TabSpotlightSearcherService extends StaticSpotlightSearcherService<() => this.route.name === "index" || this.route.name === "graphql")- private readonly restTab = this.bind(RESTTabService)+ private readonly workspaceTab = this.bind(WorkspaceTabsService)private readonly gqlTab = this.bind(GQLTabService)private isOnlyTab = computed(() =>this.route.name === "graphql"? this.gqlTab.getActiveTabs().value.length === 1- : this.restTab.getActiveTabs().value.length === 1+ : this.workspaceTab.getActiveTabs().value.length === 1)private isDesktopMode = computed(() => getKernelMode() === "desktop")diff --git a/packages/hoppscotch-common/src/services/spotlight/searchers/teamRequest.searcher.ts b/packages/hoppscotch-common/src/services/spotlight/searchers/teamRequest.searcher.tsindex bac2a5e00..7cbac18f5 100644--- a/packages/hoppscotch-common/src/services/spotlight/searchers/teamRequest.searcher.ts+++ b/packages/hoppscotch-common/src/services/spotlight/searchers/teamRequest.searcher.ts@@ -14,9 +14,9 @@ import IconFolder from "~icons/lucide/folder"import IconImport from "~icons/lucide/folder-down"import { WorkspaceService } from "~/services/workspace.service"import RESTTeamRequestEntry from "~/components/app/spotlight/entry/RESTTeamRequestEntry.vue"-import { RESTTabService } from "~/services/tab/rest"+import { WorkspaceTabsService } from "~/services/tab/workspace-tabs"import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"-import { HoppRESTRequest } from "@hoppscotch/data"+import { HoppGQLRequest, HoppRESTRequest, isGQLRequest } from "@hoppscotch/data"import MiniSearch from "minisearch"import { invokeAction } from "~/helpers/actions"@@ -37,7 +37,7 @@ export class TeamsSpotlightSearcherServiceprivate readonly workspaceService = this.bind(WorkspaceService)- private readonly tabs = this.bind(RESTTabService)+ private readonly tabs = this.bind(WorkspaceTabsService)override onServiceInit() {this.spotlight.registerSearcher(this)@@ -233,6 +233,24 @@ export class TeamsSpotlightSearcherServiceif (possibleTab) {this.tabs.setActiveTab(possibleTab.value.id)+ } else if (+ isGQLRequest(selectedRequest.request as HoppRESTRequest | HoppGQLRequest)+ ) {+ // Team collections hold mixed types — route GQL requests to a gql tab+ this.tabs.createNewTab({+ request: cloneDeep(+ selectedRequest.request as unknown as HoppGQLRequest+ ),+ isDirty: false,+ type: "gql-request",+ cursorPosition: 0,+ saveContext: {+ originLocation: "team-collection",+ requestID: selectedRequest.id,+ collectionID: selectedRequest.collectionID,+ },+ inheritedProperties: inheritedProperties,+ })} else {this.tabs.createNewTab({request: cloneDeep(selectedRequest.request as HoppRESTRequest),diff --git a/packages/hoppscotch-common/src/services/tab/__tests__/rest-tab.service.spec.ts b/packages/hoppscotch-common/src/services/tab/__tests__/workspace-tabs.service.spec.tssimilarity index 97%rename from packages/hoppscotch-common/src/services/tab/__tests__/rest-tab.service.spec.tsrename to packages/hoppscotch-common/src/services/tab/__tests__/workspace-tabs.service.spec.tsindex f0b080d9d..4f06e851b 100644--- a/packages/hoppscotch-common/src/services/tab/__tests__/rest-tab.service.spec.ts+++ b/packages/hoppscotch-common/src/services/tab/__tests__/workspace-tabs.service.spec.ts@@ -2,8 +2,8 @@ import { describe, expect, it, vi } from "vitest"import { TestContainer } from "dioc/testing"import { getDefaultRESTRequest } from "~/helpers/rest/default"-import { HoppRESTSaveContext } from "~/helpers/rest/document"-import { RESTTabService } from "../rest"+import { HoppTabSaveContext } from "~/helpers/tab/document"+import { WorkspaceTabsService } from "../workspace-tabs"// The persistence import drags in stores with top-level side effects that// can't run in this bare container; matching never touches it (hoisted mock)@@ -14,12 +14,12 @@ vi.mock("../../persistence", () => ({const makeService = () => {const container = new TestContainer()- return container.bind(RESTTabService)+ return container.bind(WorkspaceTabsService)}const openRequestTab = (- service: RESTTabService,- saveContext: HoppRESTSaveContext,+ service: WorkspaceTabsService,+ saveContext: HoppTabSaveContext,requestFields?: { _ref_id?: string; id?: string }) =>service.createNewTab({@@ -29,7 +29,7 @@ const openRequestTab = (saveContext,})-describe("RESTTabService", () => {+describe("WorkspaceTabsService", () => {describe("getTabRefWithSaveContext", () => {it("matches positionally when neither side has a requestRefID", () => {const service = makeService()diff --git a/packages/hoppscotch-common/src/services/tab/index.ts b/packages/hoppscotch-common/src/services/tab/index.tsindex 0891827ae..b55c08ba0 100644--- a/packages/hoppscotch-common/src/services/tab/index.ts+++ b/packages/hoppscotch-common/src/services/tab/index.ts@@ -1,4 +1,32 @@import { ComputedRef, WritableComputedRef } from "vue"+import type { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"+import type { Workspace } from "../workspace.service"++/**+ * A snapshot of the tab's state for one protocol, taken when the user+ * switches away from it.+ */+export type ProtocolDraft<T> = {+ request: T+ /**+ * The tab's dirty flag at snapshot time. Restoring a draft returns the tab+ * to a state it was already in, so the flag travels with it — a saved+ * request that round-trips REST → GQL → REST comes back clean instead of+ * prompting to save content identical to what's stored.+ */+ isDirty: boolean+}++/**+ * Per-tab shadow drafts of the other protocol's request, used by the+ * REST/GraphQL protocol switcher to preserve in-flight edits across switches.+ * Lives on the tab object so it automatically survives close → reopen and is+ * garbage-collected when the tab is permanently destroyed.+ */+export type ProtocolDrafts = {+ rest?: ProtocolDraft<HoppRESTRequest>+ gql?: ProtocolDraft<HoppGQLRequest>+}/*** Represents a tab in HoppScotch.@@ -9,6 +37,17 @@ export type HoppTab<Doc> = {id: string/** The document associated with the tab. */document: Doc+ /**+ * The workspace this tab is attached to, captured at creation/restore.+ * Set automatically by `WorkspaceTabsService`; standalone tab services+ * (e.g., `GQLTabService` for the legacy `/graphql` page) leave this undefined.+ */+ workspaceHandle?: Workspace+ /**+ * Shadow drafts of the opposite-protocol request for round-trip preservation+ * across `ProtocolSwitcher` swaps. Populated by `WorkspaceTabsService` only.+ */+ protocolDrafts?: ProtocolDrafts}export type PersistableTabState<Doc> = {@@ -16,6 +55,11 @@ export type PersistableTabState<Doc> = {orderedDocs: Array<{tabID: stringdoc: Doc+ /**+ * Opposite-protocol shadow drafts (see `HoppTab.protocolDrafts`) — persisted+ * so a protocol switch's unsaved draft survives a page refresh.+ */+ protocolDrafts?: ProtocolDrafts}>}@@ -91,7 +135,8 @@ export interface TabService<Doc> {* Closes the tab with the specified ID.* @param tabID - The ID of the tab to close.*/- closeTab(tabID: string): void+ /** @returns whether the tab was actually closed (refused for the last open tab) */+ closeTab(tabID: string): boolean/*** Closes all tabs except the one with the specified ID.diff --git a/packages/hoppscotch-common/src/services/tab/rest.ts b/packages/hoppscotch-common/src/services/tab/rest.tsdeleted file mode 100644index c420e5792..000000000--- a/packages/hoppscotch-common/src/services/tab/rest.ts+++ /dev/null@@ -1,171 +0,0 @@-import { Container } from "dioc"-import { computed } from "vue"-import { getDefaultRESTRequest } from "~/helpers/rest/default"-import { HoppRESTSaveContext, HoppTabDocument } from "~/helpers/rest/document"-import { getService } from "~/modules/dioc"-import { PersistenceService, STORE_KEYS } from "../persistence"-import { TabService } from "./tab"-import { HoppTab, PersistableTabState } from "."--export class RESTTabService extends TabService<HoppTabDocument> {- public static readonly ID = "REST_TAB_SERVICE"-- // TODO: Moving this to `onServiceInit` breaks `persistableTabState`- // Figure out how to fix this- constructor(c: Container) {- super(c)-- this.tabMap.set("test", {- id: "test",- document: {- type: "request",- request: getDefaultRESTRequest(),- isDirty: false,- optionTabPreference: "params",- },- })-- this.watchCurrentTabID()- }-- // override persistableTabState to remove response from the document- public override persistableTabState = computed(() => ({- lastActiveTabID: this.currentTabID.value,- orderedDocs: this.tabOrdering.value.map((tabID) => {- const tab = this.tabMap.get(tabID)! // tab ordering is guaranteed to have value for this key-- if (tab.document.type === "example-response") {- return {- tabID: tab.id,- doc: tab.document,- }- }-- if (tab.document.type === "test-runner") {- // Run results are deliberately not persisted: the collection schema- // strips `response`/`testResults`/counters so restored rows come back- // empty anyway, and per-iteration trees can blow the localStorage- // quota. The whole run is dropped; the tab restores ready to run.- return {- tabID: tab.id,- doc: {- ...tab.document,- // The debounced persist fires during a run, so a tab killed- // mid-run would restore as "running". Normalize to "stopped",- // never "idle" — an idle runner tab auto-runs on mount.- status:- tab.document.status === "running"- ? ("stopped" as const)- : tab.document.status,- request: null,- response: null,- // Drop the run outright rather than half of it: an iteration- // list without its result trees restores a summary over an- // empty table.- resultCollection: undefined,- iterationResults: undefined,- selectedIteration: 0,- // Meaningless without the result rows it points into.- selectedRequestPath: undefined,- testRunnerMeta: {- totalRequests: 0,- completedRequests: 0,- totalTests: 0,- passedTests: 0,- failedTests: 0,- totalTime: 0,- },- },- }- }-- return {- tabID: tab.id,- doc: {- ...tab.document,- response: null,- },- }- }),- }))-- protected async loadPersistedState(): Promise<PersistableTabState<HoppTabDocument> | null> {- const persistenceService = getService(PersistenceService)- const savedState = await persistenceService.getNullable<- PersistableTabState<HoppTabDocument>- >(STORE_KEYS.REST_TABS)- return savedState- }-- private matchesSaveContext(- tab: HoppTab<HoppTabDocument>,- ctx: HoppRESTSaveContext- ) {- if (tab.document.type === "test-runner") return false-- // For `team-collection` request id can be considered unique- if (ctx?.originLocation === "team-collection") {- return (- tab.document.saveContext?.originLocation === "team-collection" &&- tab.document.saveContext.requestID === ctx.requestID &&- tab.document.saveContext.exampleID === ctx.exampleID- )- }-- const tabCtx = tab.document.saveContext-- if (tabCtx?.originLocation !== "user-collection") return false- if (tabCtx.exampleID !== ctx?.exampleID) return false-- // A tab whose context predates ref ids is still identified by the request- // it holds. Truthiness, not a null check: some creation paths store `""`,- // which is not an identity.- const tabRefID =- tabCtx.requestRefID ||- (tab.document.type === "request"- ? tab.document.request._ref_id || tab.document.request.id- : undefined)-- // A lookup that names its request is authoritative — a tab with a- // different or missing identity is not that request, even at matching- // coordinates, which may have been reused since the tab was bound.- if (ctx?.requestRefID) {- return tabRefID === ctx.requestRefID- }-- // Position is all that's left when the lookup carries no identity- return (- tabCtx.folderPath === ctx?.folderPath &&- tabCtx.requestIndex === ctx?.requestIndex- )- }-- /**- * Returns every tab matching the save context — a request can be open in- * more than one tab, and a write-back that skips one leaves it holding- * stale content that its next save persists.- */- public getTabsRefWithSaveContext(ctx: HoppRESTSaveContext) {- return Array.from(this.tabMap.values())- .filter((tab) => this.matchesSaveContext(tab, ctx))- .map((tab) => this.getTabRef(tab.id))- }-- public getTabRefWithSaveContext(ctx: HoppRESTSaveContext) {- for (const tab of this.tabMap.values()) {- if (this.matchesSaveContext(tab, ctx)) return this.getTabRef(tab.id)- }-- return null- }-- public getDirtyTabsCount() {- let count = 0-- for (const tab of this.tabMap.values()) {- if (tab.document.isDirty) count++- }-- return count- }-}diff --git a/packages/hoppscotch-common/src/services/tab/tab.ts b/packages/hoppscotch-common/src/services/tab/tab.tsindex f01eeb6c9..dc68b15e7 100644--- a/packages/hoppscotch-common/src/services/tab/tab.ts+++ b/packages/hoppscotch-common/src/services/tab/tab.ts@@ -48,8 +48,8 @@ export abstract class TabService<Doc>},})- public currentActiveTab = computed(- () => this.tabMap.get(this.currentTabID.value)!+ public currentActiveTab = computed(() =>+ this.tabMap.get(this.currentTabID.value)!) // Guaranteed to not be undefinedprotected watchCurrentTabID() {@@ -180,19 +180,19 @@ export abstract class TabService<Doc>return this.tabOrdering.value}- public closeTab(tabID: string) {+ public closeTab(tabID: string): boolean {if (!this.tabMap.has(tabID)) {console.warn(`Tried to close a tab which does not exist (tab id: ${tabID})`)- return+ return false}if (this.tabOrdering.value.length === 1) {console.warn(`Tried to close the only tab open, which is not allowed. (tab id: ${tabID})`)- return+ return false}const tabIndex = this.tabOrdering.value.indexOf(tabID)@@ -213,6 +213,8 @@ export abstract class TabService<Doc>nextTick(() => {this.tabMap.delete(tabID)})++ return true}public closeOtherTabs(tabID: string) {diff --git a/packages/hoppscotch-common/src/services/tab/workspace-tabs.ts b/packages/hoppscotch-common/src/services/tab/workspace-tabs.tsnew file mode 100644index 000000000..7e083eeb7--- /dev/null+++ b/packages/hoppscotch-common/src/services/tab/workspace-tabs.ts@@ -0,0 +1,359 @@+import { Container } from "dioc"+import { computed, ref, readonly, type Ref } from "vue"+import { cloneDeep } from "lodash-es"+import type { HoppGQLRequest, HoppRESTRequest } from "@hoppscotch/data"+import { getDefaultRESTRequest } from "~/helpers/rest/default"+import { HoppTabSaveContext, HoppTabDocument } from "~/helpers/tab/document"+import { getService } from "~/modules/dioc"+import { PersistenceService, STORE_KEYS } from "../persistence"+import type { Workspace } from "../workspace.service"+import { TabService } from "./tab"+import { HoppTab, PersistableTabState, ProtocolDrafts } from "."++export type { ProtocolDrafts }++/**+ * Tab service for the unified workspace tab system.+ *+ * Hosts both REST request tabs (`type: "request"`) and GraphQL request tabs+ * (`type: "gql-request"`) alongside other unified document types+ * (`example-response`, `test-runner`, ...). The standalone `/graphql` page+ * keeps its own `GQLTabService`; do not route unified flows through that.+ *+ * `attachedWorkspace` records the workspace these tabs belong to so future+ * features can scope/filter tabs per workspace. Today it is purely+ * informational — kept in sync with `WorkspaceService.currentWorkspace`.+ */+export class WorkspaceTabsService extends TabService<HoppTabDocument> {+ public static readonly ID = "WORKSPACE_TABS_SERVICE"++ // Workspace this tab service is attached to. Mirrors `WorkspaceService.currentWorkspace`.+ // Forward-looking: future tab features may scope tabs by workspace.+ private readonly _attachedWorkspace: Ref<Workspace> = ref<Workspace>({+ type: "personal",+ })+ public readonly attachedWorkspace = readonly(this._attachedWorkspace)++ // TODO: Moving this to `onServiceInit` breaks `persistableTabState`+ // Figure out how to fix this+ constructor(c: Container) {+ super(c)++ this.tabMap.set("test", {+ id: "test",+ document: {+ type: "request",+ request: getDefaultRESTRequest(),+ isDirty: false,+ optionTabPreference: "params",+ },+ })++ this.watchCurrentTabID()+ }++ /**+ * Attach the given workspace to this tab service. Called by the workspace+ * switcher whenever the current workspace changes.+ *+ * Semantics — IMPORTANT, fidelity is best-effort by design:+ * - **New tabs** created after this call are tagged with `workspace`.+ * - **Existing tabs WITH** an explicit `workspaceHandle` keep it (a tab+ * created in workspace A doesn't silently rebrand when switching to B).+ * - **Existing tabs WITHOUT** a `workspaceHandle` (e.g. restored from+ * persistence before any workspace was attached) get back-filled with+ * `workspace`.+ *+ * `workspaceHandle` is intentionally NOT persisted: if the user reloads+ * with team-A tabs persisted, those tabs come back tagged with whatever+ * workspace is active at restore time — typically `personal` since+ * `WorkspaceService` doesn't currently persist `_currentWorkspace`.+ * Cross-workspace tab fidelity across cold boots is therefore+ * approximate. If full fidelity becomes a requirement, persist+ * `workspaceHandle` alongside the tab document and migrate the schema.+ */+ public attachToWorkspace(workspace: Workspace) {+ this._attachedWorkspace.value = workspace+ for (const id of this.tabMap.keys()) {+ const stored = this.tabMap.get(id)+ if (stored && !stored.workspaceHandle) {+ stored.workspaceHandle = workspace+ }+ }+ }++ /**+ * Override to tag newly-created tabs with the currently attached workspace.+ *+ * The assignment must go through the reactive proxy in `tabMap` (not the raw+ * `tab` reference returned by `super.createNewTab`) so Vue consumers reading+ * via `tabMap.get(id).workspaceHandle` actually see the change.+ */+ public override createNewTab(+ document: HoppTabDocument,+ switchToIt = true+ ): HoppTab<HoppTabDocument> {+ const tab = super.createNewTab(document, switchToIt)+ const stored = this.tabMap.get(tab.id)+ if (stored) stored.workspaceHandle = this._attachedWorkspace.value+ return tab+ }++ /**+ * Override to tag restored tabs with the currently attached workspace.+ * `workspaceHandle` is intentionally not persisted — fidelity across boots+ * is best-effort and tabs adopt whatever workspace is active at restore time.+ *+ * Iterates via `tabMap` so writes go through the reactive proxy.+ */+ public override loadTabsFromPersistedState(+ data: PersistableTabState<HoppTabDocument>+ ): void {+ super.loadTabsFromPersistedState(data)++ const workspace = this._attachedWorkspace.value+ for (const id of this.tabMap.keys()) {+ const stored = this.tabMap.get(id)+ if (stored) stored.workspaceHandle = workspace+ }++ // Rehydrate opposite-protocol shadow drafts (the base loader only+ // restores {tabID, doc})+ for (const entry of data?.orderedDocs ?? []) {+ if (entry.protocolDrafts) {+ const stored = this.tabMap.get(entry.tabID)+ if (stored) stored.protocolDrafts = entry.protocolDrafts+ }+ }+ }++ /**+ * Read the protocol drafts for a given tab. Returns `undefined` if no drafts+ * have been stored for the tab yet. Drafts live on the tab object, so they+ * automatically survive `closeTab` → `reopenClosedTab` and are garbage-+ * collected when the tab is permanently destroyed.+ */+ public getProtocolDraft(tabID: string): ProtocolDrafts | undefined {+ return this.tabMap.get(tabID)?.protocolDrafts+ }++ /**+ * Snapshot a request, plus the tab's dirty flag, as the draft for one+ * protocol. Stored as a deep clone so subsequent mutations to the original+ * request don't leak into the draft.+ */+ public setProtocolDraft(+ tabID: string,+ kind: "rest",+ request: HoppRESTRequest,+ isDirty: boolean+ ): void+ public setProtocolDraft(+ tabID: string,+ kind: "gql",+ request: HoppGQLRequest,+ isDirty: boolean+ ): void+ public setProtocolDraft(+ tabID: string,+ kind: "rest" | "gql",+ request: HoppRESTRequest | HoppGQLRequest,+ isDirty: boolean+ ): void {+ const tab = this.tabMap.get(tabID)+ if (!tab) return+ const drafts = tab.protocolDrafts ?? {}+ if (kind === "rest") {+ drafts.rest = { request: cloneDeep(request as HoppRESTRequest), isDirty }+ } else {+ drafts.gql = { request: cloneDeep(request as HoppGQLRequest), isDirty }+ }+ tab.protocolDrafts = drafts+ }++ /**+ * Drop both protocol drafts for a tab. NOT called automatically on save —+ * round-trip preservation is the point of drafts, so successful saves leave+ * the opposite-protocol draft intact. Intended for an explicit user action+ * (e.g. a future "reset to defaults" affordance) or programmatic cleanup.+ */+ public clearProtocolDrafts(tabID: string): void {+ const tab = this.tabMap.get(tabID)+ if (tab) tab.protocolDrafts = undefined+ }++ // override persistableTabState to remove response from the document+ public override persistableTabState = computed(() => ({+ lastActiveTabID: this.currentTabID.value,+ orderedDocs: this.tabOrdering.value.map((tabID) => {+ const tab = this.tabMap.get(tabID)! // tab ordering is guaranteed to have value for this key++ // Persist the opposite-protocol shadow draft (if any) so the unsaved+ // pre-switch request survives a page refresh like the document does+ const protocolDrafts = tab.protocolDrafts++ if (+ tab.document.type === "example-response" ||+ tab.document.type === "gql-example-response"+ ) {+ return {+ tabID: tab.id,+ doc: tab.document,+ protocolDrafts,+ }+ }++ if (tab.document.type === "test-runner") {+ // Run results are deliberately not persisted: the collection schema+ // strips `response`/`testResults`/counters so restored rows come back+ // empty anyway, and per-iteration trees can blow the localStorage+ // quota. The whole run is dropped; the tab restores ready to run.+ return {+ tabID: tab.id,+ doc: {+ ...tab.document,+ // The debounced persist fires during a run, so a tab killed+ // mid-run would restore as "running". Normalize to "stopped",+ // never "idle" — an idle runner tab auto-runs on mount.+ status:+ tab.document.status === "running"+ ? ("stopped" as const)+ : tab.document.status,+ request: null,+ response: null,+ // Drop the run outright rather than half of it: an iteration+ // list without its result trees restores a summary over an+ // empty table.+ resultCollection: undefined,+ iterationResults: undefined,+ selectedIteration: 0,+ // Meaningless without the result rows it points into.+ selectedRequestPath: undefined,+ testRunnerMeta: {+ totalRequests: 0,+ completedRequests: 0,+ totalTests: 0,+ passedTests: 0,+ failedTests: 0,+ totalTime: 0,+ },+ },+ protocolDrafts,+ }+ }++ if (tab.document.type === "gql-request") {+ return {+ tabID: tab.id,+ doc: {+ ...tab.document,+ response: null,+ // see the sentinel note on the request-doc branch below+ testResults:+ tab.document.testResults === null+ ? undefined+ : tab.document.testResults,+ },+ protocolDrafts,+ }+ }++ // REST + GQL request docs+ return {+ tabID: tab.id,+ doc: {+ ...tab.document,+ response: null,+ // `null` is the run-in-flight sentinel — persisting it verbatim+ // would restore into a permanent loading state with no run to+ // ever clear it+ testResults:+ tab.document.testResults === null+ ? undefined+ : tab.document.testResults,+ },+ protocolDrafts,+ }+ }),+ }))++ protected async loadPersistedState(): Promise<PersistableTabState<HoppTabDocument> | null> {+ const persistenceService = getService(PersistenceService)+ const savedState = await persistenceService.getNullable<+ PersistableTabState<HoppTabDocument>+ >(STORE_KEYS.REST_TABS)+ return savedState+ }++ private matchesSaveContext(+ tab: HoppTab<HoppTabDocument>,+ ctx: HoppTabSaveContext+ ) {+ if (tab.document.type === "test-runner") return false++ // For `team-collection` request id can be considered unique+ if (ctx?.originLocation === "team-collection") {+ return (+ tab.document.saveContext?.originLocation === "team-collection" &&+ tab.document.saveContext.requestID === ctx.requestID &&+ tab.document.saveContext.exampleID === ctx.exampleID+ )+ }++ const tabCtx = tab.document.saveContext++ if (tabCtx?.originLocation !== "user-collection") return false+ if (tabCtx.exampleID !== ctx?.exampleID) return false++ // A tab whose context predates ref ids is still identified by the request+ // it holds. Truthiness, not a null check: some creation paths store `""`,+ // which is not an identity.+ const tabRefID =+ tabCtx.requestRefID ||+ (tab.document.type === "request"+ ? tab.document.request._ref_id || tab.document.request.id+ : undefined)++ // A lookup that names its request is authoritative — a tab with a+ // different or missing identity is not that request, even at matching+ // coordinates, which may have been reused since the tab was bound.+ if (ctx?.requestRefID) {+ return tabRefID === ctx.requestRefID+ }++ // Position is all that's left when the lookup carries no identity+ return (+ tabCtx.folderPath === ctx?.folderPath &&+ tabCtx.requestIndex === ctx?.requestIndex+ )+ }++ /**+ * Returns every tab matching the save context — a request can be open in+ * more than one tab, and a write-back that skips one leaves it holding+ * stale content that its next save persists.+ */+ public getTabsRefWithSaveContext(ctx: HoppTabSaveContext) {+ return Array.from(this.tabMap.values())+ .filter((tab) => this.matchesSaveContext(tab, ctx))+ .map((tab) => this.getTabRef(tab.id))+ }++ public getTabRefWithSaveContext(ctx: HoppTabSaveContext) {+ for (const tab of this.tabMap.values()) {+ if (this.matchesSaveContext(tab, ctx)) return this.getTabRef(tab.id)+ }++ return null+ }++ public getDirtyTabsCount() {+ let count = 0++ for (const tab of this.tabMap.values()) {+ if (tab.document.isDirty) count+++ }++ return count+ }+}diff --git a/packages/hoppscotch-common/src/services/team-collection.service.ts b/packages/hoppscotch-common/src/services/team-collection.service.tsindex a10852454..8ad31affb 100644--- a/packages/hoppscotch-common/src/services/team-collection.service.ts+++ b/packages/hoppscotch-common/src/services/team-collection.service.ts@@ -1,6 +1,6 @@import * as E from "fp-ts/Either"import { Subscription } from "rxjs"-import { HoppCollectionVariable, translateToNewRequest } from "@hoppscotch/data"+import { HoppCollectionVariable } from "@hoppscotch/data"import { pull, remove } from "lodash-es"import { Subscription as WSubscription } from "wonka"import {@@ -23,7 +23,10 @@ import {import { SecretEnvironmentService } from "~/services/secret-environment.service"import { CurrentValueService } from "~/services/current-environment-value.service"import { TeamCollection } from "~/helpers/teams/TeamCollection"-import { TeamRequest } from "~/helpers/teams/TeamRequest"+import {+ TeamRequest,+ normalizeTeamRequestBody,+} from "~/helpers/teams/TeamRequest"import { runGQLQuery, runGQLSubscription } from "~/helpers/backend/GQLClient"import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"import { ref, watch } from "vue"@@ -531,10 +534,12 @@ export class TeamCollectionsService extends Service<void> {// Collection is not expandedif (!collection.requests) return+ // `currentRequest` was already normalized by the subscription handler+ // (`teamRequestMoved$` → `normalizeTeamRequestBody`); pass through verbatim.this.addRequest({id: request.id,collectionID: request.collectionID,- request: translateToNewRequest(request.request),+ request: currentRequest,title: request.title,})}@@ -782,8 +787,8 @@ export class TeamCollectionsService extends Service<void> {this.addRequest({id: result.right.teamRequestAdded.id,collectionID: result.right.teamRequestAdded.collectionID,- request: translateToNewRequest(- JSON.parse(result.right.teamRequestAdded.request)+ request: normalizeTeamRequestBody(+ result.right.teamRequestAdded.request),title: result.right.teamRequestAdded.title,})@@ -806,7 +811,9 @@ export class TeamCollectionsService extends Service<void> {this.updateRequest({id: result.right.teamRequestUpdated.id,collectionID: result.right.teamRequestUpdated.collectionID,- request: JSON.parse(result.right.teamRequestUpdated.request),+ request: normalizeTeamRequestBody(+ result.right.teamRequestUpdated.request+ ),title: result.right.teamRequestUpdated.title,})})@@ -848,7 +855,7 @@ export class TeamCollectionsService extends Service<void> {id: requestMoved.id,collectionID: requestMoved.collectionID,title: requestMoved.title,- request: JSON.parse(requestMoved.request),+ request: normalizeTeamRequestBody(requestMoved.request),}this.moveRequest(request)@@ -1041,14 +1048,12 @@ export class TeamCollectionsService extends Service<void> {}requests.push(- ...data.right.requestsInCollection.map<TeamRequest>((el: any) => {- return {- id: el.id,- collectionID: collection.id,- title: el.title,- request: translateToNewRequest(JSON.parse(el.request)),- }- })+ ...data.right.requestsInCollection.map<TeamRequest>((el: any) => ({+ id: el.id,+ collectionID: collection.id,+ title: el.title,+ request: normalizeTeamRequestBody(el.request),+ })))if (data.right.requestsInCollection.length !== TEAMS_BACKEND_PAGE_SIZE)diff --git a/packages/hoppscotch-common/src/services/test-runner/__tests__/plan-collection.spec.ts b/packages/hoppscotch-common/src/services/test-runner/__tests__/plan-collection.spec.tsindex 1157850de..33c3420a4 100644--- a/packages/hoppscotch-common/src/services/test-runner/__tests__/plan-collection.spec.ts+++ b/packages/hoppscotch-common/src/services/test-runner/__tests__/plan-collection.spec.ts@@ -1,10 +1,12 @@import { afterEach, describe, expect, test, vi } from "vitest"// RequestRunner drags in the network/kernel stack; the plan walk never-// touches it.+// touches it. `executedResponses$` must exist on the mock — newstore/history+// subscribes to it at module load.vi.mock("~/helpers/RequestRunner", () => ({captureInitialEnvironmentState: vi.fn(),runTestRunnerRequest: vi.fn(),+ executedResponses$: { subscribe: vi.fn() },}))import { getService } from "~/modules/dioc"@@ -73,6 +75,35 @@ const node = (testScript: "",})+const gqlRequest = (name: string) => ({+ v: 10,+ name,+ _ref_id: `gql-${name}`,+ url: "https://example.com/graphql",+ query: "query { hello }",+ variables: "{}",+ headers: [+ {+ key: "X-Own",+ value: "own",+ active: true,+ description: "",+ },+ ],+ auth: { authType: "inherit", authActive: true },+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",+})++const header = (key: string, value: string) => ({+ key,+ value,+ active: true,+ description: "",+})+const stored = (key: string, currentValue: string, varIndex: number) => ({key,currentValue,@@ -198,6 +229,88 @@ describe("TestRunnerService.planCollection — inherited variable resolution", (})})+describe("TestRunnerService.planCollection — GQL requests in unified collections", () => {+ const planWithHeaders = (collection: unknown, parentHeaders: unknown[]) =>+ (service as any).planCollection(+ collection,+ new Set<string>(),+ false,+ [],+ [],+ parentHeaders,+ undefined,+ []+ )++ test("GQL entries keep their own headers unmerged; REST siblings get inherited headers pre-merged", () => {+ const tree = node(+ { refId: "plan-gql" },+ [],+ [request("rest-leaf"), gqlRequest("gql-leaf") as any]+ )+ tree.headers = [header("X-Coll", "coll")] as any++ const planned = planWithHeaders(tree, [header("X-Parent", "parent")])+ expect(planned).toHaveLength(2)++ const [rest, gql] = planned++ // REST executor expects inherited headers pre-merged into the request+ expect(rest.request.headers.map((h: any) => h.key)).toEqual([+ "X-Parent",+ "X-Coll",+ ])++ // GQL executor slots auth headers between request and inherited headers+ // itself — the planned request must carry ONLY its own headers, with the+ // inherited ones threaded separately on the entry+ expect(gql.request.headers.map((h: any) => h.key)).toEqual(["X-Own"])+ expect(gql.inheritedHeaders.map((h: any) => h.key)).toEqual([+ "X-Parent",+ "X-Coll",+ ])+ })++ test("GQL auth: inherit resolves to the collection's effective auth", () => {+ const tree = node(+ { refId: "plan-gql-auth" },+ [],+ [gqlRequest("gql-auth-leaf") as any]+ )+ tree.auth = { authType: "basic", authActive: true } as any++ const [planned] = planCollection(tree)++ expect(planned.request.auth).toEqual({+ authType: "basic",+ authActive: true,+ })+ })++ test("selection IDs resolve for GQL rows via _ref_id", () => {+ const tree = node(+ { refId: "plan-gql-sel" },+ [],+ [request("rest-skip"), gqlRequest("gql-pick") as any]+ )++ const planned = (service as any).planCollection(+ tree,+ new Set<string>(["gql-gql-pick"]),+ true,+ [],+ [],+ undefined,+ undefined,+ []+ )++ expect(planned).toHaveLength(1)+ expect(planned[0].id).toBe("gql-gql-pick")+ expect(planned[0].request.name).toBe("gql-pick")+ })+})+describe("TestRunnerService.getTestResultInfo — pass/fail counting", () => {const count = (result: unknown) => (service as any).getTestResultInfo(result)diff --git a/packages/hoppscotch-common/src/services/test-runner/__tests__/run-gql-request.spec.ts b/packages/hoppscotch-common/src/services/test-runner/__tests__/run-gql-request.spec.tsnew file mode 100644index 000000000..a303a8b5e--- /dev/null+++ b/packages/hoppscotch-common/src/services/test-runner/__tests__/run-gql-request.spec.ts@@ -0,0 +1,236 @@+import * as E from "fp-ts/Either"+import { ref } from "vue"+import { beforeEach, describe, expect, test, vi } from "vitest"++// RequestRunner drags in the network/kernel stack; these tests only exercise+// the service's GQL result handling. `executedResponses$` must exist on the+// mock — newstore/history subscribes to it at module load.+vi.mock("~/helpers/RequestRunner", () => ({+ captureInitialEnvironmentState: vi.fn(() => ({ initial: "env-state" })),+ runTestRunnerRequest: vi.fn(),+ executedResponses$: { subscribe: vi.fn() },+}))++vi.mock("~/helpers/graphql/testRunner", () => ({+ runTestRunnerGQLRequest: vi.fn(),+}))++import { runTestRunnerGQLRequest } from "~/helpers/graphql/testRunner"+import { getService } from "~/modules/dioc"+import { TestRunnerService } from "../test-runner.service"++const service = getService(TestRunnerService)+const mockedRun = vi.mocked(runTestRunnerGQLRequest)++const gqlRequest = {+ v: 10,+ name: "gql-under-test",+ _ref_id: "gql-1",+ url: "https://example.com/graphql",+ query: "query { hello }",+ variables: "{}",+ headers: [],+ auth: { authType: "none", authActive: false },+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",+}++const emptyMeta = () => ({+ totalRequests: 0,+ completedRequests: 0,+ totalTests: 0,+ passedTests: 0,+ failedTests: 0,+ totalTime: 0,+})++const makeTab = () =>+ ref({+ id: "runner-tab",+ document: {+ type: "test-runner" as const,+ status: "running" as const,+ resultCollection: {+ v: 12,+ name: "run",+ folders: [],+ requests: [+ {+ ...gqlRequest,+ type: "test-response",+ passedTests: 0,+ failedTests: 0,+ isLoading: false,+ },+ ],+ headers: [],+ variables: [],+ auth: { authType: "none", authActive: false },+ },+ testRunnerMeta: emptyMeta(),+ },+ }) as any++const makeOptions = (overrides: Record<string, unknown> = {}) => ({+ stopRef: ref(false),+ delay: 0,+ iterations: 1,+ keepVariableValues: false,+ persistResponses: true,+ stopOnError: false,+ ...overrides,+})++const passingTestResult = (overrides: Record<string, unknown> = {}) => ({+ description: "",+ expectResults: [+ { status: "pass", message: "" },+ { status: "pass", message: "" },+ { status: "fail", message: "" },+ ],+ tests: [],+ envDiff: {+ global: { additions: [], deletions: [], updations: [] },+ selected: { additions: [], deletions: [], updations: [] },+ },+ scriptError: false,+ consoleEntries: [],+ ...overrides,+})++const successResponse = { type: "success", meta: { responseDuration: 42 } }++const runGQL = (+ tab: ReturnType<typeof makeTab>,+ options: ReturnType<typeof makeOptions>,+ iterationMeta = emptyMeta(),+ iterationVars: unknown[] = []+) =>+ (service as any).runTestGQLRequest(+ tab,+ gqlRequest,+ options,+ [0],+ iterationMeta,+ iterationVars+ )++beforeEach(() => {+ mockedRun.mockReset()+})++describe("TestRunnerService.runTestGQLRequest", () => {+ test("forwards dataset iteration variables to the GQL executor", async () => {+ mockedRun.mockResolvedValue(+ E.right({+ response: successResponse,+ testResult: passingTestResult(),+ }) as any+ )++ const iterationVars = [+ {+ key: "col",+ initialValue: "row-1",+ currentValue: "row-1",+ secret: false,+ },+ ]+ await runGQL(makeTab(), makeOptions(), emptyMeta(), iterationVars)++ expect(mockedRun).toHaveBeenCalledTimes(1)+ // (request, keepVariableValues, inheritedVariables, envState,+ // inheritedHeaders, preScripts, testScripts, iterationVars)+ expect(mockedRun.mock.calls[0][7]).toBe(iterationVars)+ // Pins the positional threading — a future arg shuffle that displaces the+ // captured env state (or iterationVars) must fail here+ expect(mockedRun.mock.calls[0][3]).toEqual({ initial: "env-state" })+ })++ test("writes per-row pass/fail counts and tallies both run metas", async () => {+ mockedRun.mockResolvedValue(+ E.right({+ response: successResponse,+ testResult: passingTestResult(),+ }) as any+ )++ const tab = makeTab()+ const iterationMeta = emptyMeta()+ await runGQL(tab, makeOptions(), iterationMeta)++ const row = tab.value.document.resultCollection.requests[0]+ expect(row.passedTests).toBe(2)+ expect(row.failedTests).toBe(1)+ expect(row.testResults).toBeTruthy()+ expect(row.isLoading).toBe(false)++ for (const meta of [tab.value.document.testRunnerMeta, iterationMeta]) {+ expect(meta.totalTests).toBe(3)+ expect(meta.passedTests).toBe(2)+ expect(meta.failedTests).toBe(1)+ expect(meta.completedRequests).toBe(1)+ expect(meta.totalTime).toBe(42)+ }+ })++ test("stopOnError halts the run on a GQL test-script failure", async () => {+ mockedRun.mockResolvedValue(+ E.right({+ response: successResponse,+ testResult: passingTestResult({+ expectResults: [],+ scriptError: true,+ }),+ }) as any+ )++ const tab = makeTab()+ await expect(+ runGQL(tab, makeOptions({ stopOnError: true }))+ ).rejects.toThrow("Test execution stopped due to error")++ expect(tab.value.document.status).toBe("stopped")+ // The row and meta record the request before the halt+ expect(tab.value.document.testRunnerMeta.failedTests).toBe(1)+ expect(tab.value.document.resultCollection.requests[0].isLoading).toBe(+ false+ )+ })++ test("a stop taken mid-flight clears the row's loading spinner", async () => {+ const options = makeOptions()+ mockedRun.mockImplementation(async () => {+ options.stopRef.value = true+ return E.right({+ response: successResponse,+ testResult: passingTestResult(),+ }) as any+ })++ const tab = makeTab()+ await expect(runGQL(tab, options)).rejects.toThrow("Test execution stopped")++ expect(tab.value.document.resultCollection.requests[0].isLoading).toBe(+ false+ )+ })++ test("executor failures mark the row and honor stopOnError", async () => {+ mockedRun.mockResolvedValue(+ E.left({ type: "subscription_unsupported" }) as any+ )++ const tab = makeTab()+ await expect(+ runGQL(tab, makeOptions({ stopOnError: true }))+ ).rejects.toThrow("Test execution stopped due to error")++ const row = tab.value.document.resultCollection.requests[0]+ expect(row.error).toMatch(/subscriptions are not supported/)+ expect(row.isLoading).toBe(false)+ expect(tab.value.document.status).toBe("stopped")+ })+})diff --git a/packages/hoppscotch-common/src/services/test-runner/test-runner.service.ts b/packages/hoppscotch-common/src/services/test-runner/test-runner.service.tsindex 5a92fac53..3ac83c43e 100644--- a/packages/hoppscotch-common/src/services/test-runner/test-runner.service.ts+++ b/packages/hoppscotch-common/src/services/test-runner/test-runner.service.ts@@ -2,6 +2,7 @@ import {HoppCollection,HoppCollectionVariable,Environment,+ HoppGQLRequest,HoppRESTHeaders,HoppRESTRequest,} from "@hoppscotch/data"@@ -9,17 +10,19 @@ import { Service } from "dioc"import { hasActualScript } from "@hoppscotch/js-sandbox/scripting"import * as E from "fp-ts/Either"import { cloneDeep } from "lodash-es"-import { Ref } from "vue"+import { nextTick, Ref } from "vue"import {captureInitialEnvironmentState,runTestRunnerRequest,type InitialEnvironmentState,} from "~/helpers/RequestRunner"+import { runTestRunnerGQLRequest } from "~/helpers/graphql/testRunner"+import { isGQLRequest } from "~/helpers/request-type"import {HoppTestRunnerDocument,TestRunnerMeta,TestRunnerConfig,-} from "~/helpers/rest/document"+} from "~/helpers/tab/document"import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"import { HoppTestData, HoppTestResult } from "~/helpers/types/HoppTestResult"import { HoppTab } from "../tab"@@ -57,9 +60,16 @@ type PlannedRequest = {inheritedVariables: HoppCollectionVariable[]inheritedPreRequestScripts: string[]inheritedTestScripts: string[]+ /** Kept unmerged for GQL requests — their executor slots auth headers+ * between request and inherited headers itself. */+ inheritedHeaders: HoppRESTHeaders}-export type TestRunnerRequest = HoppRESTRequest & {+/**+ * Run-result decorations attached to every request in the result tree —+ * shared by both protocols.+ */+type TestRunnerResultFields = {type: "test-response"response?: HoppRESTResponse | nulltestResults?: HoppTestResult | null@@ -73,6 +83,16 @@ export type TestRunnerRequest = HoppRESTRequest & {folderPath?: string[]}+/**+ * A request inside a collection run. Unified collections hold both REST and+ * GraphQL requests in the same `requests` array, so the runner discriminates+ * per entry by shape (`isGQLRequest`). GraphQL responses are shaped as+ * `HoppRESTResponse` (GraphQL-over-HTTP is a POST) so the result tree and+ * response viewer render both protocols identically.+ */+export type TestRunnerRequest = (HoppRESTRequest | HoppGQLRequest) &+ TestRunnerResultFields+function delay(timeMS: number) {return new Promise((resolve, reject) => {const timeout = setTimeout(resolve, timeMS)@@ -114,7 +134,7 @@ export class TestRunnerService extends Service {}private shouldRunRequest(- request: HoppRESTRequest,+ request: HoppRESTRequest | HoppGQLRequest,path: number[],selectedIDs: Set<string>,selectionActive: boolean@@ -439,6 +459,15 @@ export class TestRunnerService extends Service {continue}+ // Cast note: collection auth is the full REST auth union, so a GQL+ // request inheriting (say) digest auth temporarily violates the+ // HoppGQLAuth type. That's deliberate — the GQL run executor signs+ // with the REST auth generators, which cover the full union.+ //+ // Headers: REST pre-merges inherited headers into the request (the+ // REST executor expects that). GQL keeps its own headers and gets the+ // inherited ones separately, so the executor can slot auth headers+ // between them (precedence: request > auth > inherited).planned.push({id: getRequestSelectionID(request, sourcePath),request: {@@ -447,13 +476,16 @@ export class TestRunnerService extends Service {request.auth.authType === "inherit" && request.auth.authActive? inheritedAuth: request.auth,- headers: [...inheritedHeaders, ...request.headers],- },+ headers: isGQLRequest(request)+ ? request.headers+ : [...inheritedHeaders, ...request.headers],+ } as TestRunnerRequest,collection,folderPath,inheritedVariables,inheritedPreRequestScripts,inheritedTestScripts,+ inheritedHeaders,})}@@ -491,7 +523,8 @@ export class TestRunnerService extends Service {entry.inheritedVariables,entry.inheritedPreRequestScripts,entry.inheritedTestScripts,- iterationEnvState+ iterationEnvState,+ entry.inheritedHeaders)if (options.delay && options.delay > 0) {@@ -564,12 +597,32 @@ export class TestRunnerService extends Service {inheritedVariables: HoppCollectionVariable[] = [],inheritedPreRequestScripts: string[] = [],inheritedTestScripts: string[] = [],- iterationEnvState?: InitialEnvironmentState+ iterationEnvState?: InitialEnvironmentState,+ inheritedHeaders: HoppRESTHeaders = []) {if (options.stopRef?.value) {throw new Error("Test execution stopped")}+ // GraphQL requests take their own execution path (HTTP POST, response+ // shaped as HoppRESTResponse so the shared result UI renders it) with+ // the same script stages as REST.+ if (isGQLRequest(request)) {+ return this.runTestGQLRequest(+ tab,+ request as HoppGQLRequest,+ options,+ path,+ iterationMeta,+ iterationVars,+ inheritedVariables,+ inheritedHeaders,+ inheritedPreRequestScripts,+ inheritedTestScripts,+ iterationEnvState+ )+ }+try {// Update request status in the result collectionthis.updateRequestAtPath(tab.value.document.resultCollection!, path, {@@ -584,7 +637,7 @@ export class TestRunnerService extends Service {iterationEnvState ?? captureInitialEnvironmentState()const results = await runTestRunnerRequest(- request,+ request as HoppRESTRequest,options.keepVariableValues,inheritedVariables,initialEnvironmentState,@@ -678,6 +731,132 @@ export class TestRunnerService extends Service {}}+ /**+ * Executes a GraphQL request inside a run. Mirrors `runTestRequest`'s+ * result handling including the script stages — pre-request/test scripts+ * run through the shared sandbox and contribute test counts to the run+ * meta like REST requests do.+ */+ private async runTestGQLRequest(+ tab: Ref<HoppTab<HoppTestRunnerDocument>>,+ request: HoppGQLRequest,+ options: TestRunnerOptions,+ path: number[],+ iterationMeta: TestRunnerMeta,+ iterationVars: Environment["variables"] = [],+ inheritedVariables: HoppCollectionVariable[] = [],+ inheritedHeaders: HoppRESTHeaders = [],+ inheritedPreRequestScripts: string[] = [],+ inheritedTestScripts: string[] = [],+ iterationEnvState?: InitialEnvironmentState+ ) {+ try {+ this.updateRequestAtPath(tab.value.document.resultCollection!, path, {+ isLoading: true,+ error: undefined,+ })++ await nextTick()++ // Reuse the per-iteration snapshot when variable values aren't+ // persisted; otherwise re-capture so this request sees env changes+ // persisted by earlier requests in the run.+ const initialEnvironmentState =+ iterationEnvState ?? captureInitialEnvironmentState()++ const results = await runTestRunnerGQLRequest(+ request,+ options.keepVariableValues,+ inheritedVariables,+ initialEnvironmentState,+ inheritedHeaders,+ inheritedPreRequestScripts,+ inheritedTestScripts,+ iterationVars+ )++ if (options.stopRef?.value) {+ // Clear the loading flag so a stop taken mid-flight doesn't leave a+ // permanent spinner on the row.+ this.updateRequestAtPath(tab.value.document.resultCollection!, path, {+ isLoading: false,+ })+ throw new Error("Test execution stopped")+ }++ if (E.isRight(results)) {+ const { response, testResult } = results.right++ // Tally test counts into the run meta — REST parity+ // (HoppTestResult is structurally a HoppTestData root node)+ const { passed, failed } = this.getTestResultInfo(testResult)+ tab.value.document.testRunnerMeta.totalTests += passed + failed+ tab.value.document.testRunnerMeta.passedTests += passed+ tab.value.document.testRunnerMeta.failedTests += failed+ iterationMeta.totalTests += passed + failed+ iterationMeta.passedTests += passed+ iterationMeta.failedTests += failed++ this.updateRequestAtPath(tab.value.document.resultCollection!, path, {+ response: options.persistResponses ? response : null,+ testResults: testResult,+ passedTests: passed,+ failedTests: failed,+ isLoading: false,+ })++ if (response.type === "success") {+ tab.value.document.testRunnerMeta.totalTime +=+ response.meta.responseDuration+ tab.value.document.testRunnerMeta.completedRequests += 1+ iterationMeta.totalTime += response.meta.responseDuration+ iterationMeta.completedRequests += 1+ }++ // A post-request script failure arrives as a Right with `scriptError`+ // set, so the Left/stop-on-error branch below never sees it. Halt+ // here after the row and meta have recorded the request — REST parity.+ if (options.stopOnError && testResult.scriptError) {+ tab.value.document.status = "stopped"+ throw new Error("Test execution stopped due to error")+ }+ } else {+ const errorMsg =+ results.left.type === "subscription_unsupported"+ ? "GraphQL subscriptions are not supported in the collection runner"+ : results.left.message++ this.updateRequestAtPath(tab.value.document.resultCollection!, path, {+ error: errorMsg,+ isLoading: false,+ response: null,+ })++ if (options.stopOnError) {+ tab.value.document.status = "stopped"+ throw new Error("Test execution stopped due to error")+ }+ }+ } catch (error) {+ if (isStopSignal(error)) {+ throw error+ }++ const errorMsg =+ error instanceof Error ? error.message : "Unknown error occurred"++ this.updateRequestAtPath(tab.value.document.resultCollection!, path, {+ error: errorMsg,+ isLoading: false,+ })++ if (options.stopOnError) {+ tab.value.document.status = "stopped"+ throw new Error("Test execution stopped due to error")+ }+ }+ }+private getTestResultInfo(testResult: HoppTestData | HoppTestResult) {let passed = 0// A failed script means the request's assertions never ran — count it asdiff --git a/packages/hoppscotch-common/src/services/workspace.service.ts b/packages/hoppscotch-common/src/services/workspace.service.tsindex 6287bf3ed..707289471 100644--- a/packages/hoppscotch-common/src/services/workspace.service.ts+++ b/packages/hoppscotch-common/src/services/workspace.service.ts@@ -4,10 +4,16 @@ import { computed, reactive, ref, watch, readonly } from "vue"import { useStreamStatic } from "~/composables/stream"import TeamListAdapter from "~/helpers/teams/TeamListAdapter"import { platform } from "~/platform"-import { min } from "lodash-es"+import { isEqual, min } from "lodash-es"import { TeamAccessRole } from "~/helpers/backend/graphql"+import { applyLocalState } from "~/newstore/localstate"import { TeamCollectionsService } from "./team-collection.service"import { DocumentationService } from "./documentation.service"+import { WorkspaceTabsService } from "./tab/workspace-tabs"+import {+ getSelectedEnvironmentIndex,+ setSelectedEnvironmentIndex,+} from "~/newstore/environments"/*** Defines a workspace and its information@@ -49,6 +55,7 @@ export class WorkspaceService extends Service<WorkspaceServiceEvent> {private teamCollectionService = this.bind(TeamCollectionsService)private documentationService = this.bind(DocumentationService)+ private workspaceTabsService = this.bind(WorkspaceTabsService)private currentUser = useStreamStatic(platform.auth.getCurrentUserStream(),@@ -65,8 +72,10 @@ export class WorkspaceService extends Service<WorkspaceServiceEvent> {)override onServiceInit() {- // Dispose the managed team list adapter when the user logs out- // and initialize it when the user logs in+ // Session-driven state: the managed team list adapter follows login state,+ // and a team workspace can't outlive the session that granted access to it.+ // The workspace reset lives here rather than in the workspace selector —+ // that component only exists while its dropdown is open.watch(this.currentUser,(user) => {@@ -77,6 +86,11 @@ export class WorkspaceService extends Service<WorkspaceServiceEvent> {if (user && !this.managedTeamListAdapter.isInitialized) {this.managedTeamListAdapter.initialize()}++ if (!user && this._currentWorkspace.value.type === "team") {+ applyLocalState("REMEMBERED_TEAM_ID", undefined)+ this.changeWorkspace({ type: "personal" })+ }},{ immediate: true })@@ -132,6 +146,10 @@ export class WorkspaceService extends Service<WorkspaceServiceEvent> {return}+ // Keep the unified tab service aware of which workspace its tabs belong to.+ // Today this is purely informational; future tab features may scope by workspace.+ this.workspaceTabsService.attachToWorkspace(newWorkspace)+try {// Ensure authentication is ready before fetching docsif (user) {@@ -201,13 +219,33 @@ export class WorkspaceService extends Service<WorkspaceServiceEvent> {}/**- * Changes the current workspace to the given workspace.+ * Changes the current workspace. Re-selecting the identical workspace is+ * a no-op (a fresh object would retrigger every workspace watcher), and a+ * selected team environment not belonging to the target workspace is+ * reset.* @param workspace The new workspace*/public changeWorkspace(workspace: Workspace) {+ if (isEqual(this._currentWorkspace.value, workspace)) return++ this.resetStaleTeamEnvironment(workspace)this._currentWorkspace.value = workspace}+ /**+ * A selected team environment is scoped to its team — it must not stay+ * active after switching to personal or to a different team.+ */+ private resetStaleTeamEnvironment(workspace: Workspace) {+ const envIndex = getSelectedEnvironmentIndex()+ if (+ envIndex.type === "TEAM_ENV" &&+ (workspace.type === "personal" || workspace.teamID !== envIndex.teamID)+ ) {+ setSelectedEnvironmentIndex({ type: "NO_ENV_SELECTED" })+ }+ }+/*** Acquires a team list adapter that is managed by the workspace service.* The team list adapter is associated with a Vue Scope and will be disposeddiff --git a/packages/hoppscotch-data/src/collection/index.ts b/packages/hoppscotch-data/src/collection/index.tsindex 9ec501351..618bece1b 100644--- a/packages/hoppscotch-data/src/collection/index.ts+++ b/packages/hoppscotch-data/src/collection/index.ts@@ -17,7 +17,9 @@ export { CollectionVariable } from "./v/10"import { z } from "zod"import { translateToNewRequest } from "../rest"+import { HoppRESTRequest } from "../rest"import { translateToGQLRequest } from "../graphql"+import { HoppGQLRequest } from "../graphql"import { generateUniqueRefId } from "../utils/collection"const versionedObject = z.object({@@ -78,11 +80,27 @@ export function makeCollection(x: Omit<HoppCollection, "v">): HoppCollection {* @param x The collection object to load* @returns The proper new collection format*/-export function translateToNewRESTCollection(x: any): HoppCollection {+export function translateToNewCollection(x: any): HoppCollection {// Legacyconst name = x.name ?? "Untitled"- const folders = (x.folders ?? []).map(translateToNewRESTCollection)- const requests = (x.requests ?? []).map(translateToNewRequest)+ const folders = (x.folders ?? []).map(translateToNewCollection)+ const requests = (x.requests ?? []).map(+ (req: any): HoppRESTRequest | HoppGQLRequest => {+ // Detect GQL requests and translate them through the GQL path.+ // Object check first — `in` throws on primitives, and this runs on+ // raw legacy/imported JSON+ if (+ req &&+ typeof req === "object" &&+ "query" in req &&+ "url" in req &&+ !("endpoint" in req)+ ) {+ return translateToGQLRequest(req)+ }+ return translateToNewRequest(req)+ }+ )const auth = x.auth ?? { authType: "inherit", authActive: true }const headers = x.headers ?? []@@ -114,41 +132,37 @@ export function translateToNewRESTCollection(x: any): HoppCollection {}/**- * Translates an old collection to a new collection- * @param x The collection object to load- * @returns The proper new collection format+ * Checks if a request object is a GraphQL request.+ * GQL requests have `query` and `url` fields but no `endpoint` field.+ * @param req The request object to check+ * @returns Whether the request is a HoppGQLRequest*/-export function translateToNewGQLCollection(x: any): HoppCollection {- // Legacy- const name = x.name ?? "Untitled"- const folders = (x.folders ?? []).map(translateToNewGQLCollection)- const requests = (x.requests ?? []).map(translateToGQLRequest)-- const auth = x.auth ?? { authType: "inherit", authActive: true }- const headers = x.headers ?? []- const variables = x.variables ?? []-- const description = x.description ?? null-- const preRequestScript = x.preRequestScript ?? ""- const testScript = x.testScript ?? ""-- const obj = makeCollection({- name,- folders,- requests,- auth,- headers,- variables,- description,- preRequestScript,- testScript,- })-- if (x.id) obj.id = x.id- if (x._ref_id) {- obj._ref_id = x._ref_id- }+export function isGQLRequest(+ req: HoppRESTRequest | HoppGQLRequest+): req is HoppGQLRequest {+ // Object check first — callers pass raw persisted/imported JSON, and the+ // `in` operator throws on primitives+ return (+ !!req &&+ typeof req === "object" &&+ "query" in req &&+ "url" in req &&+ !("endpoint" in req)+ )+}- return obj+/**+ * Checks if a request object is a REST request.+ * REST requests have `endpoint` and `method` fields.+ * @param req The request object to check+ * @returns Whether the request is a HoppRESTRequest+ */+export function isRESTRequest(+ req: HoppRESTRequest | HoppGQLRequest+): req is HoppRESTRequest {+ // Object check first — callers pass raw persisted/imported JSON, and the+ // `in` operator throws on primitives+ return (+ !!req && typeof req === "object" && "endpoint" in req && "method" in req+ )}diff --git a/packages/hoppscotch-data/src/environment/index.ts b/packages/hoppscotch-data/src/environment/index.tsindex b08473dc5..b6b2d1993 100644--- a/packages/hoppscotch-data/src/environment/index.ts+++ b/packages/hoppscotch-data/src/environment/index.ts@@ -68,7 +68,10 @@ const getResolvedVariableValue = (variable: {export function parseBodyEnvVariablesE(body: string,- env: Environment["variables"]+ env: Environment["variables"],+ // Missing vars stay as literal `<<key>>` by default (long-standing body+ // behavior); pass false to resolve them to "" like parseTemplateStringE+ keepMissingAsKey = true) {let result = bodylet depth = 0@@ -91,7 +94,7 @@ export function parseBodyEnvVariablesE(if (foundEnv && "currentValue" in foundEnv) {return getResolvedVariableValue(foundEnv)}- return key+ return keepMissingAsKey ? key : ""})depth++@@ -107,10 +110,11 @@ export function parseBodyEnvVariablesE(*/export const parseBodyEnvVariables = (body: string,- env: Environment["variables"]+ env: Environment["variables"],+ keepMissingAsKey = true) =>pipe(- parseBodyEnvVariablesE(body, env),+ parseBodyEnvVariablesE(body, env, keepMissingAsKey),E.getOrElse(() => body))diff --git a/packages/hoppscotch-data/src/gql-request-response/index.ts b/packages/hoppscotch-data/src/gql-request-response/index.tsnew file mode 100644index 000000000..ce47644ac--- /dev/null+++ b/packages/hoppscotch-data/src/gql-request-response/index.ts@@ -0,0 +1,49 @@+import { InferredEntity, createVersionedEntity, entityReference } from "verzod"+import { z } from "zod"+import V0_VERSION from "./v/0"+import {+ HoppGQLResOriginalReqSchemaVersion,+ HoppGQLResponseOriginalRequest,+} from "./original-request"++export { HoppGQLResponseOriginalRequest } from "./original-request"++const versionedObject = z.object({+ v: z.number(),+})++export const HoppGQLRequestResponse = createVersionedEntity({+ latestVersion: 0,+ versionMap: {+ 0: V0_VERSION,+ },+ getVersion(data) {+ const versionCheck = versionedObject.safeParse(data)++ if (versionCheck.success) return versionCheck.data.v++ // Schema starts at v0 — if no `v` field, fall back to schema match.+ const result = V0_VERSION.schema.safeParse(data)+ return result.success ? 0 : null+ },+})++export type HoppGQLRequestResponse = InferredEntity<+ typeof HoppGQLRequestResponse+>++export const HoppGQLRequestResponses = z.record(+ z.string(),+ entityReference(HoppGQLRequestResponse)+)++export type HoppGQLRequestResponses = z.infer<typeof HoppGQLRequestResponses>++export function makeHoppGQLResponseOriginalRequest(+ x: Omit<HoppGQLResponseOriginalRequest, "v">+): HoppGQLResponseOriginalRequest {+ return {+ v: HoppGQLResOriginalReqSchemaVersion,+ ...x,+ }+}diff --git a/packages/hoppscotch-data/src/gql-request-response/original-request/index.ts b/packages/hoppscotch-data/src/gql-request-response/original-request/index.tsnew file mode 100644index 000000000..d731c5684--- /dev/null+++ b/packages/hoppscotch-data/src/gql-request-response/original-request/index.ts@@ -0,0 +1,31 @@+import { InferredEntity, createVersionedEntity } from "verzod"+import { z } from "zod"+import V1_VERSION from "./v/1"++const versionedObject = z.object({+ // v is a stringified number — same convention as the REST counterpart.+ v: z.string().regex(/^\d+$/).transform(Number),+})++export const HoppGQLResponseOriginalRequest = createVersionedEntity({+ latestVersion: 1,+ versionMap: {+ 1: V1_VERSION,+ },+ getVersion(data) {+ const versionCheck = versionedObject.safeParse(data)++ if (versionCheck.success) return versionCheck.data.v++ // For V1 we have to check the schema (matches the REST pattern)+ const result = V1_VERSION.schema.safeParse(data)++ return result.success ? 1 : null+ },+})++export const HoppGQLResOriginalReqSchemaVersion = "1"++export type HoppGQLResponseOriginalRequest = InferredEntity<+ typeof HoppGQLResponseOriginalRequest+>diff --git a/packages/hoppscotch-data/src/gql-request-response/original-request/v/1.ts b/packages/hoppscotch-data/src/gql-request-response/original-request/v/1.tsnew file mode 100644index 000000000..ee6d716b7--- /dev/null+++ b/packages/hoppscotch-data/src/gql-request-response/original-request/v/1.ts@@ -0,0 +1,20 @@+import { defineVersion } from "verzod"+import { z } from "zod"++import { GQLHeader } from "../../../graphql/v/6"+import { HoppGQLAuth } from "../../../graphql/v/9"++export const V1_SCHEMA = z.object({+ v: z.literal("1"),+ name: z.string(),+ url: z.string(),+ query: z.string(),+ variables: z.string(),+ headers: z.array(GQLHeader).catch([]),+ auth: HoppGQLAuth,+})++export default defineVersion({+ initial: true,+ schema: V1_SCHEMA,+})diff --git a/packages/hoppscotch-data/src/gql-request-response/v/0.ts b/packages/hoppscotch-data/src/gql-request-response/v/0.tsnew file mode 100644index 000000000..f1006bde7--- /dev/null+++ b/packages/hoppscotch-data/src/gql-request-response/v/0.ts@@ -0,0 +1,39 @@+import { defineVersion, entityReference } from "verzod"+import { z } from "zod"+import { HoppGQLResponseOriginalRequest } from "../original-request"++export const HoppGQLResponseHeaders = z.array(+ z.object({+ key: z.string(),+ value: z.string(),+ })+)++export type HoppGQLResponseHeader = z.infer<+ typeof HoppGQLResponseHeaders+>[number]++export const V0_SCHEMA = z.object({+ name: z.string(),+ originalRequest: entityReference(HoppGQLResponseOriginalRequest),+ // Transport-level status. GQL responses are usually HTTP 200, but transport+ // failures can surface non-200s; keep these for parity with the REST shape.+ status: z.string(),+ code: z.optional(z.number()).nullable().catch(null),+ headers: HoppGQLResponseHeaders,+ body: z.string(),+ // Operation identity of the run this example was saved from — the mock+ // server matches GraphQL requests by these (name + query/mutation), the+ // way REST examples match by method + path. Optional: examples saved+ // before the stamping existed simply never match by name. Nullable: the+ // mock server canonicalizes the wildcard stamp as null, and JSON writers+ // have no way to express undefined — a null stamp must not fail the parse+ // (the whole `responses` record would be silently reset by its .catch).+ operationName: z.string().nullable().optional(),+ operationType: z.string().nullable().optional(),+})++export default defineVersion({+ initial: true,+ schema: V0_SCHEMA,+})diff --git a/packages/hoppscotch-data/src/graphql/index.ts b/packages/hoppscotch-data/src/graphql/index.tsindex e27b191b2..a2db84a9c 100644--- a/packages/hoppscotch-data/src/graphql/index.ts+++ b/packages/hoppscotch-data/src/graphql/index.ts@@ -1,5 +1,6 @@import { InferredEntity, createVersionedEntity } from "verzod"import { z } from "zod"+import { generateUniqueRefId } from "../utils/collection"import V1_VERSION from "./v/1"import V2_VERSION from "./v/2"import V3_VERSION from "./v/3"@@ -9,6 +10,7 @@ import V6_VERSION from "./v/6"import V7_VERSION from "./v/7"import V8_VERSION from "./v/8"import V9_VERSION from "./v/9"+import V10_VERSION from "./v/10"export {HoppGQLAuthBasic,@@ -22,14 +24,14 @@ export { HoppGQLAuthAPIKey } from "./v/4"export { GQLHeader, HoppGQLAuthAWSSignature } from "./v/6"export { HoppGQLAuth, HoppGQLAuthOAuth2 } from "./v/9"-export const GQL_REQ_SCHEMA_VERSION = 9+export const GQL_REQ_SCHEMA_VERSION = 10const versionedObject = z.object({v: z.number(),})export const HoppGQLRequest = createVersionedEntity({- latestVersion: 9,+ latestVersion: 10,versionMap: {1: V1_VERSION,2: V2_VERSION,@@ -40,6 +42,7 @@ export const HoppGQLRequest = createVersionedEntity({7: V7_VERSION,8: V8_VERSION,9: V9_VERSION,+ 10: V10_VERSION,},getVersion(x) {const result = versionedObject.safeParse(x)@@ -75,6 +78,11 @@ export function getDefaultGQLRequest(): HoppGQLRequest {authType: "inherit",authActive: true,},+ _ref_id: generateUniqueRefId("req"),+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",}}diff --git a/packages/hoppscotch-data/src/graphql/v/10.ts b/packages/hoppscotch-data/src/graphql/v/10.tsnew file mode 100644index 000000000..c680af487--- /dev/null+++ b/packages/hoppscotch-data/src/graphql/v/10.ts@@ -0,0 +1,30 @@+import { defineVersion } from "verzod"+import { z } from "zod"+import { V9_SCHEMA } from "./9"+import { generateUniqueRefId } from "../../utils/collection"+import { HoppGQLRequestResponses } from "../../gql-request-response"++export const V10_SCHEMA = V9_SCHEMA.extend({+ v: z.literal(10),+ _ref_id: z.string().optional(),+ description: z.string().nullable().catch(null),+ responses: HoppGQLRequestResponses.catch({}),+ preRequestScript: z.string().catch(""),+ testScript: z.string().catch(""),+})++export default defineVersion({+ schema: V10_SCHEMA,+ initial: false,+ up(old: z.infer<typeof V9_SCHEMA>) {+ return {+ ...old,+ v: 10 as const,+ _ref_id: generateUniqueRefId("req"),+ description: null,+ responses: {},+ preRequestScript: "",+ testScript: "",+ }+ },+})diff --git a/packages/hoppscotch-data/src/index.ts b/packages/hoppscotch-data/src/index.tsindex ecbfc8c0e..df387dc77 100644--- a/packages/hoppscotch-data/src/index.ts+++ b/packages/hoppscotch-data/src/index.ts@@ -10,4 +10,5 @@ export * from "./utils/hawk"export * from "./utils/akamai-eg"export * from "./utils/jwt"export * from "./rest-request-response"+export * from "./gql-request-response"export * from "./cookies"diff --git a/packages/hoppscotch-js-sandbox/src/utils/shared.ts b/packages/hoppscotch-js-sandbox/src/utils/shared.tsindex 9b41fe38e..26e0c3454 100644--- a/packages/hoppscotch-js-sandbox/src/utils/shared.ts+++ b/packages/hoppscotch-js-sandbox/src/utils/shared.ts@@ -781,12 +781,9 @@ export const createExpectation = (}const toHaveLengthFn = (expectedLength: SandboxValue) => {- if (- !(- Array.isArray(resolvedExpectVal) ||- typeof resolvedExpectVal === "string"- )- ) {+ if (!(+ Array.isArray(resolvedExpectVal) || typeof resolvedExpectVal === "string"+ )) {const message ="Expected toHaveLength to be called for an array or string"const targetTest = getCurrentTest()@@ -831,12 +828,9 @@ export const createExpectation = (}const toIncludeFn = (needle: SandboxValue) => {- if (- !(- Array.isArray(resolvedExpectVal) ||- typeof resolvedExpectVal === "string"- )- ) {+ if (!(+ Array.isArray(resolvedExpectVal) || typeof resolvedExpectVal === "string"+ )) {const message = "Expected toInclude to be called for an array or string"const targetTest = getCurrentTest()if (!targetTest) return undefineddiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6ceb4a25b..f47905806 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -441,6 +441,9 @@ importers:commander:specifier: 14.0.3version: 14.0.3+ graphql:+ specifier: 16.13.2+ version: 16.13.2isolated-vm:specifier: 6.1.2version: 6.1.2