Skip to content

Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia

feat(common): add OpenAPI 3.1 collection export (#5880)

Gavin McDonough3836d70e710e
diff --git a/packages/hoppscotch-common/locales/en.json b/packages/hoppscotch-common/locales/en.json
index 3a8c2c917..f32c1fee9 100644
--- a/packages/hoppscotch-common/locales/en.json
+++ b/packages/hoppscotch-common/locales/en.json
@@ -760,6 +760,15 @@
},
"export": {
"as_json": "Export as JSON",
+ "as_openapi": "Export as OpenAPI",
+ "as_yaml": "Export as YAML",
+ "choose_format": "Choose export format",
+ "collection": "Export collection",
+ "collections": "Export collections",
+ "format_hoppscotch": "Export as Hoppscotch JSON",
+ "format_openapi_json": "Export as OpenAPI 3.1 (JSON)",
+ "format_openapi_yaml": "Export as OpenAPI 3.1 (YAML)",
+ "openapi_lossy_summary": "OpenAPI export drops scripts, auth credentials, inactive items, duplicate paths, and duplicate response status codes.",
"create_secret_gist": "Create secret Gist",
"create_secret_gist_tooltip_text": "Export as secret Gist",
"failed": "Something went wrong while exporting",
diff --git a/packages/hoppscotch-common/src/components.d.ts b/packages/hoppscotch-common/src/components.d.ts
index 357e22406..8ab704d4f 100644
--- a/packages/hoppscotch-common/src/components.d.ts
+++ b/packages/hoppscotch-common/src/components.d.ts
@@ -78,6 +78,9 @@ declare module 'vue' {
CollectionsEditRequest: typeof import('./components/collections/EditRequest.vue')['default']
CollectionsEditResponse: typeof import('./components/collections/EditResponse.vue')['default']
CollectionsExampleResponse: typeof import('./components/collections/ExampleResponse.vue')['default']
+ CollectionsExportFormatList: typeof import('./components/collections/ExportFormatList.vue')['default']
+ CollectionsExportFormatModal: typeof import('./components/collections/ExportFormatModal.vue')['default']
+ CollectionsExportFormatStep: typeof import('./components/collections/ExportFormatStep.vue')['default']
CollectionsGraphql: typeof import('./components/collections/graphql/index.vue')['default']
CollectionsGraphqlAdd: typeof import('./components/collections/graphql/Add.vue')['default']
CollectionsGraphqlAddFolder: typeof import('./components/collections/graphql/AddFolder.vue')['default']
@@ -239,12 +242,9 @@ 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']
- IconLucideBrush: typeof import('~icons/lucide/brush')['default']
IconLucideCheck: typeof import('~icons/lucide/check')['default']
IconLucideCheckCircle: typeof import('~icons/lucide/check-circle')['default']
- IconLucideChevronDown: typeof import('~icons/lucide/chevron-down')['default']
IconLucideChevronRight: typeof import('~icons/lucide/chevron-right')['default']
- IconLucideCircleCheck: typeof import('~icons/lucide/circle-check')['default']
IconLucideFileQuestion: typeof import('~icons/lucide/file-question')['default']
IconLucideFileText: typeof import('~icons/lucide/file-text')['default']
IconLucideFileX: typeof import('~icons/lucide/file-x')['default']
@@ -258,14 +258,10 @@ declare module 'vue' {
IconLucideListEnd: typeof import('~icons/lucide/list-end')['default']
IconLucideLoader2: typeof import('~icons/lucide/loader2')['default']
IconLucideMinus: typeof import('~icons/lucide/minus')['default']
- IconLucidePlusCircle: typeof import('~icons/lucide/plus-circle')['default']
IconLucideRefreshCw: typeof import('~icons/lucide/refresh-cw')['default']
- IconLucideRss: typeof import('~icons/lucide/rss')['default']
IconLucideSearch: typeof import('~icons/lucide/search')['default']
IconLucideTerminal: typeof import('~icons/lucide/terminal')['default']
- IconLucideTriangleAlert: typeof import('~icons/lucide/triangle-alert')['default']
IconLucideUsers: typeof import('~icons/lucide/users')['default']
- IconLucideVerified: typeof import('~icons/lucide/verified')['default']
IconLucideX: typeof import('~icons/lucide/x')['default']
ImportExportBase: typeof import('./components/importExport/Base.vue')['default']
ImportExportImportExportList: typeof import('./components/importExport/ImportExportList.vue')['default']
diff --git a/packages/hoppscotch-common/src/components/collections/Collection.vue b/packages/hoppscotch-common/src/components/collections/Collection.vue
index 2a9af3baa..08c345d69 100644
--- a/packages/hoppscotch-common/src/components/collections/Collection.vue
+++ b/packages/hoppscotch-common/src/components/collections/Collection.vue
@@ -263,17 +263,16 @@
v-if="!hasNoTeamAccess"
ref="exportAction"
:icon="IconDownload"
- :label="t('export.title')"
+ :label="t('export.collection')"
:shortcut="['X']"
:loading="exportLoading"
@click="
() => {
- ;(emit('export-data'),
- collectionsType === 'my-collections' ? hide() : null)
+ emit('export-data')
+ hide()
}
"
/>
-
<HoppSmartItem
ref="propertiesAction"
:icon="IconSettings2"
diff --git a/packages/hoppscotch-common/src/components/collections/ExportFormatList.vue b/packages/hoppscotch-common/src/components/collections/ExportFormatList.vue
new file mode 100644
index 000000000..6bc870b19
--- /dev/null
+++ b/packages/hoppscotch-common/src/components/collections/ExportFormatList.vue
@@ -0,0 +1,79 @@
+<template>
+ <div class="flex flex-col">
+ <div class="flex flex-col space-y-2">
+ <HoppSmartItem
+ :icon="IconFolderPlus"
+ :label="t('export.format_hoppscotch')"
+ :loading="activeFormat === 'hoppscotch'"
+ :disabled="loading"
+ @click="onSelect('hoppscotch')"
+ />
+ <HoppSmartItem
+ :icon="IconBraces"
+ :label="t('export.format_openapi_json')"
+ :loading="activeFormat === 'openapi-json'"
+ :disabled="loading"
+ @click="onSelect('openapi-json')"
+ />
+ <HoppSmartItem
+ :icon="IconFileText"
+ :label="t('export.format_openapi_yaml')"
+ :loading="activeFormat === 'openapi-yaml'"
+ :disabled="loading"
+ @click="onSelect('openapi-yaml')"
+ />
+ </div>
+ <div
+ v-if="showLossyWarning"
+ class="mt-4 flex items-start space-x-3 rounded border border-yellow-500/40 bg-primaryLight px-3 py-3 shadow-sm"
+ role="alert"
+ >
+ <IconAlertCircle class="flex-shrink-0 svg-icons text-yellow-500" />
+ <p class="flex-1 text-secondary text-tiny leading-relaxed">
+ {{ t("export.openapi_lossy_summary") }}
+ </p>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import IconAlertCircle from "~icons/lucide/alert-circle"
+import IconBraces from "~icons/lucide/braces"
+import IconFileText from "~icons/lucide/file-text"
+import IconFolderPlus from "~icons/lucide/folder-plus"
+import { useI18n } from "@composables/i18n"
+import { computed, ref, toRefs, watch } from "vue"
+
+const t = useI18n()
+
+const props = defineProps<{
+ loading: boolean
+}>()
+
+const emit = defineEmits<{
+ (e: "export-hoppscotch"): void
+ (e: "export-openapi", format: "json" | "yaml"): void
+}>()
+
+type Format = "hoppscotch" | "openapi-json" | "openapi-yaml"
+
+const activeFormat = ref<Format | null>(null)
+
+const onSelect = (format: Format) => {
+ if (props.loading) return
+ activeFormat.value = format
+ if (format === "hoppscotch") emit("export-hoppscotch")
+ else if (format === "openapi-json") emit("export-openapi", "json")
+ else emit("export-openapi", "yaml")
+}
+
+// Hoppscotch JSON export is lossless; the warning only applies to OpenAPI.
+// Show it by default (before any selection) and while an OpenAPI export is in
+// flight; hide it once the user picks Hoppscotch JSON.
+const showLossyWarning = computed(() => activeFormat.value !== "hoppscotch")
+
+const { loading } = toRefs(props)
+watch(loading, (val) => {
+ if (!val) activeFormat.value = null
+})
+</script>
diff --git a/packages/hoppscotch-common/src/components/collections/ExportFormatModal.vue b/packages/hoppscotch-common/src/components/collections/ExportFormatModal.vue
new file mode 100644
index 000000000..b6c0d25c4
--- /dev/null
+++ b/packages/hoppscotch-common/src/components/collections/ExportFormatModal.vue
@@ -0,0 +1,34 @@
+<template>
+ <HoppSmartModal
+ v-if="show"
+ dialog
+ :title="t('export.choose_format')"
+ styles="sm:max-w-md"
+ @close="emit('close')"
+ >
+ <template #body>
+ <CollectionsExportFormatList
+ :loading="loading"
+ @export-hoppscotch="emit('export-hoppscotch')"
+ @export-openapi="(f) => emit('export-openapi', f)"
+ />
+ </template>
+ </HoppSmartModal>
+</template>
+
+<script setup lang="ts">
+import { useI18n } from "@composables/i18n"
+
+const t = useI18n()
+
+defineProps<{
+ show: boolean
+ loading: boolean
+}>()
+
+const emit = defineEmits<{
+ (e: "close"): void
+ (e: "export-hoppscotch"): void
+ (e: "export-openapi", format: "json" | "yaml"): void
+}>()
+</script>
diff --git a/packages/hoppscotch-common/src/components/collections/ExportFormatStep.vue b/packages/hoppscotch-common/src/components/collections/ExportFormatStep.vue
new file mode 100644
index 000000000..6d0020209
--- /dev/null
+++ b/packages/hoppscotch-common/src/components/collections/ExportFormatStep.vue
@@ -0,0 +1,18 @@
+<template>
+ <CollectionsExportFormatList
+ :loading="loading"
+ @export-hoppscotch="emit('export-hoppscotch')"
+ @export-openapi="(f) => emit('export-openapi', f)"
+ />
+</template>
+
+<script setup lang="ts">
+defineProps<{
+ loading: boolean
+}>()
+
+const emit = defineEmits<{
+ (e: "export-hoppscotch"): void
+ (e: "export-openapi", format: "json" | "yaml"): void
+}>()
+</script>
diff --git a/packages/hoppscotch-common/src/components/collections/ImportExport.vue b/packages/hoppscotch-common/src/components/collections/ImportExport.vue
index 056d1c1f5..4572a7f2d 100644
--- a/packages/hoppscotch-common/src/components/collections/ImportExport.vue
+++ b/packages/hoppscotch-common/src/components/collections/ImportExport.vue
@@ -4,7 +4,9 @@
modal-title="modal.collections"
:importer-modules="importerModules"
:exporter-modules="exporterModules"
- :has-team-write-access="hasTeamWriteAccess"
+ :has-team-write-access="
+ hasTeamWriteAccess || collectionsType.type === 'my-collections'
+ "
@hide-modal="emit('hide-modal')"
/>
</template>
@@ -18,7 +20,9 @@ import { transformCollectionForImport } from "~/helpers/collection/collection"
import { FileSource } from "~/helpers/import-export/import/import-sources/FileSource"
import { UrlSource } from "~/helpers/import-export/import/import-sources/UrlSource"
+import IconDownload from "~icons/lucide/download"
import IconFile from "~icons/lucide/file"
+import yaml from "js-yaml"
import {
harImporter,
@@ -32,6 +36,7 @@ import {
import { defineStep } from "~/composables/step-components"
import AllCollectionImport from "~/components/importExport/ImportExportSteps/AllCollectionImport.vue"
+import CollectionsExportFormatStep from "~/components/collections/ExportFormatStep.vue"
import { useI18n } from "~/composables/i18n"
import { useToast } from "~/composables/toast"
import { appendRESTCollections, restCollections$ } from "~/newstore/collections"
@@ -62,6 +67,7 @@ import {
} from "~/helpers/import-export/export"
import { gistExporter } from "~/helpers/import-export/export/gist"
import { myCollectionsExporter } from "~/helpers/import-export/export/myCollections"
+import { hoppCollectionsToOpenAPI } from "~/helpers/import-export/export/openapi"
import { teamCollectionsExporter } from "~/helpers/import-export/export/teamCollections"
import { ImporterOrExporter } from "~/components/importExport/types"
@@ -194,8 +200,7 @@ const emit = defineEmits<{
(e: "hide-modal"): () => void
}>()
-const isHoppMyCollectionExporterInProgress = ref(false)
-const isHoppTeamCollectionExporterInProgress = ref(false)
+const isWorkspaceExportInProgress = ref(false)
const isHoppGistCollectionExporterInProgress = ref(false)
const isPostmanImporterInProgress = ref(false)
@@ -593,89 +598,171 @@ const HoppGistImporter: ImporterOrExporter = {
}),
}
-const HoppMyCollectionsExporter: ImporterOrExporter = {
- metadata: {
- id: "hopp_my_collections",
- name: "export.as_json",
- title: "action.download_file",
- icon: IconUser,
- disabled: false,
- applicableTo: ["personal-workspace"],
- isLoading: isHoppMyCollectionExporterInProgress,
- format: "hoppscotch",
- },
- importSummary: currentImportSummary,
- action: async () => {
+/**
+ * Resolve the array of HoppCollections for the current workspace. For the
+ * team workspace we have to fetch + parse the GraphQL JSON; for personal it's
+ * already a reactive ref.
+ */
+const getWorkspaceCollections = async (): Promise<{
+ collections: HoppCollection[]
+ workspaceName: string
+ fileBaseName: string
+} | null> => {
+ if (props.collectionsType.type === "my-collections") {
if (!myCollections.value.length) {
- return toast.error(t("error.no_collections_to_export"))
+ toast.error(t("error.no_collections_to_export"))
+ return null
}
+ return {
+ collections: myCollections.value,
+ workspaceName: "Hoppscotch personal collections",
+ fileBaseName: "hoppscotch-personal-collections",
+ }
+ }
- isHoppMyCollectionExporterInProgress.value = true
+ if (!props.collectionsType.selectedTeam) return null
+ const team = props.collectionsType.selectedTeam
+ const res = await teamCollectionsExporter(team.teamID)
+ if (E.isLeft(res)) {
+ toast.error(res.left)
+ return null
+ }
- const message = await initializeDownloadFile(
- myCollectionsExporter(myCollections.value),
- "hoppscotch-personal-collections"
- )
+ let collections: HoppCollection[]
+ try {
+ collections = JSON.parse(res.right) as HoppCollection[]
+ } catch {
+ toast.error(t("error.something_went_wrong"))
+ return null
+ }
+ if (!collections.length) {
+ toast.error(t("error.no_collections_to_export"))
+ return null
+ }
- if (E.isRight(message)) {
- toast.success(t("state.download_started"))
+ return {
+ collections,
+ workspaceName: team.teamName ?? "Hoppscotch team",
+ fileBaseName: "hoppscotch-team-collections",
+ }
+}
+const onWorkspaceExportHopp = async () => {
+ // Keep the modal open during the GraphQL fetch (team workspaces) and
+ // serialization. Closing early hid that latency from the user.
+ isWorkspaceExportInProgress.value = true
+ let saved = false
+ try {
+ const ctx = await getWorkspaceCollections()
+ if (!ctx) return
+
+ const json =
+ props.collectionsType.type === "my-collections"
+ ? myCollectionsExporter(ctx.collections)
+ : JSON.stringify(ctx.collections, null, 2)
+
+ const message = await initializeDownloadFile(json, ctx.fileBaseName)
+ if (E.isRight(message)) {
+ toast.success(t(message.right))
platform.analytics?.logEvent({
type: "HOPP_EXPORT_COLLECTION",
exporter: "json",
platform: "rest",
})
+ saved = true
} else {
toast.error(t(message.left))
}
-
- isHoppMyCollectionExporterInProgress.value = false
- },
+ } catch {
+ toast.error(t("export.failed"))
+ } finally {
+ isWorkspaceExportInProgress.value = false
+ // Only close the parent modal when the file actually saved. On cancel,
+ // no-data, or error the user stays on the format chooser so toasts and
+ // state remain visible and they can retry.
+ if (saved) emit("hide-modal")
+ }
}
-const HoppTeamCollectionsExporter: ImporterOrExporter = {
- metadata: {
- id: "hopp_team_collections",
- name: "export.as_json",
- title: "export.as_json",
- icon: IconUser,
- disabled: false,
- applicableTo: ["team-workspace"],
- isLoading: isHoppTeamCollectionExporterInProgress,
- },
- importSummary: currentImportSummary,
- action: async () => {
- isHoppTeamCollectionExporterInProgress.value = true
- if (
- props.collectionsType.type === "team-collections" &&
- props.collectionsType.selectedTeam
- ) {
- const res = await teamCollectionsExporter(
- props.collectionsType.selectedTeam.teamID
- )
-
- if (E.isRight(res)) {
- const message = await initializeDownloadFile(
- res.right,
- "hoppscotch-team-collections"
- )
+const onWorkspaceExportOpenAPI = async (format: "json" | "yaml") => {
+ isWorkspaceExportInProgress.value = true
+ let saved = false
+ try {
+ const ctx = await getWorkspaceCollections()
+ if (!ctx) return
- E.isRight(message)
- ? toast.success(t(message.right))
- : toast.error(t(message.left))
+ // The chooser modal already shows the full list of OpenAPI lossiness
+ // categories upfront, so the converter's post-export warnings would be
+ // redundant — drop them.
+ const { doc } = hoppCollectionsToOpenAPI(ctx.workspaceName, ctx.collections)
- platform.analytics?.logEvent({
- type: "HOPP_EXPORT_COLLECTION",
- exporter: "json",
- platform: "rest",
- })
- } else {
- toast.error(res.left)
- }
+ const isYaml = format === "yaml"
+ let data: string
+ try {
+ data = isYaml ? yaml.dump(doc) : JSON.stringify(doc, null, 2)
+ } catch {
+ toast.error(t("error.something_went_wrong"))
+ return
}
+ const extension = isYaml ? "yaml" : "json"
+ const result = await platform.kernelIO.saveFileWithDialog({
+ data,
+ contentType: isYaml ? "application/x-yaml" : "application/json",
+ suggestedFilename: `${ctx.fileBaseName}-openapi.${extension}`,
+ filters: [
+ {
+ name: `OpenAPI ${extension.toUpperCase()} file`,
+ extensions: [extension],
+ },
+ ],
+ })
+ if (result.type === "saved" || result.type === "unknown") {
+ toast.success(t("state.download_started").toString())
+ platform.analytics?.logEvent({
+ type: "HOPP_EXPORT_COLLECTION",
+ exporter: "openapi",
+ platform: "rest",
+ })
+ saved = true
+ }
+ } catch {
+ toast.error(t("export.failed"))
+ } finally {
+ isWorkspaceExportInProgress.value = false
+ if (saved) emit("hide-modal")
+ }
+}
- isHoppTeamCollectionExporterInProgress.value = false
+// In-modal step that renders the format chooser (Hoppscotch JSON / OpenAPI
+// JSON / OpenAPI YAML + lossiness disclosure). Registered as the exporter's
+// `component` so ImportExportBase advances to it on click instead of opening
+// a parallel modal.
+const exportFormatStep = defineStep(
+ "collections_export_format",
+ CollectionsExportFormatStep,
+ () => ({
+ loading: isWorkspaceExportInProgress.value,
+ "onExport-hoppscotch": () => {
+ onWorkspaceExportHopp()
+ },
+ "onExport-openapi": (format: "json" | "yaml") => {
+ onWorkspaceExportOpenAPI(format)
+ },
+ })
+)
+
+const HoppCollectionsExporter: ImporterOrExporter = {
+ metadata: {
+ id: "hopp_collections_export",
+ name: "export.collections",
+ title: "export.choose_format",
+ icon: IconDownload,
+ disabled: false,
+ applicableTo: ["personal-workspace", "team-workspace"],
+ isLoading: isWorkspaceExportInProgress,
},
+ importSummary: currentImportSummary,
+ component: exportFormatStep,
}
const HoppGistCollectionsExporter: ImporterOrExporter = {
@@ -801,10 +888,7 @@ const importerModules = computed(() => {
})
const exporterModules = computed(() => {
- const enabledExporters = [
- HoppMyCollectionsExporter,
- HoppTeamCollectionsExporter,
- ]
+ const enabledExporters = [HoppCollectionsExporter]
if (platform.platformFeatureFlags.exportAsGIST) {
enabledExporters.push(HoppGistCollectionsExporter)
diff --git a/packages/hoppscotch-common/src/components/collections/index.vue b/packages/hoppscotch-common/src/components/collections/index.vue
index 88a964efa..0c731018d 100644
--- a/packages/hoppscotch-common/src/components/collections/index.vue
+++ b/packages/hoppscotch-common/src/components/collections/index.vue
@@ -225,6 +225,13 @@
</span>
</template>
</HoppSmartModal>
+ <CollectionsExportFormatModal
+ :show="showExportModal"
+ :loading="exportLoading"
+ @close="closeExportModal"
+ @export-hoppscotch="onExportHopp"
+ @export-openapi="onExportOpenAPI"
+ />
<HoppSmartConfirmModal
:show="showConfirmModal"
:title="confirmModalTitle"
@@ -308,11 +315,13 @@ import { useService } from "dioc/vue"
import { stripJsonSerializedModulePrefix } from "@hoppscotch/js-sandbox/scripting"
import * as TE from "fp-ts/TaskEither"
+import * as E from "fp-ts/Either"
import { pipe } from "fp-ts/function"
import * as A from "fp-ts/Array"
import * as O from "fp-ts/Option"
import { flow } from "fp-ts/function"
+import yaml from "js-yaml"
import { cloneDeep, debounce, isEqual } from "lodash-es"
import { PropType, computed, nextTick, onMounted, ref, watch } from "vue"
import { useReadonlyStream } from "~/composables/stream"
@@ -321,8 +330,7 @@ import { GQLError, runMutation } from "~/helpers/backend/GQLClient"
import { UpdateRequestDocument } from "~/helpers/backend/graphql"
import {
CollectionDataProps,
- getCompleteCollectionTree,
- teamCollToHoppRESTColl,
+ getTeamCollectionObject,
} from "~/helpers/backend/helpers"
import { handleTokenValidation } from "~/helpers/handleTokenValidation"
import {
@@ -355,6 +363,7 @@ import {
} from "~/helpers/collection/request"
import { TeamCollection } from "~/helpers/teams/TeamCollection"
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 { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"
@@ -462,6 +471,10 @@ const editingRequestID = ref<string | null>(null)
const editingResponseID = ref<string | null>(null)
const showAddExampleModal = ref(false)
+// The queued collection is held here so async export work can read it after
+// the modal closes.
+const showExportModal = ref(false)
+const exportTargetCollection = ref<HoppCollection | TeamCollection | null>(null)
const editingProperties = ref<EditingProperties>({
collection: null,
@@ -892,6 +905,38 @@ const displayModalAddExample = (show: boolean) => {
if (!show) resetSelectedData()
}
+let exportGeneration = 0
+
+const closeExportModal = () => {
+ // Bump so any in-flight export's `finally` no-ops instead of closing a
+ // freshly-opened modal after this dismissal.
+ exportGeneration++
+ showExportModal.value = false
+ exportTargetCollection.value = null
+ exportLoading.value = false
+}
+
+const onExportHopp = async () => {
+ const collection = exportTargetCollection.value
+ if (!collection) return
+ // `doExportHoppCollection` sets `exportLoading = true` on entry; the reset
+ // is owned here via the generation-guarded `closeExportModal()` so a stale
+ // in-flight export cannot re-enable buttons on a freshly-opened modal.
+ // Same `exportGeneration` pattern as `doExportOpenAPI`.
+ const thisGeneration = ++exportGeneration
+ try {
+ await doExportHoppCollection(collection)
+ } finally {
+ if (thisGeneration === exportGeneration) closeExportModal()
+ }
+}
+
+const onExportOpenAPI = (format: "json" | "yaml") => {
+ // Modal stays open through the export to keep the loading state visible;
+ // doExportOpenAPI closes it when finished.
+ doExportOpenAPI(format)
+}
+
const addNewRootCollection = async (name: string) => {
if (collectionsType.value.type === "my-collections") {
modalLoadingState.value = true
@@ -3146,61 +3191,164 @@ const initializeDownloadCollection = async (
if (result.type === "unknown" || result.type === "saved") {
toast.success(t("state.download_started").toString())
+ platform.analytics?.logEvent({
+ type: "HOPP_EXPORT_COLLECTION",
+ exporter: "json",
+ platform: "rest",
+ })
}
}
/**
- * Export a specific collection or folder
- * Triggered by the export button in the tippy menu
- * @param collection - Collection or folder to be exported
+ * Entry point from the collection context menu. Opens the format-chooser
+ * modal so the user can pick between Hoppscotch JSON and OpenAPI 3.1.
*/
-const exportData = async (collection: HoppCollection | TeamCollection) => {
- if (collectionsType.value.type === "my-collections") {
- const collectionJSON = JSON.stringify(
- stripCollectionTreeForStore(collection as HoppCollection),
- stripRefIdReplacer,
- 2
- )
+const exportData = (collection: HoppCollection | TeamCollection) => {
+ exportTargetCollection.value = collection
+ showExportModal.value = true
+}
- // Strip `export {};\n` from `testScript` and `preRequestScript` fields
- const cleanedCollectionJSON =
- stripJsonSerializedModulePrefix(collectionJSON)
+/**
+ * Native Hoppscotch JSON export (the original behavior of `exportData`).
+ */
+const doExportHoppCollection = async (
+ collection: HoppCollection | TeamCollection
+) => {
+ // Strip `export {};\n` from `testScript` and `preRequestScript` fields, and
+ // strip `_ref_id` / secret variable values via `stripCollectionTreeForStore`
+ // so neither leaks into the exported file.
+ const stringifyForExport = (coll: HoppCollection): string =>
+ stripJsonSerializedModulePrefix(
+ JSON.stringify(stripCollectionTreeForStore(coll), stripRefIdReplacer, 2)
+ )
- const name = (collection as HoppCollection).name
+ exportLoading.value = true
+ try {
+ if (collectionsType.value.type === "my-collections") {
+ const hoppColl = collection as HoppCollection
+ await initializeDownloadCollection(
+ stringifyForExport(hoppColl),
+ hoppColl.name
+ )
+ return
+ }
- initializeDownloadCollection(cleanedCollectionJSON, name)
- } else {
if (!collection.id) return
- exportLoading.value = true
+ const teamID = collectionsType.value.selectedTeam?.teamID
+ if (!teamID) return
+
+ const result = await getTeamCollectionObject(teamID, collection.id)
+ if (E.isLeft(result)) {
+ const errMsg =
+ typeof result.left === "string"
+ ? result.left
+ : getErrorMessage(result.left)
+ toast.error(`${errMsg}`)
+ return
+ }
+ const hoppColl = result.right
+ await initializeDownloadCollection(
+ stringifyForExport(hoppColl),
+ hoppColl.name
+ )
+ } catch {
+ toast.error(t("error.something_went_wrong"))
+ }
+}
- pipe(
- getCompleteCollectionTree(collection.id),
- TE.match(
- (err: GQLError<string>) => {
- toast.error(`${getErrorMessage(err)}`)
- exportLoading.value = false
- return
+const doExportOpenAPI = async (format: "json" | "yaml") => {
+ const collection = exportTargetCollection.value
+ if (!collection) return
+
+ const thisGeneration = ++exportGeneration
+
+ const saveOpenAPIDoc = async (
+ openAPIDoc: Record<string, unknown>,
+ name: string
+ ) => {
+ const isYaml = format === "yaml"
+ let data: string
+ try {
+ data = isYaml
+ ? yaml.dump(openAPIDoc)
+ : JSON.stringify(openAPIDoc, null, 2)
+ } catch {
+ toast.error(t("error.something_went_wrong"))
+ return
+ }
+ const contentType = isYaml ? "application/x-yaml" : "application/json"
+ const extension = isYaml ? "yaml" : "json"
+
+ // `saveFileWithDialog` returns a discriminated SaveFileResponse and does
+ // not throw — checking `result.type` is the only correct way to know if
+ // the user actually saved or cancelled.
+ const result = await platform.kernelIO.saveFileWithDialog({
+ data,
+ contentType,
+ suggestedFilename: `${name}-openapi.${extension}`,
+ filters: [
+ {
+ name: `OpenAPI ${extension.toUpperCase()} file`,
+ extensions: [extension],
},
- async (coll) => {
- const hoppColl = teamCollToHoppRESTColl(coll)
- const collectionJSONString = JSON.stringify(
- stripCollectionTreeForStore(hoppColl),
- stripRefIdReplacer,
- 2
- )
+ ],
+ })
+
+ if (result.type === "saved" || result.type === "unknown") {
+ toast.success(t("state.download_started").toString())
+ platform.analytics?.logEvent({
+ type: "HOPP_EXPORT_COLLECTION",
+ exporter: "openapi",
+ platform: "rest",
+ })
+ }
+ }
- // Strip `export {};\n` from `testScript` and `preRequestScript` fields
- const cleanedCollectionJSON =
- stripJsonSerializedModulePrefix(collectionJSONString)
+ exportLoading.value = true
- await initializeDownloadCollection(
- cleanedCollectionJSON,
- hoppColl.name
- )
- exportLoading.value = false
- }
+ if (collectionsType.value.type === "my-collections") {
+ try {
+ // Chooser modal warns about lossiness upfront; per-export warnings would
+ // be redundant.
+ const { doc: openAPIDoc } = hoppCollectionToOpenAPI(
+ collection as HoppCollection
)
- )()
+ const name = (collection as HoppCollection).name
+ await saveOpenAPIDoc(openAPIDoc, name)
+ } catch {
+ toast.error(t("error.something_went_wrong"))
+ } finally {
+ if (thisGeneration === exportGeneration) closeExportModal()
+ }
+ } else {
+ if (!collection.id) {
+ closeExportModal()
+ return
+ }
+ const teamID = collectionsType.value.selectedTeam?.teamID
+ if (!teamID) {
+ closeExportModal()
+ return
+ }
+
+ try {
+ const result = await getTeamCollectionObject(teamID, collection.id)
+ if (E.isLeft(result)) {
+ const errMsg =
+ typeof result.left === "string"
+ ? result.left
+ : getErrorMessage(result.left)
+ toast.error(`${errMsg}`)
+ return
+ }
+ const hoppColl = result.right
+ const { doc: openAPIDoc } = hoppCollectionToOpenAPI(hoppColl)
+ await saveOpenAPIDoc(openAPIDoc, hoppColl.name)
+ } catch {
+ toast.error(t("error.something_went_wrong"))
+ } finally {
+ if (thisGeneration === exportGeneration) closeExportModal()
+ }
}
}
diff --git a/packages/hoppscotch-common/src/components/importExport/Base.vue b/packages/hoppscotch-common/src/components/importExport/Base.vue
index d7de6c12e..16dd07842 100644
--- a/packages/hoppscotch-common/src/components/importExport/Base.vue
+++ b/packages/hoppscotch-common/src/components/importExport/Base.vue
@@ -115,8 +115,16 @@ const chooseImporterOrExporter = defineStep(
const selectedExporter = props.exporterModules.find(
(i) => i.metadata.id === id
)
-
- if (selectedExporter && selectedExporter.action) {
+ if (!selectedExporter) return
+
+ // Prefer in-modal step navigation when the exporter declares one;
+ // fall back to the legacy fire-and-forget action for exporters that
+ // pop their own UI (e.g. Gist).
+ if (selectedExporter.component) {
+ goToStep(selectedExporter.component.id)
+ return
+ }
+ if (selectedExporter.action) {
selectedExporter.action()
}
},
@@ -184,6 +192,14 @@ watch(
{ deep: true }
)
+// Register exporter steps (e.g. format chooser) so the modal can advance to
+// them via goToStep instead of opening a parallel modal.
+props.exporterModules.forEach((exporter) => {
+ if (exporter.component) {
+ addStep(exporter.component)
+ }
+})
+
props.importerModules.forEach((importer) => {
if (importer.component) {
addStep(importer.component)
diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/__tests__/openapi.spec.ts b/packages/hoppscotch-common/src/helpers/import-export/export/__tests__/openapi.spec.ts
new file mode 100644
index 000000000..89bc98b4e
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/import-export/export/__tests__/openapi.spec.ts
@@ -0,0 +1,3516 @@
+import { describe, expect, it } from "vitest"
+import {
+ makeRESTRequest,
+ getDefaultRESTRequest,
+ makeCollection,
+ makeHoppRESTResponseOriginalRequest,
+ HoppCollection,
+ HoppRESTRequest,
+ HoppRESTRequestResponse,
+} from "@hoppscotch/data"
+import { OpenAPI } from "openapi-types"
+import SwaggerParser from "@apidevtools/swagger-parser"
+import { hoppCollectionToOpenAPI } from "../openapi"
+import {
+ convertOpenApiDocsToHopp,
+ splitTagSegments,
+ hasSharedTagPathPrefix,
+ pickRequestFolderSegments,
+} from "../../import/openapi"
+
+function buildCollection(
+ overrides: Partial<Parameters<typeof makeCollection>[0]> = {}
+) {
+ return makeCollection({
+ name: "Test Collection",
+ requests: [],
+ folders: [],
+ auth: { authType: "inherit", authActive: true },
+ headers: [],
+ variables: [],
+ description: null,
+ preRequestScript: "",
+ testScript: "",
+ ...overrides,
+ } as Parameters<typeof makeCollection>[0])
+}
+
+function buildRequest(
+ overrides: Partial<Parameters<typeof makeRESTRequest>[0]> = {}
+) {
+ const base = getDefaultRESTRequest()
+ return makeRESTRequest({
+ ...base,
+ ...overrides,
+ } as Parameters<typeof makeRESTRequest>[0])
+}
+
+describe("hoppCollectionToOpenAPI", () => {
+ it("produces a valid OpenAPI 3.1.0 document structure", () => {
+ const collection = buildCollection({ name: "My API" })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.openapi).toBe("3.1.0")
+ expect(doc.info.title).toBe("My API")
+ expect(doc.info.version).toBe("1.0.0")
+ expect(doc.paths).toBeDefined()
+ })
+
+ it("includes collection description in info", () => {
+ const collection = buildCollection({
+ name: "My API",
+ description: "A test API",
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.info.description).toBe("A test API")
+ })
+
+ it("omits description when null", () => {
+ const collection = buildCollection({ description: null })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.info.description).toBeUndefined()
+ })
+
+ describe("requests and paths", () => {
+ it("converts a root-level GET request", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get Users",
+ method: "GET",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/users"]).toBeDefined()
+ expect(doc.paths!["/users"]!.get).toBeDefined()
+ expect(doc.paths!["/users"]!.get!.summary).toBe("Get Users")
+ expect(doc.paths!["/users"]!.get!.operationId).toBe("Get_Users")
+ })
+
+ it("extracts server URL from endpoint", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get Users",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.servers).toEqual([{ url: "https://api.example.com" }])
+ })
+
+ it("deduplicates server URLs", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get Users",
+ endpoint: "https://api.example.com/users",
+ }),
+ buildRequest({
+ name: "Get Posts",
+ endpoint: "https://api.example.com/posts",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.servers).toHaveLength(1)
+ })
+
+ it("handles relative paths (no server)", () => {
+ const collection = buildCollection({
+ requests: [buildRequest({ name: "Test", endpoint: "/api/test" })],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.servers).toBeUndefined()
+ expect(doc.paths!["/api/test"]).toBeDefined()
+ })
+
+ it("converts template variables <<var>> to {var}", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get User",
+ endpoint: "https://api.example.com/users/<<id>>",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/users/{id}"]).toBeDefined()
+ })
+
+ it("auto-generates path params for template variables without requestVariables", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get User",
+ endpoint: "https://api.example.com/users/<<id>>/posts/<<postId>>",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/users/{id}/posts/{postId}"]!.get!
+ .parameters as any[]
+
+ const pathParams = params.filter((p: any) => p.in === "path")
+ expect(pathParams).toHaveLength(2)
+ expect(pathParams).toContainEqual(
+ expect.objectContaining({ name: "id", in: "path", required: true })
+ )
+ expect(pathParams).toContainEqual(
+ expect.objectContaining({ name: "postId", in: "path", required: true })
+ )
+ })
+
+ it("does not duplicate path params already defined in requestVariables", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get User",
+ endpoint: "https://api.example.com/users/<<id>>",
+ requestVariables: [{ key: "id", value: "123", active: true }],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/users/{id}"]!.get!.parameters as any[]
+
+ const pathParams = params.filter((p: any) => p.in === "path")
+ expect(pathParams).toHaveLength(1)
+ expect(pathParams[0].example).toBe("123")
+ })
+
+ it("deduplicates operationIds for requests with the same name", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get Users",
+ method: "GET",
+ endpoint: "https://api.example.com/users",
+ }),
+ buildRequest({
+ name: "Get Users",
+ method: "POST",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/users"]!.get!.operationId).toBe("Get_Users")
+ expect(doc.paths!["/users"]!.post!.operationId).toBe("Get_Users_2")
+ })
+
+ it("falls back to method_path operationId when name is all special characters", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "!!!",
+ method: "GET",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/users"]!.get!.operationId).toBe("get_users")
+ })
+
+ it("maps multiple HTTP methods to the same path", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get Users",
+ method: "GET",
+ endpoint: "https://api.example.com/users",
+ }),
+ buildRequest({
+ name: "Create User",
+ method: "POST",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/users"]!.get).toBeDefined()
+ expect(doc.paths!["/users"]!.post).toBeDefined()
+ })
+
+ it("includes request description when present", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get Users",
+ endpoint: "https://api.example.com/users",
+ description: "Fetches all users",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/users"]!.get!.description).toBe("Fetches all users")
+ })
+ })
+
+ describe("parameters", () => {
+ it("converts active query params", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Search",
+ endpoint: "https://api.example.com/search",
+ params: [
+ { key: "q", value: "test", active: true, description: "" },
+ {
+ key: "inactive",
+ value: "skip",
+ active: false,
+ description: "",
+ },
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/search"]!.get!.parameters as any[]
+
+ expect(params).toHaveLength(1)
+ expect(params[0]).toMatchObject({
+ name: "q",
+ in: "query",
+ example: "test",
+ })
+ })
+
+ it("converts active headers", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ headers: [
+ { key: "X-Custom", value: "val", active: true, description: "" },
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/test"]!.get!.parameters as any[]
+
+ expect(params).toHaveLength(1)
+ expect(params[0]).toMatchObject({
+ name: "X-Custom",
+ in: "header",
+ example: "val",
+ })
+ })
+
+ it("converts path variables as required", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get User",
+ endpoint: "https://api.example.com/users/<<id>>",
+ requestVariables: [{ key: "id", value: "123", active: true }],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/users/{id}"]!.get!.parameters as any[]
+
+ const pathParam = params.find((p: any) => p.in === "path")
+ expect(pathParam).toMatchObject({
+ name: "id",
+ in: "path",
+ required: true,
+ example: "123",
+ })
+ })
+
+ it("omits parameters when none are active", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ params: [
+ { key: "skip", value: "me", active: false, description: "" },
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/test"]!.get!.parameters).toBeUndefined()
+ })
+ })
+
+ describe("request body", () => {
+ it("converts JSON body with parsed example", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Create User",
+ method: "POST",
+ endpoint: "https://api.example.com/users",
+ body: {
+ contentType: "application/json",
+ body: '{"name":"John"}',
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const reqBody = doc.paths!["/users"]!.post!.requestBody as any
+
+ expect(reqBody.content["application/json"].example).toEqual({
+ name: "John",
+ })
+ })
+
+ it("handles invalid JSON body gracefully", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ method: "POST",
+ endpoint: "https://api.example.com/test",
+ body: {
+ contentType: "application/json",
+ body: "not json",
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const reqBody = doc.paths!["/test"]!.post!.requestBody as any
+
+ expect(reqBody.content["application/json"].example).toBe("not json")
+ })
+
+ it("converts multipart/form-data body", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Upload",
+ method: "POST",
+ endpoint: "https://api.example.com/upload",
+ body: {
+ contentType: "multipart/form-data",
+ body: [
+ {
+ key: "file",
+ value: "",
+ active: true,
+ isFile: true,
+ },
+ {
+ key: "name",
+ value: "test",
+ active: true,
+ isFile: false,
+ },
+ {
+ key: "inactive",
+ value: "skip",
+ active: false,
+ isFile: false,
+ },
+ ],
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const schema = (doc.paths!["/upload"]!.post!.requestBody as any).content[
+ "multipart/form-data"
+ ].schema
+
+ expect(schema.properties.file).toEqual({
+ type: "string",
+ format: "binary",
+ })
+ expect(schema.properties.name).toEqual({
+ type: "string",
+ example: "test",
+ })
+ expect(schema.properties.inactive).toBeUndefined()
+ })
+
+ it("converts form-urlencoded body", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Login",
+ method: "POST",
+ endpoint: "https://api.example.com/login",
+ body: {
+ contentType: "application/x-www-form-urlencoded",
+ // Hoppscotch persists urlencoded bodies as RawKeyValue
+ // (`key: value` per line) — match the on-disk format.
+ body: "username: admin\npassword: secret",
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const schema = (doc.paths!["/login"]!.post!.requestBody as any).content[
+ "application/x-www-form-urlencoded"
+ ].schema
+
+ expect(schema.properties.username).toEqual({
+ type: "string",
+ example: "admin",
+ })
+ expect(schema.properties.password).toEqual({
+ type: "string",
+ example: "secret",
+ })
+ })
+
+ it("converts plain text body", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Send Text",
+ method: "POST",
+ endpoint: "https://api.example.com/text",
+ body: { contentType: "text/plain", body: "Hello world" },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const reqBody = doc.paths!["/text"]!.post!.requestBody as any
+
+ expect(reqBody.content["text/plain"].example).toBe("Hello world")
+ })
+
+ it("omits requestBody when contentType is null", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get",
+ endpoint: "https://api.example.com/test",
+ body: { contentType: null, body: null },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/test"]!.get!.requestBody).toBeUndefined()
+ })
+ })
+
+ describe("authentication", () => {
+ it("converts basic auth", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "basic",
+ authActive: true,
+ username: "user",
+ password: "pass",
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.components!.securitySchemes!.basicAuth).toEqual({
+ type: "http",
+ scheme: "basic",
+ })
+ expect(doc.paths!["/test"]!.get!.security).toEqual([{ basicAuth: [] }])
+ })
+
+ it("converts bearer auth", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "bearer",
+ authActive: true,
+ token: "abc123",
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.components!.securitySchemes!.bearerAuth).toEqual({
+ type: "http",
+ scheme: "bearer",
+ })
+ })
+
+ it("converts OAuth2 authorization code flow", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "oauth-2",
+ authActive: true,
+ addTo: "HEADERS",
+ grantTypeInfo: {
+ grantType: "AUTHORIZATION_CODE",
+ authEndpoint: "https://auth.example.com/authorize",
+ tokenEndpoint: "https://auth.example.com/token",
+ clientID: "client123",
+ clientSecret: "secret",
+ scopes: "read write",
+ isPKCE: false,
+ codeVerifierMethod: "S256",
+ token: "",
+ },
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const scheme = doc.components!.securitySchemes!.oauth2 as any
+
+ expect(scheme.type).toBe("oauth2")
+ expect(scheme.flows.authorizationCode).toEqual({
+ authorizationUrl: "https://auth.example.com/authorize",
+ tokenUrl: "https://auth.example.com/token",
+ scopes: { read: "", write: "" },
+ })
+ })
+
+ it("converts OAuth2 client credentials flow", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "oauth-2",
+ authActive: true,
+ addTo: "HEADERS",
+ grantTypeInfo: {
+ grantType: "CLIENT_CREDENTIALS",
+ authEndpoint: "https://auth.example.com/token",
+ clientID: "client123",
+ clientSecret: "secret",
+ scopes: "admin",
+ token: "",
+ },
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const scheme = doc.components!.securitySchemes!.oauth2 as any
+
+ expect(scheme.flows.clientCredentials).toEqual({
+ tokenUrl: "https://auth.example.com/token",
+ scopes: { admin: "" },
+ })
+ })
+
+ it("converts OAuth2 password flow", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "oauth-2",
+ authActive: true,
+ addTo: "HEADERS",
+ grantTypeInfo: {
+ grantType: "PASSWORD",
+ authEndpoint: "https://auth.example.com/token",
+ clientID: "client123",
+ clientSecret: "secret",
+ username: "user",
+ password: "pass",
+ scopes: "",
+ token: "",
+ },
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const scheme = doc.components!.securitySchemes!.oauth2 as any
+
+ expect(scheme.flows.password).toEqual({
+ tokenUrl: "https://auth.example.com/token",
+ scopes: {},
+ })
+ })
+
+ it("converts OAuth2 implicit flow", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "oauth-2",
+ authActive: true,
+ addTo: "HEADERS",
+ grantTypeInfo: {
+ grantType: "IMPLICIT",
+ authEndpoint: "https://auth.example.com/authorize",
+ clientID: "client123",
+ scopes: "profile email",
+ token: "",
+ },
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const scheme = doc.components!.securitySchemes!.oauth2 as any
+
+ expect(scheme.flows.implicit).toEqual({
+ authorizationUrl: "https://auth.example.com/authorize",
+ scopes: { profile: "", email: "" },
+ })
+ expect(doc.paths!["/test"]!.get!.security).toEqual([
+ { oauth2: ["profile", "email"] },
+ ])
+ })
+
+ it("merges OAuth2 flows across requests with different grant types", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Auth Code Request",
+ endpoint: "https://api.example.com/a",
+ auth: {
+ authType: "oauth-2",
+ authActive: true,
+ addTo: "HEADERS",
+ grantTypeInfo: {
+ grantType: "AUTHORIZATION_CODE",
+ authEndpoint: "https://auth.example.com/authorize",
+ tokenEndpoint: "https://auth.example.com/token",
+ clientID: "c",
+ clientSecret: "s",
+ scopes: "read",
+ isPKCE: false,
+ codeVerifierMethod: "S256",
+ token: "",
+ },
+ } as any,
+ }),
+ buildRequest({
+ name: "Client Credentials Request",
+ endpoint: "https://api.example.com/b",
+ auth: {
+ authType: "oauth-2",
+ authActive: true,
+ addTo: "HEADERS",
+ grantTypeInfo: {
+ grantType: "CLIENT_CREDENTIALS",
+ authEndpoint: "https://auth.example.com/token",
+ clientID: "c",
+ clientSecret: "s",
+ scopes: "admin",
+ token: "",
+ },
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const scheme = doc.components!.securitySchemes!.oauth2 as any
+
+ expect(scheme.flows.authorizationCode).toEqual({
+ authorizationUrl: "https://auth.example.com/authorize",
+ tokenUrl: "https://auth.example.com/token",
+ scopes: { read: "" },
+ })
+ expect(scheme.flows.clientCredentials).toEqual({
+ tokenUrl: "https://auth.example.com/token",
+ scopes: { admin: "" },
+ })
+ expect(doc.paths!["/a"]!.get!.security).toEqual([{ oauth2: ["read"] }])
+ expect(doc.paths!["/b"]!.get!.security).toEqual([{ oauth2: ["admin"] }])
+ })
+
+ it("unions OAuth2 scopes across requests sharing a grant type and endpoints", () => {
+ const grantInfo = {
+ grantType: "AUTHORIZATION_CODE" as const,
+ authEndpoint: "https://auth.example.com/authorize",
+ tokenEndpoint: "https://auth.example.com/token",
+ clientID: "c",
+ clientSecret: "s",
+ isPKCE: false,
+ codeVerifierMethod: "S256" as const,
+ token: "",
+ }
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Read",
+ endpoint: "https://api.example.com/read",
+ auth: {
+ authType: "oauth-2",
+ authActive: true,
+ addTo: "HEADERS",
+ grantTypeInfo: { ...grantInfo, scopes: "read:users" },
+ } as any,
+ }),
+ buildRequest({
+ name: "Write",
+ endpoint: "https://api.example.com/write",
+ auth: {
+ authType: "oauth-2",
+ authActive: true,
+ addTo: "HEADERS",
+ grantTypeInfo: { ...grantInfo, scopes: "write:users" },
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const scheme = doc.components!.securitySchemes!.oauth2 as any
+
+ expect(scheme.flows.authorizationCode.scopes).toEqual({
+ "read:users": "",
+ "write:users": "",
+ })
+ expect(doc.paths!["/read"]!.get!.security).toEqual([
+ { oauth2: ["read:users"] },
+ ])
+ expect(doc.paths!["/write"]!.get!.security).toEqual([
+ { oauth2: ["write:users"] },
+ ])
+ })
+
+ it("flags OAuth2 endpoint conflicts within a shared grant type as lossy", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Service A",
+ endpoint: "https://a.example.com/a-resource",
+ auth: {
+ authType: "oauth-2",
+ authActive: true,
+ addTo: "HEADERS",
+ grantTypeInfo: {
+ grantType: "AUTHORIZATION_CODE",
+ authEndpoint: "https://a.example.com/authorize",
+ tokenEndpoint: "https://a.example.com/token",
+ clientID: "c",
+ clientSecret: "s",
+ scopes: "read",
+ isPKCE: false,
+ codeVerifierMethod: "S256",
+ token: "",
+ },
+ } as any,
+ }),
+ buildRequest({
+ name: "Service B",
+ endpoint: "https://b.example.com/b-resource",
+ auth: {
+ authType: "oauth-2",
+ authActive: true,
+ addTo: "HEADERS",
+ grantTypeInfo: {
+ grantType: "AUTHORIZATION_CODE",
+ authEndpoint: "https://b.example.com/authorize",
+ tokenEndpoint: "https://b.example.com/token",
+ clientID: "c",
+ clientSecret: "s",
+ scopes: "read",
+ isPKCE: false,
+ codeVerifierMethod: "S256",
+ token: "",
+ },
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const scheme = doc.components!.securitySchemes!.oauth2 as any
+
+ // Earlier endpoints win; later conflicting endpoints drop silently.
+ expect(scheme.flows.authorizationCode.authorizationUrl).toBe(
+ "https://a.example.com/authorize"
+ )
+ expect(scheme.flows.authorizationCode.tokenUrl).toBe(
+ "https://a.example.com/token"
+ )
+ })
+
+ it("converts API key auth in header", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "api-key",
+ authActive: true,
+ key: "X-API-Key",
+ value: "secret",
+ addTo: "HEADERS",
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const scheme = doc.components!.securitySchemes![
+ "apiKey_header_X-API-Key"
+ ] as any
+
+ expect(scheme).toEqual({
+ type: "apiKey",
+ in: "header",
+ name: "X-API-Key",
+ })
+ })
+
+ it("converts API key auth in query params", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "api-key",
+ authActive: true,
+ key: "api_key",
+ value: "secret",
+ addTo: "QUERY_PARAMS",
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const scheme = doc.components!.securitySchemes![
+ "apiKey_query_api_key"
+ ] as any
+
+ expect(scheme).toEqual({
+ type: "apiKey",
+ in: "query",
+ name: "api_key",
+ })
+ })
+
+ it("converts JWT auth", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "jwt",
+ authActive: true,
+ secret: "s3cret",
+ privateKey: "",
+ algorithm: "HS256",
+ payload: "{}",
+ addTo: "HEADERS",
+ headerPrefix: "Bearer",
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.components!.securitySchemes!.jwtAuth).toEqual({
+ type: "http",
+ scheme: "bearer",
+ bearerFormat: "JWT",
+ })
+ expect(doc.paths!["/test"]!.get!.security).toEqual([{ jwtAuth: [] }])
+ })
+
+ it("converts digest auth", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "digest",
+ authActive: true,
+ username: "user",
+ password: "pass",
+ realm: "",
+ nonce: "",
+ algorithm: "MD5",
+ qop: "auth",
+ nc: "",
+ cnonce: "",
+ opaque: "",
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.components!.securitySchemes!.digestAuth).toEqual({
+ type: "http",
+ scheme: "digest",
+ })
+ })
+
+ it("converts AWS Signature auth", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "aws-signature",
+ authActive: true,
+ accessKey: "AKIA...",
+ secretKey: "secret",
+ region: "us-east-1",
+ serviceName: "s3",
+ addTo: "HEADERS",
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.components!.securitySchemes!.awsSigV4).toEqual({
+ type: "apiKey",
+ in: "header",
+ name: "Authorization",
+ description: "AWS Signature Version 4",
+ })
+ })
+
+ it("converts HAWK auth", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "hawk",
+ authActive: true,
+ authId: "id123",
+ authKey: "key456",
+ algorithm: "sha256",
+ includePayloadHash: false,
+ timestamp: "",
+ nonce: "",
+ ext: "",
+ app: "",
+ dlg: "",
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.components!.securitySchemes!.hawkAuth).toEqual({
+ type: "apiKey",
+ in: "header",
+ name: "Authorization",
+ description: "Hawk authentication",
+ })
+ })
+
+ it("converts Akamai EdgeGrid auth", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "akamai-eg",
+ authActive: true,
+ accessToken: "token",
+ clientToken: "client",
+ clientSecret: "secret",
+ baseURL: "",
+ timestamp: "",
+ nonce: "",
+ headersToSign: "",
+ maxBodySize: 131072,
+ } as any,
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.components!.securitySchemes!.akamaiEdgeGrid).toEqual({
+ type: "apiKey",
+ in: "header",
+ name: "Authorization",
+ description: "Akamai EdgeGrid authentication",
+ })
+ })
+
+ it("skips auth when authActive is false", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ auth: {
+ authType: "basic",
+ authActive: false,
+ username: "user",
+ password: "pass",
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.components).toBeUndefined()
+ expect(doc.paths!["/test"]!.get!.security).toBeUndefined()
+ })
+
+ it("exports collection-level auth as global security", () => {
+ const collection = buildCollection({
+ auth: {
+ authType: "basic",
+ authActive: true,
+ username: "user",
+ password: "pass",
+ },
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.security).toEqual([{ basicAuth: [] }])
+ expect(doc.components!.securitySchemes!.basicAuth).toEqual({
+ type: "http",
+ scheme: "basic",
+ })
+ })
+
+ it("skips global security for inherit/none collection auth", () => {
+ const collection = buildCollection({
+ auth: { authType: "inherit", authActive: true },
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.security).toBeUndefined()
+ })
+
+ it("sets security to empty array when authType is none and authActive is true", () => {
+ const collection = buildCollection({
+ auth: {
+ authType: "basic",
+ authActive: true,
+ username: "u",
+ password: "p",
+ },
+ requests: [
+ buildRequest({
+ name: "Public",
+ endpoint: "https://api.example.com/health",
+ auth: { authType: "none", authActive: true },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.security).toEqual([{ basicAuth: [] }])
+ expect(doc.paths!["/health"]!.get!.security).toEqual([])
+ })
+ })
+
+ describe("collection-level headers", () => {
+ it("includes collection-level headers in operation parameters", () => {
+ const collection = buildCollection({
+ headers: [
+ {
+ key: "X-Global",
+ value: "global-val",
+ active: true,
+ description: "",
+ },
+ ],
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/test"]!.get!.parameters as any[]
+
+ expect(params).toContainEqual(
+ expect.objectContaining({
+ name: "X-Global",
+ in: "header",
+ example: "global-val",
+ })
+ )
+ })
+
+ it("request headers override collection headers (case-insensitive)", () => {
+ const collection = buildCollection({
+ headers: [
+ {
+ key: "X-Custom",
+ value: "collection-val",
+ active: true,
+ description: "",
+ },
+ ],
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ headers: [
+ {
+ key: "x-custom",
+ value: "request-val",
+ active: true,
+ description: "",
+ },
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/test"]!.get!.parameters as any[]
+
+ const headerParams = params.filter((p: any) => p.in === "header")
+ expect(headerParams).toHaveLength(1)
+ expect(headerParams[0].example).toBe("request-val")
+ })
+ })
+
+ describe("folders and tags", () => {
+ it("creates tags from folders", () => {
+ const collection = buildCollection({
+ folders: [
+ buildCollection({
+ name: "Users",
+ requests: [
+ buildRequest({
+ name: "List Users",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.tags).toContainEqual({ name: "Users" })
+ expect(doc.paths!["/users"]!.get!.tags).toEqual(["Users"])
+ })
+
+ it("creates nested tag paths for nested folders", () => {
+ const collection = buildCollection({
+ folders: [
+ buildCollection({
+ name: "API",
+ folders: [
+ buildCollection({
+ name: "Users",
+ requests: [
+ buildRequest({
+ name: "List",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ }),
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.tags).toContainEqual({ name: "API" })
+ expect(doc.tags).toContainEqual({ name: "API/Users" })
+ expect(doc.paths!["/users"]!.get!.tags).toEqual(["API/Users"])
+ })
+
+ it("root-level requests have no tags", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Health",
+ endpoint: "https://api.example.com/health",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/health"]!.get!.tags).toBeUndefined()
+ expect(doc.tags).toBeUndefined()
+ })
+ })
+
+ describe("responses", () => {
+ it("generates default 200 response when no responses saved", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ responses: {},
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/test"]!.get!.responses).toEqual({
+ "200": { description: "Successful response" },
+ })
+ })
+
+ it("converts saved responses with body and headers", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ responses: {
+ resp1: {
+ name: "Success",
+ code: 200,
+ status: "OK",
+ headers: [
+ { key: "Content-Type", value: "application/json" },
+ { key: "X-Request-Id", value: "abc" },
+ ],
+ body: '{"result":"ok"}',
+ } as any,
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const resp = doc.paths!["/test"]!.get!.responses["200"] as any
+
+ expect(resp.description).toBe("Success")
+ expect(resp.headers["X-Request-Id"].example).toBe("abc")
+ expect(resp.content["application/json"].example).toEqual({
+ result: "ok",
+ })
+ })
+
+ it("falls back to default 200 when every saved response has a null code", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ responses: {
+ resp1: {
+ name: "draft",
+ code: null,
+ status: "",
+ headers: [],
+ body: "",
+ } as any,
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.paths!["/test"]!.get!.responses).toEqual({
+ "200": { description: "Successful response" },
+ })
+ })
+ })
+
+ describe("dropped output", () => {
+ it("drops duplicate (path, method) operations — first wins", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "First",
+ method: "GET",
+ endpoint: "https://api.example.com/users",
+ }),
+ buildRequest({
+ name: "Second",
+ method: "GET",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/users"]!.get!.summary).toBe("First")
+ })
+
+ it("skips operations with HTTP methods OpenAPI does not support", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Connect Tunnel",
+ method: "CONNECT",
+ endpoint: "https://api.example.com/tunnel",
+ }),
+ buildRequest({
+ name: "Get Users",
+ method: "GET",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/tunnel"]).toBeUndefined()
+ expect(doc.paths!["/users"]).toBeDefined()
+ })
+ })
+
+ describe("path template variables (regression)", () => {
+ // These tests document the BLOCKER fix: the WHATWG URL parser
+ // percent-encodes `{}` to `%7B%7D` in pathnames. The converter must
+ // decode those back so OpenAPI path parameters land correctly.
+ it("preserves {var} placeholders that the URL parser percent-encoded", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get",
+ endpoint: "https://api.example.com/users/{id}",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.paths!["/users/{id}"]).toBeDefined()
+ })
+
+ it("converts <<var>> in absolute URLs to {var} after URL parsing", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get",
+ endpoint: "https://api.example.com/users/<<id>>/posts/<<postId>>",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.paths!["/users/{id}/posts/{postId}"]).toBeDefined()
+ })
+
+ it("preserves intentionally percent-encoded path segments (e.g. %2F)", () => {
+ // Regression: an over-eager decodeURIComponent on the whole pathname
+ // would turn `%2F` into a literal `/`, splitting a single segment in two.
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get",
+ endpoint: "https://api.example.com/files/a%2Fb/info",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.paths!["/files/a%2Fb/info"]).toBeDefined()
+ expect(doc.paths!["/files/a/b/info"]).toBeUndefined()
+ })
+
+ it("strips fragments from relative endpoints", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({ name: "Get", endpoint: "/users/list#section" }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.paths!["/users/list"]).toBeDefined()
+ expect(doc.paths!["/users/list#section"]).toBeUndefined()
+ })
+
+ it("treats a leading <<var>> as the server, not as a path segment", () => {
+ // Regression: `<<baseUrl>>/pets/9704` was previously kept whole inside
+ // the path, then importer-side double-prefixed `<<baseUrl>>` on round-trip.
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Get pet",
+ endpoint: "<<baseUrl>>/pets/9704",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+
+ expect(doc.paths!["/pets/9704"]).toBeDefined()
+ // The leading variable lands in servers, not in any path key
+ expect(doc.paths!["/<<baseUrl>>/pets/9704"]).toBeUndefined()
+ expect(doc.paths!["/{baseUrl}/pets/9704"]).toBeUndefined()
+ expect(doc.servers).toEqual([{ url: "<<baseUrl>>" }])
+ })
+
+ it("handles a bare leading <<var>> with no path", () => {
+ const collection = buildCollection({
+ requests: [buildRequest({ name: "Root", endpoint: "<<baseUrl>>" })],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.paths!["/"]).toBeDefined()
+ expect(doc.servers).toEqual([{ url: "<<baseUrl>>" }])
+ })
+
+ it("resolves a leading <<var>> to its collection-variable value in servers", () => {
+ // Regression: previously the doc shipped `servers: [{ url: "<<baseUrl>>" }]`
+ // even when the collection knew the actual host. OpenAPI consumers can't
+ // resolve Hoppscotch placeholders, so we substitute the value here.
+ const collection = buildCollection({
+ variables: [
+ {
+ key: "baseUrl",
+ initialValue: "https://api.petstore.com",
+ currentValue: "https://api.petstore.com",
+ secret: false,
+ },
+ ],
+ requests: [
+ buildRequest({
+ name: "Get pet",
+ endpoint: "<<baseUrl>>/pets/9704",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.servers).toEqual([{ url: "https://api.petstore.com" }])
+ expect(doc.paths!["/pets/9704"]).toBeDefined()
+ })
+
+ it("works for any variable name, not only baseUrl", () => {
+ const collection = buildCollection({
+ variables: [
+ {
+ key: "petstoreHost",
+ initialValue: "https://api.petstore.com",
+ currentValue: "https://api.petstore.com",
+ secret: false,
+ },
+ ],
+ requests: [
+ buildRequest({
+ name: "Get pet",
+ endpoint: "<<petstoreHost>>/pets/9704",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.servers).toEqual([{ url: "https://api.petstore.com" }])
+ })
+
+ it("does not leak secret variables into the exported servers", () => {
+ const collection = buildCollection({
+ variables: [
+ {
+ key: "secretHost",
+ initialValue: "https://internal.example.com",
+ currentValue: "https://internal.example.com",
+ secret: true,
+ },
+ ],
+ requests: [
+ buildRequest({
+ name: "Get",
+ endpoint: "<<secretHost>>/api/x",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ // Falls back to the placeholder so the user can see something is off,
+ // rather than embedding a secret value into the spec.
+ expect(doc.servers).toEqual([{ url: "<<secretHost>>" }])
+ })
+
+ it("falls back to placeholder when no matching variable exists", () => {
+ const collection = buildCollection({
+ variables: [],
+ requests: [
+ buildRequest({
+ name: "Get",
+ endpoint: "<<unknown>>/path",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.servers).toEqual([{ url: "<<unknown>>" }])
+ })
+
+ it("uses currentValue, falling back to initialValue", () => {
+ const collection = buildCollection({
+ variables: [
+ {
+ key: "baseUrl",
+ initialValue: "https://prod.example.com",
+ currentValue: "https://staging.example.com",
+ secret: false,
+ },
+ ],
+ requests: [buildRequest({ name: "Get", endpoint: "<<baseUrl>>/x" })],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.servers).toEqual([{ url: "https://staging.example.com" }])
+ })
+
+ it("a deeper folder variable overrides a collection variable", () => {
+ const collection = buildCollection({
+ variables: [
+ {
+ key: "baseUrl",
+ initialValue: "https://prod.example.com",
+ currentValue: "https://prod.example.com",
+ secret: false,
+ },
+ ],
+ folders: [
+ buildCollection({
+ name: "Sandbox",
+ variables: [
+ {
+ key: "baseUrl",
+ initialValue: "https://sandbox.example.com",
+ currentValue: "https://sandbox.example.com",
+ secret: false,
+ },
+ ],
+ requests: [
+ buildRequest({ name: "Get", endpoint: "<<baseUrl>>/x" }),
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.servers).toEqual([{ url: "https://sandbox.example.com" }])
+ })
+ })
+
+ describe("URL query string handling", () => {
+ it("extracts query params from absolute URL into operation parameters", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Search",
+ endpoint: "https://api.example.com/search?q=hello&limit=10",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/search"]!.get!.parameters as any[]
+
+ // path key has no `?`
+ expect(doc.paths!["/search?q=hello&limit=10"]).toBeUndefined()
+ const queryParams = params.filter((p: any) => p.in === "query")
+ expect(queryParams).toContainEqual(
+ expect.objectContaining({ name: "q", example: "hello" })
+ )
+ expect(queryParams).toContainEqual(
+ expect.objectContaining({ name: "limit", example: "10" })
+ )
+ })
+
+ it("strips query string from a relative endpoint and exposes its params", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Filter",
+ endpoint: "/users?active=true",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.paths!["/users"]).toBeDefined()
+ // path key must not contain `?`
+ expect(doc.paths!["/users?active=true"]).toBeUndefined()
+ const params = doc.paths!["/users"]!.get!.parameters as any[]
+ const queryParams = params.filter((p: any) => p.in === "query")
+ expect(queryParams).toContainEqual(
+ expect.objectContaining({ name: "active", example: "true" })
+ )
+ })
+
+ it("explicit request.params take precedence over duplicates in URL", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Search",
+ endpoint: "https://api.example.com/search?q=from-url",
+ params: [
+ {
+ key: "q",
+ value: "from-explicit",
+ active: true,
+ description: "",
+ },
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/search"]!.get!.parameters as any[]
+ const queryParams = params.filter((p: any) => p.in === "query")
+ expect(queryParams).toHaveLength(1)
+ expect(queryParams[0].example).toBe("from-explicit")
+ })
+ })
+
+ describe("parameter de-duplication", () => {
+ it("dedupes duplicate query params (first wins)", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/test",
+ params: [
+ { key: "page", value: "1", active: true, description: "" },
+ { key: "page", value: "2", active: true, description: "" },
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/test"]!.get!.parameters as any[]
+ const queryParams = params.filter((p: any) => p.in === "query")
+ expect(queryParams).toHaveLength(1)
+ expect(queryParams[0].example).toBe("1")
+ })
+
+ it("dedupes duplicate path params introduced both via requestVariables and path", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "Test",
+ endpoint: "https://api.example.com/users/<<id>>/posts/<<id>>",
+ requestVariables: [{ key: "id", value: "42", active: true }],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const params = doc.paths!["/users/{id}/posts/{id}"]!.get!
+ .parameters as any[]
+ const pathParams = params.filter((p: any) => p.in === "path")
+ expect(pathParams).toHaveLength(1)
+ expect(pathParams[0].name).toBe("id")
+ })
+ })
+
+ describe("auth inheritance", () => {
+ it("operation inherits folder-level auth when request auth is inherit", () => {
+ const collection = buildCollection({
+ folders: [
+ buildCollection({
+ name: "Authenticated",
+ auth: {
+ authType: "basic",
+ authActive: true,
+ username: "u",
+ password: "p",
+ },
+ requests: [
+ buildRequest({
+ name: "Get Secure",
+ endpoint: "https://api.example.com/secure",
+ auth: { authType: "inherit", authActive: true },
+ }),
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.paths!["/secure"]!.get!.security).toEqual([{ basicAuth: [] }])
+ expect(doc.components!.securitySchemes!.basicAuth).toEqual({
+ type: "http",
+ scheme: "basic",
+ })
+ })
+
+ it("nested folder auth wins over collection auth via inherit", () => {
+ const collection = buildCollection({
+ auth: {
+ authType: "basic",
+ authActive: true,
+ username: "u",
+ password: "p",
+ },
+ folders: [
+ buildCollection({
+ name: "Inner",
+ auth: { authType: "bearer", authActive: true, token: "t" },
+ requests: [
+ buildRequest({
+ name: "Get",
+ endpoint: "https://api.example.com/inner",
+ auth: { authType: "inherit", authActive: true },
+ }),
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.paths!["/inner"]!.get!.security).toEqual([{ bearerAuth: [] }])
+ })
+
+ it("folder auth=none under collection auth produces empty operation security", () => {
+ const collection = buildCollection({
+ auth: {
+ authType: "basic",
+ authActive: true,
+ username: "u",
+ password: "p",
+ },
+ folders: [
+ buildCollection({
+ name: "Public",
+ auth: { authType: "none", authActive: true },
+ requests: [
+ buildRequest({
+ name: "Health",
+ endpoint: "https://api.example.com/public/health",
+ auth: { authType: "inherit", authActive: true },
+ }),
+ ],
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ expect(doc.paths!["/public/health"]!.get!.security).toEqual([])
+ expect(doc.security).toEqual([{ basicAuth: [] }])
+ })
+ })
+
+ describe("API key scheme name collisions", () => {
+ it("disambiguates API-key schemes that sanitize to the same name", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "A",
+ endpoint: "https://api.example.com/a",
+ auth: {
+ authType: "api-key",
+ authActive: true,
+ key: "X@Api-Key",
+ value: "v1",
+ addTo: "HEADERS",
+ },
+ }),
+ buildRequest({
+ name: "B",
+ endpoint: "https://api.example.com/b",
+ auth: {
+ authType: "api-key",
+ authActive: true,
+ key: "X#Api-Key",
+ value: "v2",
+ addTo: "HEADERS",
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const schemes = doc.components!.securitySchemes!
+ const schemeNames = Object.keys(schemes)
+ // both schemes should exist under different names; neither should silently overwrite
+ expect(schemeNames).toHaveLength(2)
+ // each operation should reference its own scheme
+ const aSec = doc.paths!["/a"]!.get!.security as any[]
+ const bSec = doc.paths!["/b"]!.get!.security as any[]
+ expect(Object.keys(aSec[0])[0]).not.toBe(Object.keys(bSec[0])[0])
+ // but the underlying scheme.name fields should differ
+ const aSchemeName = Object.keys(aSec[0])[0]
+ const bSchemeName = Object.keys(bSec[0])[0]
+ expect((schemes[aSchemeName] as any).name).toBe("X@Api-Key")
+ expect((schemes[bSchemeName] as any).name).toBe("X#Api-Key")
+ })
+
+ it("reuses the scheme name when two API-key schemes are identical", () => {
+ const collection = buildCollection({
+ requests: [
+ buildRequest({
+ name: "A",
+ endpoint: "https://api.example.com/a",
+ auth: {
+ authType: "api-key",
+ authActive: true,
+ key: "X-Api-Key",
+ value: "v",
+ addTo: "HEADERS",
+ },
+ }),
+ buildRequest({
+ name: "B",
+ endpoint: "https://api.example.com/b",
+ auth: {
+ authType: "api-key",
+ authActive: true,
+ key: "X-Api-Key",
+ value: "v",
+ addTo: "HEADERS",
+ },
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ const schemes = doc.components!.securitySchemes!
+ expect(Object.keys(schemes)).toHaveLength(1)
+ })
+ })
+})
+
+// Round-trip audit: HoppCollection -> OpenAPI 3.1 -> HoppCollection.
+// Tests labelled `LOSSY` document a known and disclosed loss; tests without
+// that label assert exact preservation. New regressions surfaced by the
+// audit land here.
+
+const buildResponse = (
+ overrides: {
+ name?: string
+ code?: number
+ status?: string
+ headers?: Array<{ key: string; value: string }>
+ body?: string
+ } = {}
+): HoppRESTRequestResponse =>
+ ({
+ name: "Success",
+ code: 200,
+ status: "OK",
+ headers: [],
+ body: "",
+ ...overrides,
+ originalRequest: makeHoppRESTResponseOriginalRequest({
+ name: "Test",
+ method: "GET",
+ endpoint: "https://api.example.com/test",
+ params: [],
+ headers: [],
+ auth: { authType: "inherit", authActive: true },
+ body: { contentType: null, body: null },
+ requestVariables: [],
+ }),
+ }) as HoppRESTRequestResponse
+
+const buildColl = (
+ overrides: Partial<Parameters<typeof makeCollection>[0]> = {}
+) =>
+ makeCollection({
+ name: "Round Trip",
+ requests: [],
+ folders: [],
+ auth: { authType: "inherit", authActive: true },
+ headers: [],
+ variables: [],
+ description: null,
+ preRequestScript: "",
+ testScript: "",
+ ...overrides,
+ } as Parameters<typeof makeCollection>[0])
+
+const buildReq = (
+ overrides: Partial<Parameters<typeof makeRESTRequest>[0]> = {}
+) =>
+ makeRESTRequest({
+ name: "Test",
+ method: "GET",
+ endpoint: "https://api.example.com/test",
+ params: [],
+ headers: [],
+ preRequestScript: "",
+ testScript: "",
+ auth: { authType: "inherit", authActive: true },
+ body: { contentType: null, body: null },
+ requestVariables: [],
+ responses: {},
+ description: null,
+ ...overrides,
+ } as Parameters<typeof makeRESTRequest>[0])
+
+const roundTrip = async (input: HoppCollection): Promise<HoppCollection> => {
+ const { doc } = hoppCollectionToOpenAPI(input)
+ const r = await convertOpenApiDocsToHopp([doc as OpenAPI.Document])()
+ if (r._tag === "Left") throw new Error(r.left as string)
+ return r.right[0]
+}
+
+// `HoppCollection["requests"]` is a union of REST and GQL; every fixture below
+// builds REST. These accessors narrow the union so tests can read REST-only
+// fields (`requestVariables`, `responses`, `method`) without per-call casts.
+const restRequestsOf = (c: HoppCollection | undefined): HoppRESTRequest[] =>
+ (c?.requests ?? []) as HoppRESTRequest[]
+
+const firstReq = (c: HoppCollection): HoppRESTRequest | undefined => {
+ const direct = restRequestsOf(c)[0]
+ if (direct) return direct
+ const inFolder = restRequestsOf(c.folders[0])[0]
+ if (inFolder) return inFolder
+ return restRequestsOf(c.folders[0]?.folders[0])[0]
+}
+
+// Identity fields: collection name/description, request name/description/method.
+describe("round-trip — identity fields", () => {
+ it("preserves collection name", async () => {
+ const out = await roundTrip(buildColl({ name: "My API" }))
+ expect(out.name).toBe("My API")
+ })
+
+ it("preserves collection description", async () => {
+ const out = await roundTrip(buildColl({ description: "A description" }))
+ expect(out.description).toBe("A description")
+ })
+
+ it("preserves request name (with spaces)", async () => {
+ const out = await roundTrip(
+ buildColl({ requests: [buildReq({ name: "Get Pet By ID" })] })
+ )
+ expect(firstReq(out)?.name).toBe("Get Pet By ID")
+ })
+
+ it("preserves request description", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [buildReq({ description: "Fetches a single pet" })],
+ })
+ )
+ expect(firstReq(out)?.description).toBe("Fetches a single pet")
+ })
+
+ it("preserves request method", async () => {
+ const out = await roundTrip(
+ buildColl({ requests: [buildReq({ method: "POST" })] })
+ )
+ expect(firstReq(out)?.method).toBe("POST")
+ })
+})
+
+// Endpoint shape: server URL parametrization, baseUrl seeding, path templates.
+describe("round-trip — endpoint variants", () => {
+ it("LOSSY: absolute URL gets parametrized to <<baseUrl>> + collection variable", async () => {
+ // Importer seeds a `baseUrl` variable from the doc's `servers[0].url` so
+ // users have one place to switch hosts. Endpoints are rewritten to use
+ // the placeholder. The actual request still resolves to the original URL
+ // at runtime via the variable.
+ const out = await roundTrip(
+ buildColl({
+ requests: [buildReq({ endpoint: "https://api.example.com/pets/9704" })],
+ })
+ )
+ expect(firstReq(out)?.endpoint).toBe("<<baseUrl>>/pets/9704")
+ expect(out.variables[0]?.key).toBe("baseUrl")
+ expect(out.variables[0]?.initialValue).toBe("https://api.example.com")
+ // Importer leaves currentValue empty; runtime values live in
+ // CurrentValueService and are not synced server-side.
+ expect(out.variables[0]?.currentValue).toBe("")
+ })
+
+ it("preserves leading <<var>> when collection has no value for it", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [buildReq({ endpoint: "<<unknownHost>>/pets/9704" })],
+ })
+ )
+ expect(firstReq(out)?.endpoint).toBe("<<unknownHost>>/pets/9704")
+ })
+
+ it("LOSSY: variable name normalizes to baseUrl when value is known", async () => {
+ // Original variable was `petstoreHost` with a real URL. Exporter resolves
+ // to the URL; importer re-creates as `baseUrl`.
+ const out = await roundTrip(
+ buildColl({
+ variables: [
+ {
+ key: "petstoreHost",
+ initialValue: "https://api.petstore.com",
+ currentValue: "https://api.petstore.com",
+ secret: false,
+ },
+ ],
+ requests: [buildReq({ endpoint: "<<petstoreHost>>/pets" })],
+ })
+ )
+ expect(firstReq(out)?.endpoint).toBe("<<baseUrl>>/pets")
+ expect(out.variables[0]?.key).toBe("baseUrl")
+ expect(out.variables[0]?.initialValue).toBe("https://api.petstore.com")
+ expect(out.variables[0]?.currentValue).toBe("")
+ })
+
+ it("preserves path template variables (under <<baseUrl>>)", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ endpoint: "https://api.example.com/users/<<id>>",
+ requestVariables: [{ key: "id", value: "42", active: true }],
+ }),
+ ],
+ })
+ )
+ // Server is parametrized; path keeps its template variable; the
+ // requestVariable's value round-trips via the OpenAPI `example` field.
+ expect(firstReq(out)?.endpoint).toBe("<<baseUrl>>/users/<<id>>")
+ expect(firstReq(out)?.requestVariables[0]?.key).toBe("id")
+ expect(firstReq(out)?.requestVariables[0]?.value).toBe("42")
+ })
+})
+
+// Query params: keys, values, descriptions.
+describe("round-trip — query params", () => {
+ it("preserves query param keys", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ params: [
+ { key: "q", value: "x", active: true, description: "" },
+ { key: "limit", value: "10", active: true, description: "" },
+ ],
+ }),
+ ],
+ })
+ )
+ const keys = firstReq(out)?.params.map((p) => p.key) ?? []
+ expect(keys).toContain("q")
+ expect(keys).toContain("limit")
+ })
+
+ it("preserves query param values", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ params: [
+ { key: "q", value: "hello", active: true, description: "" },
+ ],
+ }),
+ ],
+ })
+ )
+ const p = firstReq(out)?.params.find((p) => p.key === "q")
+ expect(p?.value).toBe("hello")
+ })
+
+ it("preserves query param descriptions", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ params: [
+ {
+ key: "status",
+ value: "open",
+ active: true,
+ description: "Filter by status",
+ },
+ ],
+ }),
+ ],
+ })
+ )
+ const p = firstReq(out)?.params.find((p) => p.key === "status")
+ expect(p?.description).toBe("Filter by status")
+ })
+})
+
+// Per-request and collection-level headers.
+describe("round-trip — headers", () => {
+ it("preserves request header keys and values", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ headers: [
+ {
+ key: "X-Custom",
+ value: "abc",
+ active: true,
+ description: "",
+ },
+ ],
+ }),
+ ],
+ })
+ )
+ const h = firstReq(out)?.headers.find((h) => h.key === "X-Custom")
+ expect(h?.value).toBe("abc")
+ })
+
+ it("collection-level headers become per-request headers on round-trip", async () => {
+ // OpenAPI has no concept of doc-level headers; the converter emits them
+ // as per-operation headers. On reimport they land on each request.
+ const out = await roundTrip(
+ buildColl({
+ headers: [
+ { key: "X-Global", value: "g", active: true, description: "" },
+ ],
+ requests: [buildReq({ headers: [] })],
+ })
+ )
+ const h = firstReq(out)?.headers.find((h) => h.key === "X-Global")
+ expect(h?.value).toBe("g")
+ })
+})
+
+// Auth schemes — credentials never survive (intentional: secrets stay out
+// of exported docs). Only the auth type/scheme is preserved.
+describe("round-trip — auth", () => {
+ it("LOSSY: basic auth — credentials are dropped (only scheme survives)", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ auth: {
+ authType: "basic",
+ authActive: true,
+ username: "alice",
+ password: "secret",
+ },
+ }),
+ ],
+ })
+ )
+ expect(firstReq(out)?.auth.authType).toBe("basic")
+ expect((firstReq(out)?.auth as { username?: string }).username).toBe("")
+ expect((firstReq(out)?.auth as { password?: string }).password).toBe("")
+ })
+
+ it("LOSSY: bearer token is dropped", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ auth: { authType: "bearer", authActive: true, token: "abc" },
+ }),
+ ],
+ })
+ )
+ expect(firstReq(out)?.auth.authType).toBe("bearer")
+ expect((firstReq(out)?.auth as { token?: string }).token).toBe("")
+ })
+
+ it("LOSSY: api-key value dropped (key name preserved)", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ auth: {
+ authType: "api-key",
+ authActive: true,
+ key: "X-API-Key",
+ value: "secret-value",
+ addTo: "HEADERS",
+ },
+ }),
+ ],
+ })
+ )
+ const a = firstReq(out)?.auth as {
+ authType: string
+ key?: string
+ value?: string
+ }
+ expect(a.authType).toBe("api-key")
+ expect(a.key).toBe("X-API-Key")
+ expect(a.value).toBe("")
+ })
+})
+
+// Body shapes: JSON, multipart, urlencoded, plain text.
+describe("round-trip — body", () => {
+ it("preserves JSON body content", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ method: "POST",
+ body: {
+ contentType: "application/json",
+ body: '{"name":"Buddy"}',
+ },
+ }),
+ ],
+ })
+ )
+ expect(firstReq(out)?.body.contentType).toBe("application/json")
+ })
+
+ it("preserves multipart/form-data field structure", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ method: "POST",
+ body: {
+ contentType: "multipart/form-data",
+ body: [
+ {
+ key: "name",
+ value: "Buddy",
+ active: true,
+ isFile: false,
+ },
+ ],
+ },
+ }),
+ ],
+ })
+ )
+ expect(firstReq(out)?.body.contentType).toBe("multipart/form-data")
+ })
+
+ it("preserves JSON body content (string)", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ method: "POST",
+ body: {
+ contentType: "application/json",
+ body: '{"name":"Buddy"}',
+ },
+ }),
+ ],
+ })
+ )
+ const r = firstReq(out)
+ expect(r?.body.contentType).toBe("application/json")
+ if (typeof r?.body.body === "string") {
+ const original = JSON.parse('{"name":"Buddy"}')
+ const got = JSON.parse(r.body.body)
+ expect(got).toEqual(original)
+ }
+ })
+
+ it("preserves plain text body content", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ method: "POST",
+ body: { contentType: "text/plain", body: "hello world" },
+ }),
+ ],
+ })
+ )
+ expect(firstReq(out)?.body.contentType).toBe("text/plain")
+ expect(firstReq(out)?.body.body).toBe("hello world")
+ })
+
+ it("multipart entries preserve key+isFile flag", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ method: "POST",
+ body: {
+ contentType: "multipart/form-data",
+ body: [
+ {
+ key: "name",
+ value: "Buddy",
+ active: true,
+ isFile: false,
+ },
+ {
+ key: "avatar",
+ value: "",
+ active: true,
+ isFile: true,
+ },
+ ],
+ },
+ }),
+ ],
+ })
+ )
+ const body = firstReq(out)?.body
+ expect(body?.contentType).toBe("multipart/form-data")
+ if (Array.isArray(body?.body)) {
+ const name = body.body.find((e: { key: string }) => e.key === "name")
+ const avatar = body.body.find((e: { key: string }) => e.key === "avatar")
+ expect(name).toBeDefined()
+ expect(avatar?.isFile).toBe(true)
+ }
+ })
+
+ it("urlencoded body keys round-trip", async () => {
+ // Hoppscotch persists urlencoded bodies in RawKeyValue (`key: value`
+ // per line) format, not querystring form — fixture matches on-disk
+ // representation produced by the URL-encoded body editor.
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ method: "POST",
+ body: {
+ contentType: "application/x-www-form-urlencoded",
+ body: "user: alice\npass: secret",
+ },
+ }),
+ ],
+ })
+ )
+ const body = firstReq(out)?.body
+ expect(body?.contentType).toBe("application/x-www-form-urlencoded")
+ if (typeof body?.body === "string") {
+ expect(body.body).toMatch(/user/)
+ expect(body.body).toMatch(/pass/)
+ }
+ })
+})
+
+// Saved responses on a request.
+describe("round-trip — saved responses", () => {
+ it("preserves response name and code", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ responses: {
+ ok: buildResponse({
+ name: "Success",
+ code: 200,
+ status: "OK",
+ body: '{"ok":true}',
+ }),
+ },
+ }),
+ ],
+ })
+ )
+ const responses = firstReq(out)?.responses ?? {}
+ const r = Object.values(responses)[0] as { name?: string; code?: number }
+ expect(r?.code).toBe(200)
+ })
+
+ it("preserves response status code and body for a single saved response", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ responses: {
+ ok: buildResponse({
+ name: "OK",
+ code: 200,
+ status: "OK",
+ headers: [{ key: "Content-Type", value: "application/json" }],
+ body: '{"ok":true}',
+ }),
+ },
+ }),
+ ],
+ })
+ )
+ const r = firstReq(out)
+ const responses = r?.responses ?? {}
+ const first = Object.values(responses)[0] as {
+ code?: number
+ body?: string
+ }
+ expect(first?.code).toBe(200)
+ })
+})
+
+// Folder structure: deep nesting, descriptions, multiple top-level folders.
+describe("round-trip — folder hierarchy", () => {
+ it("preserves a deeply nested folder", async () => {
+ const out = await roundTrip(
+ buildColl({
+ folders: [
+ buildColl({
+ name: "API",
+ folders: [
+ buildColl({
+ name: "Users",
+ requests: [
+ buildReq({
+ name: "List",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ }),
+ ],
+ }),
+ ],
+ })
+ )
+ expect(out.folders[0]?.name).toBe("API")
+ expect(out.folders[0]?.folders[0]?.name).toBe("Users")
+ expect(restRequestsOf(out.folders[0]?.folders[0])[0]?.name).toBe("List")
+ })
+
+ it("preserves folder description", async () => {
+ const out = await roundTrip(
+ buildColl({
+ folders: [
+ buildColl({
+ name: "Users",
+ description: "Endpoints for managing users",
+ requests: [
+ buildReq({
+ name: "Get",
+ endpoint: "https://api.example.com/users/me",
+ }),
+ ],
+ }),
+ ],
+ })
+ )
+ expect(out.folders[0]?.description).toBe("Endpoints for managing users")
+ })
+
+ it("preserves multiple top-level folders", async () => {
+ const out = await roundTrip(
+ buildColl({
+ folders: [
+ buildColl({
+ name: "Pets",
+ requests: [
+ buildReq({
+ name: "List",
+ endpoint: "https://api.example.com/pets",
+ }),
+ ],
+ }),
+ buildColl({
+ name: "Orders",
+ requests: [
+ buildReq({
+ name: "List",
+ endpoint: "https://api.example.com/orders",
+ }),
+ ],
+ }),
+ ],
+ })
+ )
+ const names = out.folders.map((f) => f.name).sort()
+ expect(names).toEqual(["Orders", "Pets"])
+ })
+})
+
+// Collection-level auth: stays on the collection rather than being flattened
+// to per-request copies. Per-request explicit overrides still survive.
+describe("round-trip — collection-level auth structure", () => {
+ it("collection-level basic auth stays on the collection (not duplicated on each request)", async () => {
+ const out = await roundTrip(
+ buildColl({
+ auth: {
+ authType: "basic",
+ authActive: true,
+ username: "alice",
+ password: "secret",
+ },
+ requests: [
+ buildReq({
+ name: "A",
+ endpoint: "https://api.example.com/a",
+ }),
+ buildReq({
+ name: "B",
+ endpoint: "https://api.example.com/b",
+ }),
+ ],
+ })
+ )
+ expect(out.auth.authType).toBe("basic")
+ expect(restRequestsOf(out)[0]?.auth.authType).toBe("inherit")
+ expect(restRequestsOf(out)[1]?.auth.authType).toBe("inherit")
+ })
+
+ it("per-request explicit override coexists with collection-level default", async () => {
+ const out = await roundTrip(
+ buildColl({
+ auth: {
+ authType: "basic",
+ authActive: true,
+ username: "alice",
+ password: "p",
+ },
+ requests: [
+ buildReq({
+ name: "Inherits",
+ endpoint: "https://api.example.com/a",
+ }),
+ buildReq({
+ name: "Overrides",
+ endpoint: "https://api.example.com/b",
+ auth: { authType: "bearer", authActive: true, token: "t" },
+ }),
+ ],
+ })
+ )
+ expect(out.auth.authType).toBe("basic")
+ const inheritReq = restRequestsOf(out).find((r) => r.name === "Inherits")
+ const overrideReq = restRequestsOf(out).find((r) => r.name === "Overrides")
+ expect(inheritReq?.auth.authType).toBe("inherit")
+ expect(overrideReq?.auth.authType).toBe("bearer")
+ })
+
+ it("explicit no-auth on a request (authType=none) round-trips as none, not inherit", async () => {
+ const out = await roundTrip(
+ buildColl({
+ auth: {
+ authType: "basic",
+ authActive: true,
+ username: "u",
+ password: "p",
+ },
+ requests: [
+ buildReq({
+ name: "Public",
+ endpoint: "https://api.example.com/health",
+ auth: { authType: "none", authActive: true },
+ }),
+ ],
+ })
+ )
+ expect(out.auth.authType).toBe("basic")
+ expect(restRequestsOf(out)[0]?.auth.authType).toBe("none")
+ })
+
+ it("collection without any auth round-trips as inherit", async () => {
+ const out = await roundTrip(
+ buildColl({
+ auth: { authType: "inherit", authActive: true },
+ requests: [buildReq({ endpoint: "https://api.example.com/a" })],
+ })
+ )
+ expect(out.auth.authType).toBe("inherit")
+ expect(restRequestsOf(out)[0]?.auth.authType).toBe("inherit")
+ })
+})
+
+// Validates the exported doc against the OpenAPI 3.1 spec via SwaggerParser.
+// Catches output that's structurally invalid even if our own importer is lenient.
+describe("exported doc validates against OpenAPI 3.1 spec", () => {
+ const validate = async (collection: HoppCollection) => {
+ const { doc } = hoppCollectionToOpenAPI(collection)
+ // SwaggerParser mutates input; clone first.
+ const cloned = JSON.parse(JSON.stringify(doc))
+ await SwaggerParser.validate(cloned)
+ }
+
+ it("a minimal collection produces a valid OpenAPI 3.1 doc", async () => {
+ await expect(
+ validate(
+ buildColl({
+ requests: [buildReq({ endpoint: "https://api.example.com/pets" })],
+ })
+ )
+ ).resolves.not.toThrow()
+ })
+
+ it("a collection with auth + headers + body validates", async () => {
+ await expect(
+ validate(
+ buildColl({
+ requests: [
+ buildReq({
+ method: "POST",
+ endpoint: "https://api.example.com/pets",
+ headers: [
+ {
+ key: "X-Custom",
+ value: "abc",
+ active: true,
+ description: "",
+ },
+ ],
+ params: [
+ {
+ key: "draft",
+ value: "true",
+ active: true,
+ description: "",
+ },
+ ],
+ auth: {
+ authType: "bearer",
+ authActive: true,
+ token: "tk",
+ },
+ body: {
+ contentType: "application/json",
+ body: '{"name":"Buddy"}',
+ },
+ }),
+ ],
+ })
+ )
+ ).resolves.not.toThrow()
+ })
+
+ it("a collection with nested folders validates", async () => {
+ await expect(
+ validate(
+ buildColl({
+ folders: [
+ buildColl({
+ name: "API",
+ folders: [
+ buildColl({
+ name: "Users",
+ requests: [
+ buildReq({
+ name: "List",
+ endpoint: "https://api.example.com/users",
+ }),
+ ],
+ }),
+ ],
+ }),
+ ],
+ })
+ )
+ ).resolves.not.toThrow()
+ })
+
+ it("a collection that resolves a baseUrl variable validates (no <<>> in spec output)", async () => {
+ await expect(
+ validate(
+ buildColl({
+ variables: [
+ {
+ key: "baseUrl",
+ initialValue: "https://api.example.com",
+ currentValue: "https://api.example.com",
+ secret: false,
+ },
+ ],
+ requests: [buildReq({ endpoint: "<<baseUrl>>/pets" })],
+ })
+ )
+ ).resolves.not.toThrow()
+ })
+})
+
+// Active flag preservation. OpenAPI has no concept of inactive params/headers,
+// so inactive entries are dropped on export and reimported as active=true.
+describe("round-trip — active flag", () => {
+ it("LOSSY: inactive query params are dropped on export (only active ones survive)", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ params: [
+ {
+ key: "kept",
+ value: "1",
+ active: true,
+ description: "",
+ },
+ {
+ key: "skipped",
+ value: "x",
+ active: false,
+ description: "",
+ },
+ ],
+ }),
+ ],
+ })
+ )
+ const keys = firstReq(out)?.params.map((p) => p.key) ?? []
+ expect(keys).toContain("kept")
+ expect(keys).not.toContain("skipped")
+ })
+
+ it("LOSSY: inactive headers are dropped on export", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ headers: [
+ {
+ key: "X-Kept",
+ value: "1",
+ active: true,
+ description: "",
+ },
+ {
+ key: "X-Skipped",
+ value: "x",
+ active: false,
+ description: "",
+ },
+ ],
+ }),
+ ],
+ })
+ )
+ const keys = firstReq(out)?.headers.map((h) => h.key) ?? []
+ expect(keys).toContain("X-Kept")
+ expect(keys).not.toContain("X-Skipped")
+ })
+
+ it("active flag defaults to true on import (OpenAPI has no concept of disabled params)", async () => {
+ const out = await roundTrip(
+ buildColl({
+ requests: [
+ buildReq({
+ params: [{ key: "q", value: "1", active: true, description: "" }],
+ }),
+ ],
+ })
+ )
+ expect(firstReq(out)?.params[0]?.active).toBe(true)
+ })
+})
+
+// Combined-features fixture mimicking a real Petstore-shaped collection,
+// to catch interactions that single-feature tests miss.
+describe("round-trip — kitchen sink (combined features)", () => {
+ it("a real-world-shaped collection survives round-trip with the expected losses", async () => {
+ const original = buildColl({
+ name: "Petstore",
+ description: "Test API",
+ variables: [
+ {
+ key: "baseUrl",
+ initialValue: "https://api.petstore.com",
+ currentValue: "https://api.petstore.com",
+ secret: false,
+ },
+ ],
+ headers: [
+ {
+ key: "X-Tenant",
+ value: "default",
+ active: true,
+ description: "Tenant",
+ },
+ ],
+ folders: [
+ buildColl({
+ name: "Pets",
+ description: "Pet endpoints",
+ requests: [
+ buildReq({
+ name: "Get pet by ID",
+ method: "GET",
+ endpoint: "<<baseUrl>>/v1/pets/<<petId>>",
+ params: [
+ {
+ key: "include",
+ value: "tags",
+ active: true,
+ description: "Comma-separated includes",
+ },
+ ],
+ requestVariables: [{ key: "petId", value: "9704", active: true }],
+ }),
+ buildReq({
+ name: "Add a new pet",
+ method: "POST",
+ endpoint: "<<baseUrl>>/v1/pets",
+ body: {
+ contentType: "application/json",
+ body: '{"name":"Buddy","status":"available"}',
+ },
+ }),
+ ],
+ }),
+ ],
+ })
+
+ const out = await roundTrip(original)
+
+ expect(out.name).toBe("Petstore")
+ expect(out.description).toBe("Test API")
+
+ const petsFolder = out.folders.find((f) => f.name === "Pets")
+ expect(petsFolder).toBeDefined()
+ expect(petsFolder?.description).toBe("Pet endpoints")
+
+ expect(out.variables[0]?.key).toBe("baseUrl")
+ expect(out.variables[0]?.initialValue).toBe("https://api.petstore.com")
+ expect(out.variables[0]?.currentValue).toBe("")
+
+ const getReq = restRequestsOf(petsFolder).find(
+ (r) => r.name === "Get pet by ID"
+ )
+ expect(getReq?.endpoint).toBe("<<baseUrl>>/v1/pets/<<petId>>")
+ expect(getReq?.params[0]?.value).toBe("tags")
+ expect(getReq?.params[0]?.description).toBe("Comma-separated includes")
+ expect(getReq?.requestVariables[0]?.value).toBe("9704")
+
+ const addReq = restRequestsOf(petsFolder).find(
+ (r) => r.name === "Add a new pet"
+ )
+ expect(addReq?.method).toBe("POST")
+ expect(addReq?.body.contentType).toBe("application/json")
+ })
+})
+
+// Collection variables — only the auto-seeded baseUrl from the server URL
+// survives. Other custom variables (tokens, IDs) are dropped on export.
+describe("round-trip — collection variables", () => {
+ it("LOSSY: collection variable definitions are dropped (only the seeded baseUrl from server URL survives)", async () => {
+ const out = await roundTrip(
+ buildColl({
+ variables: [
+ {
+ key: "apiToken",
+ initialValue: "tk-xxx",
+ currentValue: "tk-xxx",
+ secret: true,
+ },
+ {
+ key: "tenantId",
+ initialValue: "1234",
+ currentValue: "1234",
+ secret: false,
+ },
+ ],
+ requests: [buildReq({ endpoint: "https://api.example.com/x" })],
+ })
+ )
+ expect(out.variables.map((v) => v.key)).toEqual(["baseUrl"])
+ })
+})
+
+// Folder hierarchy: tag splitting, marker, and importer integration.
+// Pure-function tests for the segment helpers, plus integration tests that
+// drive the full importer with synthetic OpenAPI fixtures.
+
+describe("splitTagSegments", () => {
+ it("splits on slash and filters empty segments", () => {
+ expect(splitTagSegments("API/Users")).toEqual(["API", "Users"])
+ expect(splitTagSegments("/API/Users/")).toEqual(["API", "Users"])
+ expect(splitTagSegments("API//Users")).toEqual(["API", "Users"])
+ expect(splitTagSegments(" API / Users ")).toEqual(["API", "Users"])
+ expect(splitTagSegments("Single")).toEqual(["Single"])
+ expect(splitTagSegments("")).toEqual([])
+ })
+})
+
+describe("hasSharedTagPathPrefix", () => {
+ it("detects when one tag is a strict ancestor of another", () => {
+ expect(hasSharedTagPathPrefix(["API", "API/Users"])).toBe(true)
+ })
+
+ it("detects when two tags share a non-empty segment prefix", () => {
+ expect(hasSharedTagPathPrefix(["API/Users", "API/Posts"])).toBe(true)
+ })
+
+ it("returns false for unrelated single-segment tags", () => {
+ expect(hasSharedTagPathPrefix(["Users", "Admin", "Reports"])).toBe(false)
+ })
+
+ it("returns false for a single tag with literal slashes (no companion)", () => {
+ expect(hasSharedTagPathPrefix(["OAuth/PKCE"])).toBe(false)
+ expect(hasSharedTagPathPrefix(["Admin/API"])).toBe(false)
+ })
+
+ it("returns false when two unrelated multi-segment tags don't share a prefix", () => {
+ expect(hasSharedTagPathPrefix(["OAuth/PKCE", "Admin/API"])).toBe(false)
+ })
+})
+
+describe("pickRequestFolderSegments", () => {
+ it("returns the single literal tag when shouldSplit is false", () => {
+ expect(pickRequestFolderSegments(["API/Users"], false)).toEqual([
+ "API/Users",
+ ])
+ })
+
+ it("picks the deepest tag among multi-tag operations", () => {
+ expect(pickRequestFolderSegments(["API", "API/Users"], true)).toEqual([
+ "API",
+ "Users",
+ ])
+ })
+
+ it("ties broken by first occurrence", () => {
+ expect(pickRequestFolderSegments(["Foo/Bar", "Baz/Qux"], true)).toEqual([
+ "Foo",
+ "Bar",
+ ])
+ })
+
+ it("returns empty for no tags", () => {
+ expect(pickRequestFolderSegments([], true)).toEqual([])
+ expect(pickRequestFolderSegments([], false)).toEqual([])
+ })
+})
+
+// Test fixtures intentionally use permissively-typed OpenAPI documents so we
+// can build minimal docs without satisfying every required field.
+type DocOverrides = {
+ paths: Record<string, unknown>
+ info?: { title?: string; description?: string; version?: string }
+ tags?: Array<{ name: string; description?: string }>
+ [extension: `x-${string}`]: unknown
+}
+
+const buildOpenAPIDoc = (overrides: DocOverrides): OpenAPI.Document =>
+ ({
+ openapi: "3.1.0",
+ info: { title: "Test", version: "1.0.0" },
+ ...overrides,
+ }) as unknown as OpenAPI.Document
+
+type OpStub = {
+ summary: string
+ operationId: string
+ tags: string[]
+ responses: Record<string, { description: string }>
+}
+
+const op = (tags: string[], summary: string): OpStub => ({
+ summary,
+ operationId: summary.replace(/\W+/g, "_"),
+ tags,
+ responses: { "200": { description: "ok" } },
+})
+
+const runImport = async (doc: OpenAPI.Document) => {
+ const result = await convertOpenApiDocsToHopp([doc])()
+ if (result._tag === "Left") throw new Error(result.left as string)
+ return result.right[0]
+}
+
+describe("convertOpenApiDocsToHopp — request body examples", () => {
+ it("imports form-urlencoded object examples as JSON strings", async () => {
+ const coll = await runImport(
+ buildOpenAPIDoc({
+ paths: {
+ "/submit": {
+ post: {
+ ...op([], "Submit"),
+ requestBody: {
+ content: {
+ "application/x-www-form-urlencoded": {
+ schema: {
+ type: "object",
+ properties: {
+ payload: { example: { nested: true } },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ })
+ )
+
+ expect(firstReq(coll)?.body).toEqual({
+ contentType: "application/x-www-form-urlencoded",
+ body: 'payload: {"nested":true}',
+ })
+ })
+
+ it("imports multipart object examples as JSON strings for non-file fields", async () => {
+ const coll = await runImport(
+ buildOpenAPIDoc({
+ paths: {
+ "/upload": {
+ post: {
+ ...op([], "Upload"),
+ requestBody: {
+ content: {
+ "multipart/form-data": {
+ schema: {
+ type: "object",
+ properties: {
+ file: { type: "string", format: "binary" },
+ metadata: { example: { title: "avatar" } },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ })
+ )
+
+ expect(firstReq(coll)?.body).toEqual({
+ contentType: "multipart/form-data",
+ body: [
+ { key: "file", isFile: true, value: [], active: true },
+ {
+ key: "metadata",
+ isFile: false,
+ value: '{"title":"avatar"}',
+ active: true,
+ },
+ ],
+ })
+ })
+})
+
+describe("convertOpenApiDocsToHopp — folder hierarchy", () => {
+ it("nests folders when tags use slash convention with prefix tree", async () => {
+ const doc = buildOpenAPIDoc({
+ paths: {
+ "/users": { get: op(["API/Users"], "List") },
+ "/users/{id}": { get: op(["API/Users"], "Get") },
+ "/posts": { get: op(["API/Posts"], "ListPosts") },
+ },
+ })
+ const coll = await runImport(doc)
+
+ expect(coll.folders).toHaveLength(1)
+ expect(coll.folders[0].name).toBe("API")
+ expect(coll.folders[0].folders).toHaveLength(2)
+ const folderNames = coll.folders[0].folders.map((f) => f.name).sort()
+ expect(folderNames).toEqual(["Posts", "Users"])
+ })
+
+ it("places multi-tag operations at the deepest tag location only (no duplication)", async () => {
+ const doc = buildOpenAPIDoc({
+ paths: {
+ "/users/{id}": { get: op(["API", "API/Users"], "GetUser") },
+ },
+ })
+ const coll = await runImport(doc)
+
+ const apiFolder = coll.folders.find((f) => f.name === "API")!
+ expect(apiFolder).toBeDefined()
+ expect(apiFolder.requests).toHaveLength(0)
+ const usersFolder = apiFolder.folders.find((f) => f.name === "Users")!
+ expect(usersFolder.requests).toHaveLength(1)
+ expect(usersFolder.requests[0].name).toBe("GetUser")
+ })
+
+ it("respects the explicit Hoppscotch marker even with a single nested tag", async () => {
+ // Heuristic alone wouldn't split a lone "API/Users" — the marker forces it.
+ const doc = buildOpenAPIDoc({
+ "x-hoppscotch-folder-tags": "slash",
+ paths: { "/x": { get: op(["API/Users"], "X") } },
+ })
+ const coll = await runImport(doc)
+
+ expect(coll.folders).toHaveLength(1)
+ expect(coll.folders[0].name).toBe("API")
+ expect(coll.folders[0].folders).toHaveLength(1)
+ expect(coll.folders[0].folders[0].name).toBe("Users")
+ expect(coll.folders[0].folders[0].requests).toHaveLength(1)
+ })
+
+ it("keeps tags flat for a doc with literal-slash tag and no marker", async () => {
+ const doc = buildOpenAPIDoc({
+ paths: {
+ "/auth/pkce": { get: op(["OAuth/PKCE"], "Authorize") },
+ },
+ })
+ const coll = await runImport(doc)
+
+ expect(coll.folders).toHaveLength(1)
+ expect(coll.folders[0].name).toBe("OAuth/PKCE")
+ expect(coll.folders[0].folders).toHaveLength(0)
+ })
+
+ it("seeds a baseUrl collection variable from servers[0].url and parametrizes endpoints", async () => {
+ const doc = buildOpenAPIDoc({
+ servers: [{ url: "https://api.petstore.com" }],
+ paths: { "/v1/pets": { get: op([], "List") } },
+ } as DocOverrides)
+ const coll = await runImport(doc)
+
+ expect(coll.variables).toEqual([
+ {
+ key: "baseUrl",
+ initialValue: "https://api.petstore.com",
+ currentValue: "",
+ secret: false,
+ },
+ ])
+ expect(restRequestsOf(coll)[0]?.endpoint).toBe("<<baseUrl>>/v1/pets")
+ })
+
+ it("does not seed a baseUrl variable when the doc has no servers", async () => {
+ const doc = buildOpenAPIDoc({
+ paths: { "/health": { get: op([], "Health") } },
+ })
+ const coll = await runImport(doc)
+
+ expect(coll.variables).toEqual([])
+ expect(restRequestsOf(coll)[0]?.endpoint).toBe("<<baseUrl>>/health")
+ })
+
+ it("places untagged operations at the root", async () => {
+ const doc = buildOpenAPIDoc({
+ paths: { "/health": { get: op([], "Health") } },
+ })
+ const coll = await runImport(doc)
+
+ expect(coll.requests).toHaveLength(1)
+ expect(coll.requests[0].name).toBe("Health")
+ expect(coll.folders).toHaveLength(0)
+ })
+
+ it("applies tag descriptions at the matching folder level", async () => {
+ const doc = buildOpenAPIDoc({
+ tags: [
+ { name: "API", description: "Top-level API" },
+ { name: "API/Users", description: "User endpoints" },
+ ],
+ paths: { "/users": { get: op(["API/Users"], "Get") } },
+ })
+ const coll = await runImport(doc)
+
+ expect(coll.folders[0].name).toBe("API")
+ expect(coll.folders[0].description).toBe("Top-level API")
+ expect(coll.folders[0].folders[0].name).toBe("Users")
+ expect(coll.folders[0].folders[0].description).toBe("User endpoints")
+ })
+
+ it("collapses normalized-equivalent tags (API//Users === API/Users)", async () => {
+ const doc = buildOpenAPIDoc({
+ "x-hoppscotch-folder-tags": "slash",
+ tags: [
+ { name: "API//Users", description: "first" },
+ { name: "API/Users", description: "second" },
+ ],
+ paths: {
+ "/a": { get: op(["API//Users"], "A") },
+ "/b": { get: op(["API/Users"], "B") },
+ },
+ })
+ const coll = await runImport(doc)
+
+ expect(coll.folders).toHaveLength(1)
+ const usersFolder = coll.folders[0].folders[0]
+ expect(usersFolder.name).toBe("Users")
+ expect(usersFolder.requests).toHaveLength(2)
+ expect(usersFolder.description).toBe("first")
+ })
+})
+
+// Export -> import round-trip specifically for folder-related concerns
+// (marker emission, name preservation, leading <<var>> handling).
+describe("export → import round-trip preserves folder hierarchy", () => {
+ it("a single nested folder survives round-trip via the Hoppscotch marker", async () => {
+ const original = buildColl({
+ name: "Original",
+ folders: [
+ buildColl({
+ name: "API",
+ folders: [
+ buildColl({
+ name: "Users",
+ requests: [
+ buildReq({
+ name: "Get",
+ endpoint: "https://api.example.com/users/<<id>>",
+ }),
+ ],
+ }),
+ ],
+ }),
+ ],
+ })
+
+ const { doc } = hoppCollectionToOpenAPI(original)
+ expect((doc as Record<string, unknown>)["x-hoppscotch-folder-tags"]).toBe(
+ "slash"
+ )
+
+ const imported = await (async () => {
+ const r = await convertOpenApiDocsToHopp([doc as OpenAPI.Document])()
+ if (r._tag === "Left") throw new Error(r.left as string)
+ return r.right[0]
+ })()
+
+ expect(imported.folders).toHaveLength(1)
+ expect(imported.folders[0].name).toBe("API")
+ expect(imported.folders[0].folders).toHaveLength(1)
+ expect(imported.folders[0].folders[0].name).toBe("Users")
+ expect(imported.folders[0].folders[0].requests).toHaveLength(1)
+ expect(imported.folders[0].folders[0].requests[0].name).toBe("Get")
+ })
+
+ it("preserves spaces in request names through round-trip", async () => {
+ // Regression: importer used to prefer `operationId` (sanitized, e.g.
+ // `Get_Pet`) over `summary` (human-readable, e.g. `Get Pet`), so a
+ // round-trip turned `Get Pet` into `Get_Pet`.
+ const original = buildColl({
+ requests: [
+ buildReq({
+ name: "Get Pet",
+ endpoint: "https://api.example.com/pets/9704",
+ }),
+ ],
+ })
+ const { doc } = hoppCollectionToOpenAPI(original)
+
+ const imported = await (async () => {
+ const r = await convertOpenApiDocsToHopp([doc as OpenAPI.Document])()
+ if (r._tag === "Left") throw new Error(r.left as string)
+ return r.right[0]
+ })()
+
+ expect(imported.requests[0].name).toBe("Get Pet")
+ })
+
+ it("does not double-prefix endpoints that start with a Hoppscotch <<var>>", async () => {
+ // Regression: `<<baseUrl>>/pets/9704` round-tripped as
+ // `<<baseUrl>>/<<baseUrl>>/pets/9704` because the export side kept the
+ // variable inside the path key. After the fix, the variable becomes the
+ // server and the path is just `/pets/9704`.
+ const original = buildColl({
+ name: "Pets",
+ requests: [
+ buildReq({
+ name: "Get pet",
+ endpoint: "<<baseUrl>>/pets/9704",
+ }),
+ ],
+ })
+
+ const { doc } = hoppCollectionToOpenAPI(original)
+
+ const imported = await (async () => {
+ const r = await convertOpenApiDocsToHopp([doc as OpenAPI.Document])()
+ if (r._tag === "Left") throw new Error(r.left as string)
+ return r.right[0]
+ })()
+
+ expect(imported.requests).toHaveLength(1)
+ expect(restRequestsOf(imported)[0]?.endpoint).toBe("<<baseUrl>>/pets/9704")
+ })
+})
+
+// Backward compatibility: OpenAPI 3.0.x and Swagger 2.0.
+// The 3.1 fixes (collection-level auth, parameter value preservation,
+// multipart isFile, baseUrl seeding) were primarily exercised through 3.1
+// round-trips. These tests run equivalent docs in 3.0 and 2.0 shape to
+// surface any version-specific regressions.
+
+const importDoc = async (raw: unknown) => {
+ const r = await convertOpenApiDocsToHopp([raw as OpenAPI.Document])()
+ if (r._tag === "Left") throw new Error(r.left as string)
+ return r.right[0]
+}
+
+describe("OpenAPI 3.0.x compatibility", () => {
+ it("imports a 3.0 doc with servers + components.securitySchemes", async () => {
+ const doc = {
+ openapi: "3.0.0",
+ info: { title: "Petstore 3.0", version: "1.0.0" },
+ servers: [{ url: "https://api.petstore.com" }],
+ paths: {
+ "/pets": {
+ get: {
+ summary: "List pets",
+ operationId: "listPets",
+ tags: ["pets"],
+ parameters: [
+ {
+ name: "limit",
+ in: "query",
+ description: "Max items",
+ schema: { type: "integer" },
+ example: 20,
+ },
+ ],
+ responses: { "200": { description: "ok" } },
+ },
+ },
+ },
+ components: {
+ securitySchemes: {
+ basicAuth: { type: "http", scheme: "basic" },
+ },
+ },
+ security: [{ basicAuth: [] }],
+ }
+ const c = await importDoc(doc)
+ expect(c.variables[0]?.key).toBe("baseUrl")
+ expect(c.variables[0]?.initialValue).toBe("https://api.petstore.com")
+ expect(c.variables[0]?.currentValue).toBe("")
+ expect(c.auth.authType).toBe("basic")
+ const req = c.folders[0]?.requests[0] ?? c.requests[0]
+ expect(req?.auth.authType).toBe("inherit")
+ const limit = (
+ req as { params?: Array<{ key: string; value: string }> }
+ )?.params?.find((p) => p.key === "limit")
+ expect(limit?.value).toBe("20")
+ })
+
+ it("imports a 3.0 doc with operation-level security override", async () => {
+ const doc = {
+ openapi: "3.0.0",
+ info: { title: "X", version: "1.0.0" },
+ paths: {
+ "/public": {
+ get: {
+ operationId: "publicGet",
+ security: [],
+ responses: { "200": { description: "ok" } },
+ },
+ },
+ },
+ components: {
+ securitySchemes: {
+ basicAuth: { type: "http", scheme: "basic" },
+ },
+ },
+ security: [{ basicAuth: [] }],
+ }
+ const c = await importDoc(doc)
+ expect(c.auth.authType).toBe("basic")
+ expect(c.requests[0]?.auth.authType).toBe("none")
+ })
+})
+
+describe("Swagger 2.0 compatibility", () => {
+ it("seeds baseUrl from host + basePath + scheme", async () => {
+ const doc = {
+ swagger: "2.0",
+ info: { title: "Swagger 2", version: "1.0.0" },
+ host: "api.petstore.com",
+ basePath: "/v2",
+ schemes: ["https"],
+ paths: {
+ "/pets": {
+ get: {
+ operationId: "listPets",
+ responses: { "200": { description: "ok" } },
+ },
+ },
+ },
+ }
+ const c = await importDoc(doc)
+ expect(c.variables[0]?.key).toBe("baseUrl")
+ // Should be a fully-qualified URL — without the scheme, the variable
+ // value isn't a usable URL at runtime.
+ expect(c.variables[0]?.initialValue).toBe("https://api.petstore.com/v2")
+ expect(c.variables[0]?.currentValue).toBe("")
+ expect(restRequestsOf(c)[0]?.endpoint).toBe("<<baseUrl>>/pets")
+ })
+
+ it("falls back to https when schemes is missing", async () => {
+ const doc = {
+ swagger: "2.0",
+ info: { title: "X", version: "1.0.0" },
+ host: "api.example.com",
+ basePath: "/v1",
+ paths: {
+ "/x": {
+ get: {
+ operationId: "x",
+ responses: { "200": { description: "ok" } },
+ },
+ },
+ },
+ }
+ const c = await importDoc(doc)
+ expect(c.variables[0]?.initialValue).toBe("https://api.example.com/v1")
+ expect(c.variables[0]?.currentValue).toBe("")
+ })
+
+ it("imports query param with default value", async () => {
+ const doc = {
+ swagger: "2.0",
+ info: { title: "X", version: "1.0.0" },
+ host: "api.example.com",
+ paths: {
+ "/search": {
+ get: {
+ operationId: "search",
+ parameters: [
+ {
+ name: "q",
+ in: "query",
+ type: "string",
+ default: "hello",
+ },
+ ],
+ responses: { "200": { description: "ok" } },
+ },
+ },
+ },
+ }
+ const c = await importDoc(doc)
+ const params =
+ (c.requests[0] as { params?: Array<{ key: string; value: string }> })
+ ?.params ?? []
+ const q = params.find((p) => p.key === "q")
+ // V2 widely uses `default` for example values; we should preserve it.
+ expect(q?.value).toBe("hello")
+ })
+
+ it("imports collection-level securityDefinitions + security", async () => {
+ const doc = {
+ swagger: "2.0",
+ info: { title: "X", version: "1.0.0" },
+ host: "api.example.com",
+ paths: {
+ "/things": {
+ get: {
+ operationId: "listThings",
+ responses: { "200": { description: "ok" } },
+ },
+ },
+ },
+ securityDefinitions: {
+ basicAuth: { type: "basic" },
+ },
+ security: [{ basicAuth: [] }],
+ }
+ const c = await importDoc(doc)
+ expect(c.auth.authType).toBe("basic")
+ expect(c.requests[0]?.auth.authType).toBe("inherit")
+ })
+
+ it("imports a multipart formData body with isFile flag", async () => {
+ const doc = {
+ swagger: "2.0",
+ info: { title: "X", version: "1.0.0" },
+ host: "api.example.com",
+ paths: {
+ "/upload": {
+ post: {
+ operationId: "upload",
+ consumes: ["multipart/form-data"],
+ parameters: [
+ { name: "name", in: "formData", type: "string" },
+ { name: "avatar", in: "formData", type: "file" },
+ ],
+ responses: { "200": { description: "ok" } },
+ },
+ },
+ },
+ }
+ const c = await importDoc(doc)
+ const body =
+ (
+ c.requests[0] as {
+ body?: {
+ contentType?: string
+ body?: Array<{ key: string; isFile: boolean }>
+ }
+ }
+ )?.body ?? {}
+ expect(body.contentType).toBe("multipart/form-data")
+ if (Array.isArray(body.body)) {
+ const avatar = body.body.find((e) => e.key === "avatar")
+ expect(avatar?.isFile).toBe(true)
+ }
+ })
+})
diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/openapi.ts b/packages/hoppscotch-common/src/helpers/import-export/export/openapi.ts
new file mode 100644
index 000000000..8532b6240
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/import-export/export/openapi.ts
@@ -0,0 +1,1021 @@
+import {
+ HoppCollection,
+ HoppRESTRequest,
+ makeCollection,
+ parseRawKeyValueEntries,
+} from "@hoppscotch/data"
+import { OpenAPIV3_1 } from "openapi-types"
+
+type AuthLike = HoppRESTRequest["auth"]
+
+/**
+ * OpenAPI 3.1 PathItem permits only this fixed set of HTTP method keys.
+ * Anything else makes the document invalid and must be skipped.
+ */
+const OPENAPI_METHODS = new Set([
+ "get",
+ "put",
+ "post",
+ "delete",
+ "options",
+ "head",
+ "patch",
+ "trace",
+])
+
+/**
+ * OpenAPI 3.1 §4.8.14: Content-Type, Accept, and Authorization
+ * are expressed via requestBody/responses/security, not header parameters.
+ */
+const SKIP_HEADER_NAMES = new Set(["content-type", "accept", "authorization"])
+
+/**
+ * Convert Hoppscotch template variables `<<var>>` to OpenAPI path parameters `{var}`
+ */
+function convertTemplateVars(path: string): string {
+ return path.replace(/<<([a-zA-Z0-9_.-]+)>>/g, "{$1}")
+}
+
+/**
+ * Extract base URL, path, and any URL-embedded query params from an endpoint.
+ * Template vars are converted to `{var}` before parsing so the WHATWG parser
+ * only encodes ASCII braces; we decode just those pairs back, preserving any
+ * other percent-encoding the user placed intentionally (e.g. `%2F`).
+ */
+function parseEndpoint(endpoint: string): {
+ server: string
+ path: string
+ queryParams: Array<{ key: string; value: string }>
+} {
+ let converted = convertTemplateVars(endpoint)
+
+ // Protocol-relative URL (`//host/path`) — `new URL` would reject it.
+ // Default to https so it still emits a valid server + path pair.
+ if (converted.startsWith("//") && !converted.startsWith("///")) {
+ converted = `https:${converted}`
+ }
+
+ try {
+ const url = new URL(converted)
+ const server = `${url.protocol}//${url.host}`
+ // `new URL` already strips the fragment from `pathname`, so no extra work
+ // is needed for absolute URLs.
+ const path = url.pathname.replace(/%7B/gi, "{").replace(/%7D/gi, "}") || "/"
+ const queryParams: Array<{ key: string; value: string }> = []
+ for (const [key, value] of url.searchParams) {
+ queryParams.push({ key, value })
+ }
+ return { server, path, queryParams }
+ } catch {
+ // Not a valid absolute URL — strip any fragment and query string so they
+ // don't end up inside the OpenAPI path key.
+ let raw = converted
+ const fragIdx = raw.indexOf("#")
+ if (fragIdx >= 0) raw = raw.slice(0, fragIdx)
+
+ const queryParams: Array<{ key: string; value: string }> = []
+ const queryIdx = raw.indexOf("?")
+ if (queryIdx >= 0) {
+ const queryStr = raw.slice(queryIdx + 1)
+ raw = raw.slice(0, queryIdx)
+ try {
+ for (const [key, value] of new URLSearchParams(queryStr)) {
+ queryParams.push({ key, value })
+ }
+ } catch {
+ // ignore malformed query string
+ }
+ }
+
+ // A Hoppscotch endpoint that starts with a template variable like
+ // `<<baseUrl>>/pets` is the convention for "use the env-provided host."
+ // After convertTemplateVars that leading variable is `{baseUrl}`. Split
+ // it off as the server (in original `<<var>>` syntax for round-trip
+ // through the importer) so it doesn't end up inside the OpenAPI path key,
+ // which would cause `<<baseUrl>>/<<baseUrl>>/pets` doubling on reimport.
+ const leadingVarMatch = /^\{([a-zA-Z0-9_.-]+)\}(.*)$/.exec(raw)
+ if (leadingVarMatch) {
+ const varName = leadingVarMatch[1]
+ const rest = leadingVarMatch[2] || ""
+ const pathPart = rest.startsWith("/") ? rest : rest ? `/${rest}` : "/"
+ return { server: `<<${varName}>>`, path: pathPart, queryParams }
+ }
+
+ const pathRaw = raw.startsWith("/") ? raw : `/${raw}`
+ return { server: "", path: pathRaw, queryParams }
+ }
+}
+
+/**
+ * Resolve effective auth by walking parent inheritance: a request/folder with
+ * `authType: "inherit"` adopts its nearest non-inherit ancestor; an explicit
+ * `none/basic/...` overrides regardless of what the ancestor specifies.
+ */
+function resolveEffectiveAuth(
+ ownAuth: AuthLike,
+ inheritedAuth: AuthLike | null
+): AuthLike | null {
+ if (ownAuth.authType === "inherit") return inheritedAuth
+ return ownAuth
+}
+
+/**
+ * Compare two auths for OpenAPI export equivalence — would they emit the same
+ * security scheme? Lets the exporter skip per-operation security when it would
+ * duplicate the doc-level default. Credential values are not compared.
+ */
+function authsMatchForOpenAPI(a: AuthLike | null, b: AuthLike | null): boolean {
+ const aActive = a?.authActive === true
+ const bActive = b?.authActive === true
+ if (!aActive && !bActive) return true
+ if (aActive !== bActive) return false
+ // Both active here.
+ if (a!.authType === "none" && b!.authType === "none") return true
+ if (a!.authType !== b!.authType) return false
+ // Same type — for OpenAPI emission what matters is the resulting scheme
+ // identity AND the requested scopes (OAuth2 ops with different scopes
+ // are distinct security requirements even when sharing a scheme).
+ const aResult = convertAuth(a as HoppRESTRequest["auth"])
+ const bResult = convertAuth(b as HoppRESTRequest["auth"])
+ if (aResult?.schemeName !== bResult?.schemeName) return false
+ const aScopes = [...(aResult?.scopes ?? [])].sort().join(" ")
+ const bScopes = [...(bResult?.scopes ?? [])].sort().join(" ")
+ return aScopes === bScopes
+}
+
+/**
+ * Create a safe operationId from a request name
+ */
+function sanitizeOperationId(name: string): string {
+ return name
+ .replace(/[^a-zA-Z0-9_\s-]/g, "")
+ .replace(/\s+/g, "_")
+ .replace(/-+/g, "_")
+}
+
+/**
+ * Parse a space-separated scopes string into an OpenAPI scopes object.
+ * Filters out empty/whitespace-only entries.
+ */
+function parseScopes(scopes: string | undefined): Record<string, string> {
+ if (!scopes) return {}
+ const entries = scopes
+ .split(" ")
+ .filter((s) => s.length > 0)
+ .map((s) => [s, ""] as const)
+ return Object.fromEntries(entries)
+}
+
+/**
+ * Convert request body to OpenAPI requestBody
+ */
+function convertBody(
+ body: HoppRESTRequest["body"]
+): OpenAPIV3_1.RequestBodyObject | undefined {
+ if (!body || body.contentType === null) return undefined
+
+ if (body.contentType === "multipart/form-data") {
+ const properties: Record<string, OpenAPIV3_1.SchemaObject> = {}
+ const bodyEntries = Array.isArray(body.body) ? body.body : []
+
+ for (const entry of bodyEntries) {
+ if (!entry.active || !entry.key) continue
+ properties[entry.key] = entry.isFile
+ ? { type: "string", format: "binary" }
+ : { type: "string", example: entry.value }
+ }
+
+ // Skip emission when there are no active entries — an empty `properties`
+ // object produces an OpenAPI media object that some validators reject and
+ // misleads importers into creating an empty multipart body.
+ if (Object.keys(properties).length === 0) return undefined
+
+ return {
+ content: {
+ "multipart/form-data": {
+ schema: {
+ type: "object",
+ properties,
+ },
+ },
+ },
+ }
+ }
+
+ if (body.contentType === "application/x-www-form-urlencoded") {
+ // Hoppscotch persists urlencoded bodies in RawKeyValue format (`key:
+ // value` per line, possibly JSON-quoted), not in querystring form, so
+ // parse with the same helper the runtime uses in getFinalBodyFromRequest.
+ const bodyStr = typeof body.body === "string" ? body.body : ""
+ const properties: Record<string, OpenAPIV3_1.SchemaObject> = {}
+
+ for (const entry of parseRawKeyValueEntries(bodyStr)) {
+ if (!entry.active || !entry.key) continue
+ properties[entry.key] = { type: "string", example: entry.value }
+ }
+
+ if (Object.keys(properties).length === 0) return undefined
+
+ return {
+ content: {
+ "application/x-www-form-urlencoded": {
+ schema: {
+ type: "object",
+ properties,
+ },
+ },
+ },
+ }
+ }
+
+ if (body.contentType === "application/octet-stream") {
+ const mediaTypeObj: OpenAPIV3_1.MediaTypeObject = {
+ schema: {
+ type: "string",
+ format: "binary",
+ },
+ }
+ // Hopp's schema permits octet-stream body to be `File | null`, but users
+ // occasionally save a string snapshot. Surface it as an example rather
+ // than silently discarding the data.
+ if (typeof body.body === "string" && body.body.length > 0) {
+ mediaTypeObj.example = body.body
+ }
+ return {
+ content: {
+ "application/octet-stream": mediaTypeObj,
+ },
+ }
+ }
+
+ // Text-based content types (JSON, XML, HTML, plain text, etc.)
+ const bodyStr = typeof body.body === "string" ? body.body : ""
+
+ const mediaTypeObj: OpenAPIV3_1.MediaTypeObject = {}
+ if (bodyStr) {
+ if (body.contentType.includes("json")) {
+ try {
+ mediaTypeObj.example = JSON.parse(bodyStr)
+ } catch {
+ mediaTypeObj.example = bodyStr
+ }
+ } else {
+ mediaTypeObj.example = bodyStr
+ }
+ }
+
+ return {
+ content: {
+ [body.contentType]: mediaTypeObj,
+ },
+ }
+}
+
+/**
+ * Convert request auth to an OpenAPI security scheme entry.
+ * Returns { schemeName, schemeObject, securityRequirement } or null if auth should be skipped.
+ */
+function convertAuth(auth: HoppRESTRequest["auth"]): {
+ schemeName: string
+ scheme: OpenAPIV3_1.SecuritySchemeObject
+ scopes: string[]
+} | null {
+ if (!auth.authActive) return null
+
+ switch (auth.authType) {
+ case "basic":
+ return {
+ schemeName: "basicAuth",
+ scheme: { type: "http", scheme: "basic" },
+ scopes: [],
+ }
+ case "bearer":
+ return {
+ schemeName: "bearerAuth",
+ scheme: { type: "http", scheme: "bearer" },
+ scopes: [],
+ }
+ case "api-key": {
+ const addTo = auth.addTo === "QUERY_PARAMS" ? "query" : "header"
+ const sanitizedKey = (auth.key || "key")
+ .replace(/[^a-zA-Z0-9.\-_]/g, "_")
+ .replace(/_+/g, "_")
+ const name = `apiKey_${addTo}_${sanitizedKey}`
+ return {
+ schemeName: name,
+ scheme: {
+ type: "apiKey",
+ in: addTo,
+ name: auth.key || "api_key",
+ },
+ scopes: [],
+ }
+ }
+ case "jwt":
+ return {
+ schemeName: "jwtAuth",
+ scheme: { type: "http", scheme: "bearer", bearerFormat: "JWT" },
+ scopes: [],
+ }
+ case "digest":
+ return {
+ schemeName: "digestAuth",
+ scheme: { type: "http", scheme: "digest" },
+ scopes: [],
+ }
+ case "aws-signature":
+ return {
+ schemeName: "awsSigV4",
+ scheme: {
+ type: "apiKey",
+ in: "header",
+ name: "Authorization",
+ description: "AWS Signature Version 4",
+ },
+ scopes: [],
+ }
+ case "hawk":
+ return {
+ schemeName: "hawkAuth",
+ scheme: {
+ type: "apiKey",
+ in: "header",
+ name: "Authorization",
+ description: "Hawk authentication",
+ },
+ scopes: [],
+ }
+ case "akamai-eg":
+ return {
+ schemeName: "akamaiEdgeGrid",
+ scheme: {
+ type: "apiKey",
+ in: "header",
+ name: "Authorization",
+ description: "Akamai EdgeGrid authentication",
+ },
+ scopes: [],
+ }
+ case "oauth-2": {
+ const flows: OpenAPIV3_1.OAuthFlowsObject = {}
+ const grantInfo = auth.grantTypeInfo
+ const scopes = parseScopes(grantInfo.scopes)
+
+ // OpenAPI 3.1 §4.8.30 requires `tokenUrl`/`authorizationUrl` to be
+ // non-empty URLs for the corresponding flow object. Skip flows whose
+ // endpoint(s) are missing rather than emit invalid (empty-URL) flows.
+ switch (grantInfo.grantType) {
+ case "AUTHORIZATION_CODE":
+ if (grantInfo.authEndpoint && grantInfo.tokenEndpoint) {
+ flows.authorizationCode = {
+ authorizationUrl: grantInfo.authEndpoint,
+ tokenUrl: grantInfo.tokenEndpoint,
+ scopes,
+ }
+ }
+ break
+ case "CLIENT_CREDENTIALS":
+ if (grantInfo.authEndpoint) {
+ flows.clientCredentials = {
+ tokenUrl: grantInfo.authEndpoint,
+ scopes,
+ }
+ }
+ break
+ case "PASSWORD":
+ if (grantInfo.authEndpoint) {
+ flows.password = {
+ tokenUrl: grantInfo.authEndpoint,
+ scopes,
+ }
+ }
+ break
+ case "IMPLICIT":
+ if (grantInfo.authEndpoint) {
+ flows.implicit = {
+ authorizationUrl: grantInfo.authEndpoint,
+ scopes,
+ }
+ }
+ break
+ }
+
+ // If no flow could be emitted, the resulting securityScheme would be
+ // `{ type: "oauth2", flows: {} }` — invalid per spec. Return null and
+ // let the caller flag it as unsupported (lossy).
+ if (Object.keys(flows).length === 0) return null
+
+ const scopeKeys = Object.keys(scopes)
+ return {
+ schemeName: "oauth2",
+ scheme: { type: "oauth2", flows },
+ scopes: scopeKeys,
+ }
+ }
+ default:
+ return null
+ }
+}
+
+/**
+ * Register a security scheme and return the name it was registered under.
+ * OAuth2 schemes merge flows by grant type and union scopes within a matching
+ * flow. Non-OAuth2 schemes reuse the name when identical, or get a numeric
+ * suffix when differing — never silently overwritten.
+ */
+function registerSecurityScheme(
+ securitySchemes: Record<string, OpenAPIV3_1.SecuritySchemeObject>,
+ schemeName: string,
+ scheme: OpenAPIV3_1.SecuritySchemeObject
+): string {
+ const existing = securitySchemes[schemeName]
+
+ if (!existing) {
+ securitySchemes[schemeName] = scheme
+ return schemeName
+ }
+
+ if (existing.type === "oauth2" && scheme.type === "oauth2") {
+ type MergeableFlow = {
+ authorizationUrl?: string
+ tokenUrl?: string
+ refreshUrl?: string
+ scopes: Record<string, string>
+ }
+ const existingFlows = existing.flows as Record<string, MergeableFlow>
+ const newFlows = scheme.flows as Record<string, MergeableFlow>
+
+ for (const [flowType, newFlow] of Object.entries(newFlows)) {
+ const existingFlow = existingFlows[flowType]
+ if (!existingFlow) {
+ existingFlows[flowType] = newFlow
+ continue
+ }
+ existingFlow.scopes = { ...existingFlow.scopes, ...newFlow.scopes }
+ }
+
+ return schemeName
+ }
+
+ // Non-OAuth2: identical schemes share a name; differing schemes get suffixed.
+ const equalSchemes = (a: unknown, b: unknown) =>
+ JSON.stringify(a) === JSON.stringify(b)
+
+ if (equalSchemes(existing, scheme)) {
+ return schemeName
+ }
+
+ let counter = 2
+ for (;;) {
+ const candidate = `${schemeName}_${counter}`
+ const candidateExisting = securitySchemes[candidate]
+ if (!candidateExisting) {
+ securitySchemes[candidate] = scheme
+ return candidate
+ }
+ if (equalSchemes(candidateExisting, scheme)) {
+ return candidate
+ }
+ counter++
+ }
+}
+
+/**
+ * Convert saved responses from a request to OpenAPI response objects
+ */
+function convertResponses(
+ responses: HoppRESTRequest["responses"]
+): OpenAPIV3_1.ResponsesObject {
+ if (!responses || Object.keys(responses).length === 0) {
+ return { "200": { description: "Successful response" } }
+ }
+
+ const result: OpenAPIV3_1.ResponsesObject = {}
+
+ for (const [, response] of Object.entries(responses)) {
+ // OpenAPI's `responses` map is keyed by HTTP status code; a saved
+ // response without a code can't be addressed and is ambiguous, skip it.
+ if (response.code == null) continue
+ const statusCode = response.code.toString()
+
+ const responseObj: OpenAPIV3_1.ResponseObject = {
+ description: response.name?.trim() || `${statusCode} response`,
+ }
+
+ if (response.headers && response.headers.length > 0) {
+ responseObj.headers = {}
+ for (const header of response.headers) {
+ if (!header.key) continue
+ // OpenAPI 3.1 §4.8.17: Content-Type is expressed via the content map key
+ if (header.key.toLowerCase() === "content-type") continue
+ responseObj.headers[header.key] = {
+ schema: { type: "string" },
+ example: header.value,
+ }
+ }
+ if (Object.keys(responseObj.headers).length === 0) {
+ delete responseObj.headers
+ }
+ }
+
+ if (response.body) {
+ // Try to detect content type from response headers
+ const contentTypeHeader = response.headers?.find(
+ (h) => h.key.toLowerCase() === "content-type"
+ )
+ const contentType =
+ contentTypeHeader?.value?.split(";")[0].trim() || "application/json"
+
+ const mediaType: OpenAPIV3_1.MediaTypeObject = {}
+ if (contentType.includes("json")) {
+ try {
+ mediaType.example = JSON.parse(response.body)
+ } catch {
+ mediaType.example = response.body
+ }
+ } else {
+ mediaType.example = response.body
+ }
+
+ responseObj.content = { [contentType]: mediaType }
+ }
+
+ result[statusCode] = responseObj
+ }
+
+ // OpenAPI 3.1 §4.8.10.1 requires at least one entry — if every saved
+ // response was skipped (all had null codes), fall back to the default.
+ if (Object.keys(result).length === 0) {
+ return { "200": { description: "Successful response" } }
+ }
+ return result
+}
+
+/**
+ * Convert a HoppCollection to an OpenAPI 3.1.0 document.
+ */
+export function hoppCollectionToOpenAPI(collection: HoppCollection): {
+ doc: OpenAPIV3_1.Document
+} {
+ const paths: OpenAPIV3_1.PathsObject = {}
+ const tags: OpenAPIV3_1.TagObject[] = []
+ const usedTagNames = new Set<string>()
+ const securitySchemes: Record<string, OpenAPIV3_1.SecuritySchemeObject> = {}
+ const servers = new Set<string>()
+ const usedOperationIds = new Set<string>()
+
+ /**
+ * Resolve a `<<varName>>` server placeholder to the variable's actual value
+ * if one is in scope. Defensive: skips variables flagged `secret` so we
+ * don't leak credentials into an exported spec.
+ */
+ const resolveServerPlaceholder = (
+ server: string,
+ variableValues: Map<string, string>
+ ): string => {
+ const match = /^<<([a-zA-Z0-9_.-]+)>>$/.exec(server)
+ if (!match) return server
+ const value = variableValues.get(match[1])
+ return value && value.length > 0 ? value : server
+ }
+
+ /**
+ * Build the effective variable map for the current scope by walking ancestor
+ * variable arrays from root → leaf, with deeper levels overriding shallower.
+ * Secret variables are excluded so resolveServerPlaceholder never substitutes
+ * them into the doc.
+ */
+ const buildVariableValues = (
+ variableLayers: ReadonlyArray<HoppCollection["variables"]>
+ ): Map<string, string> => {
+ const result = new Map<string, string>()
+ for (const layer of variableLayers) {
+ for (const v of layer) {
+ if ((v as { secret?: boolean }).secret) continue
+ const value =
+ (v as { currentValue?: string }).currentValue ||
+ (v as { initialValue?: string }).initialValue ||
+ ""
+ if (value) result.set(v.key, value)
+ }
+ }
+ return result
+ }
+
+ /** Collect the keys of every secret variable in scope (any layer). */
+ const collectSecretKeys = (
+ variableLayers: ReadonlyArray<HoppCollection["variables"]>
+ ): Set<string> => {
+ const result = new Set<string>()
+ for (const layer of variableLayers) {
+ for (const v of layer) {
+ if ((v as { secret?: boolean }).secret) result.add(v.key)
+ }
+ }
+ return result
+ }
+
+ /**
+ * Substitute `<<var>>` tokens in a value with their resolved (non-secret)
+ * values. Returns `undefined` if any secret variable appears in the string —
+ * the param's `example` field should be omitted entirely rather than leak
+ * a credential placeholder into the exported spec.
+ */
+ const resolveExampleValue = (
+ value: string | undefined,
+ variableValues: Map<string, string>,
+ secretKeys: Set<string>
+ ): string | undefined => {
+ if (!value) return undefined
+ let containsSecret = false
+ const out = value.replace(/<<([a-zA-Z0-9_.-]+)>>/g, (_match, name) => {
+ if (secretKeys.has(name)) {
+ containsSecret = true
+ return ""
+ }
+ return variableValues.get(name) ?? `<<${name}>>`
+ })
+ if (containsSecret) return undefined
+ return out
+ }
+
+ function processRequests(
+ requests: HoppRESTRequest[],
+ tagPath: string | null,
+ inheritedHeaders: HoppCollection["headers"][],
+ inheritedAuth: AuthLike | null,
+ inheritedVariables: ReadonlyArray<HoppCollection["variables"]>,
+ docLevelAuth: AuthLike | null
+ ) {
+ const variableValues = buildVariableValues(inheritedVariables)
+ const secretKeys = collectSecretKeys(inheritedVariables)
+ for (const request of requests) {
+ const {
+ server,
+ path: rawPath,
+ queryParams: urlQueryParams,
+ } = parseEndpoint(request.endpoint)
+ const method = request.method.toLowerCase()
+
+ // Substitute non-secret runtime variables that landed inside the path
+ // (e.g. `<<env>>/api/<<region>>/users` -> `/prod/api/us-east-1/users`).
+ // True path templates — vars listed in `requestVariables` — are kept
+ // as `{name}` so they round-trip and remain consumer-supplied. Secret
+ // vars are also kept as templates rather than substituted to avoid
+ // leaking credentials into the spec.
+ const requestVarKeys = new Set(
+ request.requestVariables
+ .filter((v) => v.active && v.key)
+ .map((v) => v.key)
+ )
+ const path = rawPath.replace(
+ /\{([a-zA-Z0-9_.-]+)\}/g,
+ (token, name: string) => {
+ if (requestVarKeys.has(name)) return token
+ if (secretKeys.has(name)) return token
+ const resolved = variableValues.get(name)
+ return resolved !== undefined ? resolved : token
+ }
+ )
+
+ // Skip methods OpenAPI 3.1 doesn't recognize as PathItem keys —
+ // emitting them would produce an invalid document.
+ if (!OPENAPI_METHODS.has(method)) continue
+
+ // Skip duplicate (path, method) — OpenAPI cannot represent two
+ // operations with the same key. Keep the first seen; drop the rest.
+ const pathItem = (paths[path] = (paths[path] ??
+ {}) as OpenAPIV3_1.PathItemObject) as Record<
+ string,
+ OpenAPIV3_1.OperationObject
+ >
+ if (pathItem[method]) continue
+
+ if (server) servers.add(resolveServerPlaceholder(server, variableValues))
+
+ const parameters: OpenAPIV3_1.ParameterObject[] = []
+ // OpenAPI requires unique (name, in) per operation — dedupe as we go,
+ // first-write wins (mirrors the existing "child-overrides-parent" rule
+ // for inherited headers).
+ const seenParamKeys = new Set<string>()
+ const pushParam = (param: OpenAPIV3_1.ParameterObject) => {
+ const key = `${param.in}::${param.name.toLowerCase()}`
+ if (seenParamKeys.has(key)) return
+ seenParamKeys.add(key)
+ parameters.push(param)
+ }
+
+ // Explicit request-level query params first (so they take precedence
+ // over duplicates encoded in the URL itself).
+ for (const param of request.params) {
+ if (!param.active || !param.key) continue
+ pushParam({
+ name: param.key,
+ in: "query",
+ schema: { type: "string" },
+ example: resolveExampleValue(param.value, variableValues, secretKeys),
+ description: param.description || undefined,
+ })
+ }
+
+ // Query params embedded in the endpoint URL itself.
+ for (const { key, value } of urlQueryParams) {
+ if (!key) continue
+ pushParam({
+ name: key,
+ in: "query",
+ schema: { type: "string" },
+ example: resolveExampleValue(value, variableValues, secretKeys),
+ })
+ }
+
+ // Request-level headers
+ for (const header of request.headers) {
+ if (!header.active || !header.key) continue
+ if (SKIP_HEADER_NAMES.has(header.key.toLowerCase())) continue
+ pushParam({
+ name: header.key,
+ in: "header",
+ schema: { type: "string" },
+ example: resolveExampleValue(
+ header.value,
+ variableValues,
+ secretKeys
+ ),
+ description: header.description || undefined,
+ })
+ }
+
+ // Inherited headers (nearest ancestor first; first-write-wins via dedup)
+ for (const headers of inheritedHeaders) {
+ for (const header of headers) {
+ if (!header.active || !header.key) continue
+ if (SKIP_HEADER_NAMES.has(header.key.toLowerCase())) continue
+ pushParam({
+ name: header.key,
+ in: "header",
+ schema: { type: "string" },
+ example: resolveExampleValue(
+ header.value,
+ variableValues,
+ secretKeys
+ ),
+ description: header.description || undefined,
+ })
+ }
+ }
+
+ // Path variables from requestVariables
+ const definedPathParams = new Set<string>()
+ for (const variable of request.requestVariables) {
+ if (!variable.active || !variable.key) continue
+ definedPathParams.add(variable.key)
+ pushParam({
+ name: variable.key,
+ in: "path",
+ required: true,
+ schema: { type: "string" },
+ example: resolveExampleValue(
+ variable.value,
+ variableValues,
+ secretKeys
+ ),
+ })
+ }
+
+ // Auto-generate path params for any {var} in the path not already defined
+ const pathParamMatches = path.matchAll(/\{([a-zA-Z0-9_.-]+)\}/g)
+ for (const match of pathParamMatches) {
+ const paramName = match[1]
+ if (definedPathParams.has(paramName)) continue
+ definedPathParams.add(paramName)
+ pushParam({
+ name: paramName,
+ in: "path",
+ required: true,
+ schema: { type: "string" },
+ })
+ }
+
+ const operation: OpenAPIV3_1.OperationObject = {
+ summary: request.name,
+ responses: convertResponses(request.responses),
+ }
+
+ if (request.description) {
+ operation.description = request.description
+ }
+
+ let operationId =
+ sanitizeOperationId(request.name) ||
+ `${method}_${path.replace(/[^a-zA-Z0-9]/g, "_").replace(/^_+|_+$/g, "")}`
+ if (usedOperationIds.has(operationId)) {
+ let counter = 2
+ while (usedOperationIds.has(`${operationId}_${counter}`)) {
+ counter++
+ }
+ operationId = `${operationId}_${counter}`
+ }
+ usedOperationIds.add(operationId)
+ operation.operationId = operationId
+
+ if (tagPath) {
+ operation.tags = [tagPath]
+ }
+
+ if (parameters.length > 0) {
+ operation.parameters = parameters
+ }
+
+ const requestBody = convertBody(request.body)
+ if (requestBody) {
+ operation.requestBody = requestBody
+ }
+
+ // Effective auth = nearest non-inherit ancestor (or own auth if explicit).
+ // Folder/collection auth is now respected via inheritedAuth.
+ const effectiveAuth = resolveEffectiveAuth(request.auth, inheritedAuth)
+ // Only emit `operation.security` when the request's effective auth
+ // *differs* from the doc-level auth. If they match, OpenAPI's natural
+ // inheritance from `doc.security` covers it — and skipping the emit
+ // is what makes round-tripping `request.auth = inherit` come back as
+ // `inherit` rather than as a duplicated copy on every request.
+ if (
+ effectiveAuth?.authActive &&
+ !authsMatchForOpenAPI(effectiveAuth, docLevelAuth)
+ ) {
+ if (effectiveAuth.authType === "none") {
+ operation.security = []
+ } else {
+ const authResult = convertAuth(effectiveAuth)
+ if (authResult) {
+ const name = registerSecurityScheme(
+ securitySchemes,
+ authResult.schemeName,
+ authResult.scheme
+ )
+ operation.security = [{ [name]: authResult.scopes }]
+ }
+ }
+ } else if (
+ // Special case: collection has auth but this request's effective auth
+ // is explicitly disabled (`authActive: false`) — either on the request
+ // itself or via a folder ancestor that opts out. Emit `[]` so the
+ // operation is exempted from doc.security at runtime.
+ docLevelAuth?.authActive &&
+ effectiveAuth &&
+ !effectiveAuth.authActive &&
+ effectiveAuth.authType !== "inherit"
+ ) {
+ operation.security = []
+ }
+
+ pathItem[method] = operation
+ }
+ }
+
+ function processFolders(
+ folders: HoppCollection[],
+ parentPath: string | null,
+ inheritedHeaders: HoppCollection["headers"][],
+ inheritedAuth: AuthLike | null,
+ inheritedVariables: ReadonlyArray<HoppCollection["variables"]>,
+ docLevelAuth: AuthLike | null
+ ) {
+ for (const folder of folders) {
+ const tagPath = parentPath ? `${parentPath}/${folder.name}` : folder.name
+ const folderHeaders = [folder.headers, ...inheritedHeaders]
+ const folderAuth = resolveEffectiveAuth(
+ folder.auth as AuthLike,
+ inheritedAuth
+ )
+ const folderVariables = [...inheritedVariables, folder.variables]
+
+ if (!usedTagNames.has(tagPath)) {
+ usedTagNames.add(tagPath)
+ const tag: OpenAPIV3_1.TagObject = { name: tagPath }
+ if (folder.description) tag.description = folder.description
+ tags.push(tag)
+ }
+
+ processRequests(
+ folder.requests as HoppRESTRequest[],
+ tagPath,
+ folderHeaders,
+ folderAuth,
+ folderVariables,
+ docLevelAuth
+ )
+ processFolders(
+ folder.folders,
+ tagPath,
+ folderHeaders,
+ folderAuth,
+ folderVariables,
+ docLevelAuth
+ )
+ }
+ }
+
+ const rootHeaders = [collection.headers]
+ const collectionAuthAsRequest = collection.auth as AuthLike
+ // Root inheritance: a top-level "inherit" has no parent, so treat as no auth.
+ const rootInheritedAuth: AuthLike | null =
+ collectionAuthAsRequest.authType === "inherit"
+ ? null
+ : collectionAuthAsRequest
+
+ const rootVariables: ReadonlyArray<HoppCollection["variables"]> = [
+ collection.variables,
+ ]
+ // The "doc-level auth" is what the importer will set as collection.auth,
+ // mirrored from `doc.security`. Operations whose effective auth matches it
+ // can omit `operation.security` and let OpenAPI's inheritance kick in.
+ const docLevelAuth: AuthLike | null = rootInheritedAuth?.authActive
+ ? rootInheritedAuth
+ : null
+
+ processRequests(
+ collection.requests as HoppRESTRequest[],
+ null,
+ rootHeaders,
+ rootInheritedAuth,
+ rootVariables,
+ docLevelAuth
+ )
+ processFolders(
+ collection.folders,
+ null,
+ rootHeaders,
+ rootInheritedAuth,
+ rootVariables,
+ docLevelAuth
+ )
+
+ const doc: OpenAPIV3_1.Document = {
+ openapi: "3.1.0",
+ info: {
+ title: collection.name,
+ description: collection.description ?? undefined,
+ version: "1.0.0",
+ },
+ paths,
+ }
+
+ if (servers.size > 0) {
+ doc.servers = Array.from(servers).map((url) => ({ url }))
+ }
+
+ if (tags.length > 0) {
+ doc.tags = tags
+ // Mark the document so the importer knows tag names use slash-as-folder
+ // separator. Round-trip stays exact even when there's only a single
+ // nested folder (which the heuristic alone couldn't detect).
+ ;(doc as Record<string, unknown>)["x-hoppscotch-folder-tags"] = "slash"
+ }
+
+ // Collection-level auth → global security (only when explicit and non-none)
+ if (rootInheritedAuth?.authActive) {
+ if (rootInheritedAuth.authType !== "none") {
+ const collectionAuth = convertAuth(rootInheritedAuth)
+ if (collectionAuth) {
+ const name = registerSecurityScheme(
+ securitySchemes,
+ collectionAuth.schemeName,
+ collectionAuth.scheme
+ )
+ doc.security = [{ [name]: collectionAuth.scopes }]
+ }
+ }
+ }
+
+ if (Object.keys(securitySchemes).length > 0) {
+ doc.components = { securitySchemes }
+ }
+
+ return { doc }
+}
+
+/**
+ * Wrap multiple top-level collections into a single OpenAPI 3.1 document.
+ * Each becomes a top-level folder of a synthetic root, so the tag tree mirrors
+ * the workspace and remains round-trippable. (method, path) collisions across
+ * collections are dropped — already warned upfront by the chooser modal.
+ */
+export function hoppCollectionsToOpenAPI(
+ workspaceName: string,
+ collections: HoppCollection[]
+): { doc: OpenAPIV3_1.Document } {
+ const root = makeCollection({
+ name: workspaceName,
+ folders: collections,
+ requests: [],
+ auth: { authType: "inherit", authActive: true },
+ headers: [],
+ variables: [],
+ description: null,
+ preRequestScript: "",
+ testScript: "",
+ })
+ return hoppCollectionToOpenAPI(root)
+}
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.ts
index 001ea7dea..12386797d 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
@@ -127,9 +127,14 @@ const getOpenAPIOperationName = (info: OpenAPIOperationType): string => {
? info.title
: undefined
+ // OpenAPI semantics: `summary` is the short human-readable name shown in
+ // tools like Swagger UI; `operationId` is a machine identifier (no spaces,
+ // typically code-gen-friendly). Prefer the human-readable one for the
+ // Hoppscotch request name; fall back to operationId only if summary is
+ // missing. Otherwise round-tripping turns "Get Pet" into "Get_Pet".
const candidates: Array<string | undefined> = [
- info.operationId,
info.summary,
+ info.operationId,
title,
]
@@ -151,6 +156,66 @@ const replaceOpenApiPathTemplating = flow(
S.replace(/}/g, ">>")
)
+/**
+ * Read an example/default value off an OpenAPI param-like object and return
+ * it as a string. Used by query/header/path parsers so values round-trip.
+ *
+ * Sources tried, in order:
+ * - `example` (OpenAPI 3.x — what our exporter writes)
+ * - first entry of `examples` (OpenAPI 3.x alternative)
+ * - `x-example` (common Swagger 2.0 extension)
+ * - `default` (Swagger 2.0 — `default` carries the example value, while
+ * OpenAPI 3.x reserves it for schema defaults; v2 docs in the wild
+ * overwhelmingly use `default` for both)
+ * - `schema.default` (OpenAPI 3.x schema-level default)
+ */
+const readParamExampleAsString = (param: unknown): string => {
+ if (typeof param !== "object" || param === null) return ""
+ const p = param as {
+ example?: unknown
+ examples?: unknown
+ "x-example"?: unknown
+ default?: unknown
+ schema?: { default?: unknown }
+ }
+ // Strings pass through; objects/arrays are JSON-encoded so callers see the
+ // structured shape rather than `[object Object]`. Numbers/booleans use
+ // `String(...)` for their natural literal form.
+ const stringify = (v: unknown): string => {
+ if (typeof v === "string") return v
+ if (typeof v === "object" && v !== null) {
+ try {
+ return JSON.stringify(v)
+ } catch {
+ return String(v)
+ }
+ }
+ return String(v)
+ }
+
+ if (p.example !== undefined && p.example !== null) return stringify(p.example)
+
+ if (p.examples && typeof p.examples === "object") {
+ const first = Object.values(p.examples as Record<string, unknown>)[0]
+ if (first && typeof first === "object") {
+ const v = (first as { value?: unknown }).value
+ if (v !== undefined && v !== null) return stringify(v)
+ }
+ }
+
+ if (p["x-example"] !== undefined && p["x-example"] !== null) {
+ return stringify(p["x-example"])
+ }
+
+ if (p.default !== undefined && p.default !== null) return stringify(p.default)
+
+ if (p.schema?.default !== undefined && p.schema?.default !== null) {
+ return stringify(p.schema.default)
+ }
+
+ return ""
+}
+
const parseOpenAPIParams = (params: OpenAPIParamsType[]): HoppRESTParam[] =>
pipe(
params,
@@ -162,7 +227,7 @@ const parseOpenAPIParams = (params: OpenAPIParamsType[]): HoppRESTParam[] =>
(param) =>
<HoppRESTParam>{
key: param.name,
- value: "", // TODO: Can we do anything more ? (parse default values maybe)
+ value: readParamExampleAsString(param),
active: true,
description: param.description ?? "",
}
@@ -184,7 +249,7 @@ const parseOpenAPIVariables = (
(param) =>
<HoppRESTRequestVariable>{
key: param.name,
- value: "", // TODO: Can we do anything more ? (parse default values maybe)
+ value: readParamExampleAsString(param),
active: true,
}
)
@@ -412,7 +477,7 @@ const parseOpenAPIHeaders = (params: OpenAPIParamsType[]): HoppRESTHeader[] =>
O.map((header) => {
return <HoppRESTParam>{
key: header.name,
- value: "", // TODO: Can we do anything more ? (parse default values maybe)
+ value: readParamExampleAsString(header),
active: true,
description: header.description ?? "",
}
@@ -439,15 +504,21 @@ const parseOpenAPIV2Body = (op: OpenAPIV2.OperationObject): HoppRESTReqBody => {
A.filterMap(
flow(
O.fromPredicate((param) => param.in === "formData"),
- O.map(
- (param) =>
- <FormDataKeyValue>{
- key: param.name,
- isFile: param.type === "file",
- value: "",
- active: true,
- }
- )
+ O.map((param) => {
+ const isFile = param.type === "file"
+ // Files don't carry a default text value; for non-file fields,
+ // pull `default`/`example`/`x-example` so values round-trip.
+ // FormDataKeyValue's discriminated union requires `Blob[]` when
+ // `isFile: true` and `string` when `false`.
+ return <FormDataKeyValue>(isFile
+ ? { key: param.name, isFile: true, value: [], active: true }
+ : {
+ key: param.name,
+ isFile: false,
+ value: readParamExampleAsString(param),
+ active: true,
+ })
+ })
)
)
)
@@ -455,7 +526,9 @@ const parseOpenAPIV2Body = (op: OpenAPIV2.OperationObject): HoppRESTReqBody => {
return obj === "application/x-www-form-urlencoded"
? {
contentType: obj,
- body: formDataValues.map(({ key }) => `${key}: `).join("\n"),
+ body: formDataValues
+ .map(({ key, value }) => `${key}: ${value ?? ""}`)
+ .join("\n"),
}
: { contentType: obj, body: formDataValues }
}
@@ -494,19 +567,40 @@ const parseOpenAPIV3BodyFormData = (
: { contentType, body: [] }
}
- const keys = Object.keys(schema.properties ?? {})
+ const properties = (schema.properties ?? {}) as Record<
+ string,
+ { format?: string; example?: unknown }
+ >
+ const keys = Object.keys(properties)
if (contentType === "application/x-www-form-urlencoded") {
return {
contentType,
- body: keys.map((key) => `${key}: `).join("\n"),
+ body: keys
+ .map((key) => {
+ const value = readParamExampleAsString(properties[key])
+ return `${key}: ${value}`
+ })
+ .join("\n"),
}
}
return {
contentType,
- body: keys.map(
- (key) => <FormDataKeyValue>{ key, value: "", isFile: false, active: true }
- ),
+ body: keys.map((key) => {
+ const prop = properties[key]
+ const isFile = prop?.format === "binary"
+ // FormDataKeyValue requires `Blob[]` for files and `string` for others.
+ if (isFile) {
+ return <FormDataKeyValue>{ key, isFile: true, value: [], active: true }
+ }
+ const value = readParamExampleAsString(prop)
+ return <FormDataKeyValue>{
+ key,
+ isFile: false,
+ value,
+ active: true,
+ }
+ }),
}
}
@@ -541,6 +635,11 @@ const parseOpenAPIV3Body = (
)
return parseOpenAPIV3BodyFormData(contentType, media)
+ // Binary uploads have no string body; the schema requires `File | null`.
+ if (contentType === "application/octet-stream") {
+ return { contentType, body: null } as HoppRESTReqBody
+ }
+
// For other content types (JSON, XML, etc.), try to generate sample from schema
if (media.schema) {
try {
@@ -664,7 +763,7 @@ const resolveOpenAPIV3SecurityObj = (
authType: "api-key",
authActive: true,
addTo: "QUERY_PARAMS",
- key: scheme.in,
+ key: scheme.name,
value: "",
}
}
@@ -817,18 +916,49 @@ const resolveOpenAPIV3Security = (
return resolveOpenAPIV3SecurityScheme(doc, schemeName, schemeData)
}
+/**
+ * Per-operation auth resolution.
+ *
+ * Returns ONLY the override for a single operation:
+ * - `op.security` undefined → `inherit` (defer to collection-level)
+ * - `op.security = []` → `none, active` (explicit opt-out per
+ * OpenAPI 3.1 §4.8.10: "an empty array
+ * can be used [to remove] a top-level
+ * security declaration")
+ * - `op.security = [{schemeA: …}]` → resolve `schemeA`
+ *
+ * The doc-level fallback used to live here. It now lives in
+ * `parseCollectionLevelAuthV3` so the collection-vs-request distinction
+ * round-trips correctly.
+ */
const parseOpenAPIV3Auth = (
doc: OpenAPIV3.Document | OpenAPIV31.Document,
op: OpenAPIV3.OperationObject | OpenAPIV31.OperationObject
): HoppRESTAuth => {
- const rootAuth = doc.security
- ? resolveOpenAPIV3Security(doc, doc.security)
- : undefined
- const opAuth = op.security
- ? resolveOpenAPIV3Security(doc, op.security)
- : undefined
-
- return opAuth ?? rootAuth ?? { authType: "none", authActive: true }
+ if (op.security === undefined) {
+ return { authType: "inherit", authActive: true }
+ }
+ if (op.security.length === 0) {
+ return { authType: "none", authActive: true }
+ }
+ return resolveOpenAPIV3Security(doc, op.security)
+}
+
+/**
+ * Doc-level auth resolution. Mirrors the per-op logic but reads `doc.security`
+ * — gives the collection a single source of truth that all `inherit`-typed
+ * requests can defer to.
+ */
+const parseCollectionLevelAuthV3 = (
+ doc: OpenAPIV3.Document | OpenAPIV31.Document
+): HoppRESTAuth => {
+ if (doc.security === undefined) {
+ return { authType: "inherit", authActive: true }
+ }
+ if (doc.security.length === 0) {
+ return { authType: "none", authActive: true }
+ }
+ return resolveOpenAPIV3Security(doc, doc.security)
}
const resolveOpenAPIV2SecurityScheme = (
@@ -981,14 +1111,36 @@ const parseOpenAPIV2Auth = (
doc: OpenAPIV2.Document,
op: OpenAPIV2.OperationObject
): HoppRESTAuth => {
- const rootAuth = doc.security
- ? resolveOpenAPIV2Security(doc, doc.security)
- : undefined
- const opAuth = op.security
- ? resolveOpenAPIV2Security(doc, op.security)
- : undefined
-
- return opAuth ?? rootAuth ?? { authType: "none", authActive: true }
+ if (op.security === undefined) {
+ return { authType: "inherit", authActive: true }
+ }
+ if (op.security.length === 0) {
+ return { authType: "none", authActive: true }
+ }
+ return resolveOpenAPIV2Security(doc, op.security)
+}
+
+const parseCollectionLevelAuthV2 = (doc: OpenAPIV2.Document): HoppRESTAuth => {
+ if (doc.security === undefined) {
+ return { authType: "inherit", authActive: true }
+ }
+ if (doc.security.length === 0) {
+ return { authType: "none", authActive: true }
+ }
+ return resolveOpenAPIV2Security(doc, doc.security)
+}
+
+/**
+ * Resolves the doc-level (collection-level) auth from any supported OpenAPI
+ * version. Used once per imported document.
+ */
+const parseCollectionLevelAuth = (doc: OpenAPI.Document): HoppRESTAuth => {
+ if (objectHasProperty(doc, "swagger")) {
+ return parseCollectionLevelAuthV2(doc as OpenAPIV2.Document)
+ }
+ return parseCollectionLevelAuthV3(
+ doc as OpenAPIV3.Document | OpenAPIV31.Document
+ )
}
const parseOpenAPIAuth = (
@@ -999,36 +1151,65 @@ const parseOpenAPIAuth = (
? parseOpenAPIV3Auth(doc as OpenAPIV3.Document | OpenAPIV31.Document, op)
: parseOpenAPIV2Auth(doc as OpenAPIV2.Document, op)
+/**
+ * Resolve a doc-level base URL.
+ *
+ * Returns:
+ * - `prefix`: the string each endpoint is prefixed with. Always
+ * `<<baseUrl>>` (Hoppscotch's collection-variable convention) so users get
+ * a single place to edit the host instead of a hardcoded URL repeated
+ * across every request.
+ * - `baseUrlValue`: the resolved real URL if the doc declared one (so the
+ * importer can seed a `baseUrl` collection variable with it), or `null`
+ * if the doc had no `servers`/`host` to learn from.
+ */
const parseOpenAPIUrl = (
doc: OpenAPI.Document | OpenAPIV2.Document | OpenAPIV3.Document
-): string => {
- /**
- * OpenAPI V2 has version as a string in the document's swagger property.
- * And host and basePath are in the document's host and basePath properties.
- * Relevant v2 reference: https://swagger.io/specification/v2/#:~:text=to%20be%20obscured.-,Schema,-Swagger%20Object
- **/
+): { prefix: string; baseUrlValue: string | null } => {
+ const prefix = "<<baseUrl>>"
+ // OpenAPI V2 — host + basePath at the doc root, with `schemes` providing
+ // the protocol(s). Without a scheme prefix the value isn't a usable URL,
+ // so default to `https` (common practice for public APIs) when missing.
if (objectHasProperty(doc, "swagger")) {
- // TODO: dynamically add doc.host, doc.basePath value as variables in the environment if available. or notify user to add it.
- // add base url variable to each request
- const host = doc.host?.trim() || "<<baseUrl>>"
- const basePath = doc.basePath?.trim() || ""
- return `${host}${basePath}`
+ const host = doc.host?.trim() ?? ""
+ const basePath = doc.basePath?.trim() ?? ""
+ if (!host && !basePath) return { prefix, baseUrlValue: null }
+ if (!host) {
+ // `basePath` alone isn't a URL — fabricating `https://<basePath>`
+ // would produce a host like `https://v2`. Skip seeding a variable;
+ // instead append the basePath to the placeholder prefix so endpoints
+ // resolve as `<<baseUrl>>/<basePath>/...` once the user fills in the
+ // host themselves.
+ const normalisedBase = basePath.startsWith("/")
+ ? basePath
+ : `/${basePath}`
+ return { prefix: `${prefix}${normalisedBase}`, baseUrlValue: null }
+ }
+ const scheme = doc.schemes?.[0] ?? "https"
+ return {
+ prefix,
+ baseUrlValue: `${scheme}://${host}${basePath}`,
+ }
}
- /**
- * OpenAPI V3 has version as a string in the document's openapi property.
- * And host and basePath are in the document's servers property.
- * Relevant v3 reference: https://swagger.io/specification/#server-object
- **/
+ // OpenAPI V3 — first entry of `servers`.
if (objectHasProperty(doc, "servers")) {
- // TODO: dynamically add server URL value as variable in the environment if available, or notify user to add it.
const serverUrl = doc.servers?.[0]?.url
- return !serverUrl || serverUrl === "./" ? "<<baseUrl>>" : serverUrl
+ if (!serverUrl || serverUrl === "./") {
+ return { prefix, baseUrlValue: null }
+ }
+ // Don't seed a `baseUrl` variable whose value is itself a Hoppscotch
+ // placeholder (`<<X>>`). That would create a variable referencing another
+ // variable, which is confusing and round-trips badly. The placeholder will
+ // simply pass through to the endpoint.
+ if (/^<<[a-zA-Z0-9_.-]+>>$/.test(serverUrl)) {
+ return { prefix: serverUrl, baseUrlValue: null }
+ }
+ return { prefix, baseUrlValue: serverUrl }
}
- // If the document is neither v2 nor v3 or missing required fields
- return "<<baseUrl>>"
+ return { prefix, baseUrlValue: null }
}
const convertPathToHoppReqs = (
@@ -1049,7 +1230,7 @@ const convertPathToHoppReqs = (
// Construct request object
RA.map(({ method, info }) => {
- const openAPIUrl = parseOpenAPIUrl(doc)
+ const { prefix: openAPIUrl } = parseOpenAPIUrl(doc)
const openAPIPath = replaceOpenApiPathTemplating(pathName)
const endpoint =
@@ -1122,7 +1303,163 @@ const convertPathToHoppReqs = (
RA.toArray
)
-const convertOpenApiDocsToHopp = (
+/**
+ * Hoppscotch's OpenAPI export encodes nested folders as `/`-separated tag paths
+ * (`API/Users` = folder `Users` inside folder `API`). On import we want to
+ * reverse that — but slash-as-nesting is a convention, not a spec feature, so
+ * we only split when the tag set actually looks hierarchical or the document
+ * was produced by Hoppscotch (carrying our explicit marker).
+ *
+ * Heuristic: split iff at least one pair of tags has a strict segment-prefix
+ * relationship (e.g. `API` and `API/Users`, or `API/Users` and `API/Posts`
+ * which both share `API`). Single tags with literal slashes like `OAuth/PKCE`
+ * are kept flat to avoid mis-importing third-party docs.
+ */
+const HOPP_FOLDER_TAGS_MARKER = "x-hoppscotch-folder-tags"
+
+export const splitTagSegments = (tag: string): string[] =>
+ tag
+ .split("/")
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0)
+
+const tagNameToFolderSegments = (
+ tagName: string,
+ shouldSplit: boolean
+): string[] => {
+ if (shouldSplit) return splitTagSegments(tagName)
+ return tagName.length > 0 ? [tagName] : []
+}
+
+export const hasSharedTagPathPrefix = (allTagNames: string[]): boolean => {
+ const splits = allTagNames.map(splitTagSegments).filter((s) => s.length > 0)
+ if (splits.length < 2) return false
+
+ // NUL byte as the path-join separator — it cannot appear inside an
+ // OpenAPI tag segment, so two normalised paths only collide when their
+ // segment lists are identical. Written as the explicit "\u0000" escape
+ // so the source stays reviewable rather than carrying a raw NUL byte.
+ const sep = "\u0000"
+ const fullPaths = new Set(splits.map((segs) => segs.join(sep)))
+
+ // (a) any tag has another tag as a strict ancestor
+ for (const segs of splits) {
+ for (let i = 1; i < segs.length; i++) {
+ if (fullPaths.has(segs.slice(0, i).join(sep))) return true
+ }
+ }
+
+ // (b) two tags share a non-empty segment prefix
+ const seenPrefixes = new Set<string>()
+ for (const segs of splits) {
+ for (let i = 1; i < segs.length; i++) {
+ const prefix = segs.slice(0, i).join(sep)
+ if (seenPrefixes.has(prefix)) return true
+ seenPrefixes.add(prefix)
+ }
+ }
+
+ return false
+}
+
+const docHasFolderTagsMarker = (doc: unknown): boolean =>
+ typeof doc === "object" &&
+ doc !== null &&
+ (doc as Record<string, unknown>)[HOPP_FOLDER_TAGS_MARKER] === "slash"
+
+/**
+ * Among the operation's tags, pick the single canonical placement:
+ * the deepest (longest) split-segments list, ties broken by first occurrence.
+ * Avoids placing a request in `API` when it's also tagged `API/Users`.
+ */
+export const pickRequestFolderSegments = (
+ tags: string[],
+ shouldSplit: boolean
+): string[] => {
+ const segLists = tags
+ .map((t) => tagNameToFolderSegments(t, shouldSplit))
+ .filter((s) => s.length > 0)
+ if (segLists.length === 0) return []
+ return segLists.reduce((best, cur) => (cur.length > best.length ? cur : best))
+}
+
+type FolderTreeNode = {
+ name: string
+ description: string | null
+ requests: HoppRESTRequest[]
+ children: Map<string, FolderTreeNode>
+}
+
+const createFolderTreeNode = (name: string): FolderTreeNode => ({
+ name,
+ description: null,
+ requests: [],
+ children: new Map(),
+})
+
+const getOrCreateFolderNode = (
+ root: FolderTreeNode,
+ segments: string[]
+): FolderTreeNode => {
+ let node = root
+ for (const seg of segments) {
+ let child = node.children.get(seg)
+ if (!child) {
+ child = createFolderTreeNode(seg)
+ node.children.set(seg, child)
+ }
+ node = child
+ }
+ return node
+}
+
+const folderTreeNodeToCollection = (node: FolderTreeNode): HoppCollection =>
+ makeCollection({
+ name: node.name,
+ description: node.description,
+ requests: node.requests,
+ folders: [...node.children.values()].map(folderTreeNodeToCollection),
+ auth: { authType: "inherit", authActive: true },
+ headers: [],
+ variables: [],
+ preRequestScript: "",
+ testScript: "",
+ })
+
+const collectOpenApiTagNames = (
+ doc: OpenAPI.Document,
+ paths: Array<{ metadata: { tags: string[] } }>
+): Set<string> => {
+ const names = new Set<string>()
+ for (const { metadata } of paths) {
+ for (const t of metadata.tags) names.add(t)
+ }
+ if ("tags" in doc && Array.isArray(doc.tags)) {
+ for (const t of doc.tags) {
+ if (t && typeof t.name === "string") names.add(t.name)
+ }
+ }
+ return names
+}
+
+const extractTagDescriptions = (
+ doc: OpenAPI.Document
+): Record<string, string> => {
+ const result: Record<string, string> = {}
+ if ("tags" in doc && Array.isArray(doc.tags)) {
+ for (const tag of doc.tags as Array<{
+ name?: unknown
+ description?: unknown
+ }>) {
+ if (typeof tag.name === "string" && typeof tag.description === "string") {
+ result[tag.name] = tag.description
+ }
+ }
+ }
+ return result
+}
+
+export const convertOpenApiDocsToHopp = (
docs: OpenAPI.Document[]
): TE.TaskEither<string, HoppCollection[]> => {
// checking for unresolved references before conversion
@@ -1136,65 +1473,86 @@ const convertOpenApiDocsToHopp = (
}
const collections = docs.map((doc) => {
- const name = doc.info.title
- const description = doc.info.description ?? null
-
- // Extract tag descriptions from OpenAPI spec
- const tagDescriptions: Record<string, string> = {}
- if ("tags" in doc && Array.isArray(doc.tags)) {
- doc.tags.forEach((tag: any) => {
- if (tag.name && tag.description) {
- tagDescriptions[tag.name] = tag.description
- }
- })
+ const paths = Object.entries(doc.paths ?? {}).flatMap(
+ ([pathName, pathObj]) => convertPathToHoppReqs(doc, pathName, pathObj)
+ )
+ const allTagNames = collectOpenApiTagNames(doc, paths)
+ const tagDescriptions = extractTagDescriptions(doc)
+ const { baseUrlValue } = parseOpenAPIUrl(doc)
+
+ // Decide whether to interpret `/` as folder nesting: either an explicit
+ // marker from a Hoppscotch export, or the tag set has clear hierarchical
+ // structure.
+ const shouldSplitTags =
+ docHasFolderTagsMarker(doc) || hasSharedTagPathPrefix([...allTagNames])
+
+ const root = createFolderTreeNode("")
+ const requestsWithoutTags: HoppRESTRequest[] = []
+
+ // Apply tag descriptions at their (possibly nested) folder level.
+ for (const tagName of allTagNames) {
+ const desc = tagDescriptions[tagName]
+ if (!desc) continue
+ const segs = tagNameToFolderSegments(tagName, shouldSplitTags)
+ if (segs.length === 0) continue
+ const node = getOrCreateFolderNode(root, segs)
+ // First description wins if multiple tags collapse to the same path
+ // (e.g. `API//Users` and `API/Users` after normalization).
+ if (node.description === null) node.description = desc
}
- const paths = Object.entries(doc.paths ?? {})
- .map(([pathName, pathObj]) =>
- convertPathToHoppReqs(doc, pathName, pathObj)
+ // Place each operation at its canonical folder. Multi-tag operations land
+ // at one location only (deepest tag); duplicating across folders would
+ // break edit semantics on subsequent re-export.
+ for (const { metadata, request } of paths) {
+ if (metadata.tags.length === 0) {
+ requestsWithoutTags.push(request)
+ continue
+ }
+ const targetSegs = pickRequestFolderSegments(
+ metadata.tags,
+ shouldSplitTags
)
- .flat()
-
- const requestsByTags: Record<string, Array<HoppRESTRequest>> = {}
- const requestsWithoutTags: Array<HoppRESTRequest> = []
-
- paths.forEach(({ metadata, request }) => {
- const tags = metadata.tags
-
- if (tags.length === 0) {
+ if (targetSegs.length === 0) {
requestsWithoutTags.push(request)
- return
+ continue
}
+ const node = getOrCreateFolderNode(root, targetSegs)
+ node.requests.push(cloneDeep(request))
+ }
- for (const tag of tags) {
- if (!requestsByTags[tag]) {
- requestsByTags[tag] = []
- }
-
- requestsByTags[tag].push(cloneDeep(request))
- }
- })
+ // Seed a `baseUrl` collection variable from the doc's resolved server URL
+ // so users have one place to switch hosts (staging/prod/local) instead of
+ // every endpoint hardcoding a literal URL.
+ //
+ // `currentValue` is left empty to match the convention used by the other
+ // importers (postman, insomnia): runtime current values live in
+ // `CurrentValueService` and are local-only; only `initialValue` is
+ // persisted server-side.
+ const variables =
+ baseUrlValue !== null
+ ? [
+ {
+ key: "baseUrl",
+ initialValue: baseUrlValue,
+ currentValue: "",
+ secret: false,
+ },
+ ]
+ : []
return makeCollection({
- name,
- folders: Object.entries(requestsByTags).map(([name, paths]) =>
- makeCollection({
- name,
- description: tagDescriptions[name] ?? null,
- requests: paths,
- folders: [],
- auth: { authType: "inherit", authActive: true },
- headers: [],
- variables: [],
- preRequestScript: "",
- testScript: "",
- })
- ),
+ name: doc.info.title,
+ description: doc.info.description ?? null,
+ folders: [...root.children.values()].map(folderTreeNodeToCollection),
requests: requestsWithoutTags,
- auth: { authType: "inherit", authActive: true },
+ // Read doc-level security ONCE here so the collection-vs-request
+ // structure mirrors the OpenAPI two-layer model. Per-operation reads
+ // (in parseOpenAPIV3Auth / parseOpenAPIV2Auth) only return overrides;
+ // requests with no override get `inherit` and defer to this value.
+ auth: parseCollectionLevelAuth(doc),
headers: [],
- variables: [],
- description,
+ variables,
preRequestScript: "",
testScript: "",
})