
//#region src/index.ts
const VALID_SCHEMAS = ["https://schema.getpostman.com/json/collection/v2.0.0/collection.json", "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"];
const plugin = { importer: {
	name: "Postman",
	description: "Import postman collections",
	onImport(_ctx, args) {
		return convertPostman(args.text);
	}
} };
function convertPostman(contents) {
	const root = parseJSONToRecord(contents);
	if (root == null) return;
	const info = toRecord(root.info);
	if (!VALID_SCHEMAS.includes(typeof info.schema === "string" ? info.schema : "n/a") || !Array.isArray(root.item)) return;
	const globalAuth = importAuth(root.auth);
	const exportResources = {
		workspaces: [],
		environments: [],
		httpRequests: [],
		folders: []
	};
	const workspace = {
		model: "workspace",
		id: generateId("workspace"),
		name: info.name ? String(info.name) : "Postman Import",
		description: importDescription(info.description),
		...globalAuth
	};
	exportResources.workspaces.push(workspace);
	const environment = {
		model: "environment",
		id: generateId("environment"),
		name: "Global Variables",
		workspaceId: workspace.id,
		parentModel: "workspace",
		parentId: null,
		variables: toArray(root.variable).map((v) => ({
			name: v.key,
			value: v.value
		})) ?? []
	};
	exportResources.environments.push(environment);
	let sortPriorityIndex = 0;
	const importItem = (v, folderId = null) => {
		if (typeof v.name === "string" && Array.isArray(v.item)) {
			const folder = {
				model: "folder",
				sortPriority: sortPriorityIndex++,
				workspaceId: workspace.id,
				id: generateId("folder"),
				name: v.name,
				folderId
			};
			exportResources.folders.push(folder);
			for (const child of v.item) importItem(child, folder.id);
		} else if (typeof v.name === "string" && "request" in v) {
			const r = toRecord(v.request);
			const bodyPatch = importBody(r.body);
			const requestAuth = importAuth(r.auth);
			const headers = toArray(r.header).map((h) => {
				return {
					name: h.key,
					value: h.value,
					enabled: !h.disabled
				};
			});
			for (const bodyPatchHeader of bodyPatch.headers) {
				if (headers.find((h) => h.name.toLowerCase() === bodyPatchHeader.name.toLowerCase())) continue;
				headers.push(bodyPatchHeader);
			}
			const { url, urlParameters } = convertUrl(r.url);
			const request = {
				model: "http_request",
				id: generateId("http_request"),
				workspaceId: workspace.id,
				folderId,
				name: v.name,
				description: importDescription(r.description),
				method: typeof r.method === "string" ? r.method : "GET",
				url,
				urlParameters,
				body: bodyPatch.body,
				bodyType: bodyPatch.bodyType,
				sortPriority: sortPriorityIndex++,
				headers,
				...requestAuth
			};
			exportResources.httpRequests.push(request);
		} else console.log("Unknown item", v, folderId);
	};
	for (const item of root.item) importItem(item);
	return { resources: deleteUndefinedAttrs(convertTemplateSyntax(exportResources)) };
}
function convertUrl(rawUrl) {
	if (typeof rawUrl === "string") return {
		url: rawUrl,
		urlParameters: []
	};
	const url = toRecord(rawUrl);
	let v = "";
	if ("protocol" in url && typeof url.protocol === "string") v += `${url.protocol}://`;
	if ("host" in url) v += `${Array.isArray(url.host) ? url.host.join(".") : String(url.host)}`;
	if ("port" in url && typeof url.port === "string") v += `:${url.port}`;
	if ("path" in url) {
		if (Array.isArray(url.path) && url.path.length > 0) v += `/${url.path.join("/")}`;
		else if (typeof url.path === "string" && url.path.length > 0) v += `/${url.path.replace(/^\//, "")}`;
	}
	const params = [];
	if ("query" in url && Array.isArray(url.query) && url.query.length > 0) for (const query of url.query) params.push({
		name: query.key ?? "",
		value: query.value ?? "",
		enabled: !query.disabled
	});
	if ("variable" in url && Array.isArray(url.variable) && url.variable.length > 0) for (const v$1 of url.variable) params.push({
		name: `:${v$1.key ?? ""}`,
		value: v$1.value ?? "",
		enabled: !v$1.disabled
	});
	if ("hash" in url && typeof url.hash === "string") v += `#${url.hash}`;
	return {
		url: v,
		urlParameters: params
	};
}
function importAuth(rawAuth) {
	const auth = toRecord(rawAuth);
	const pmArrayToObj = (v) => {
		if (!Array.isArray(v)) return toRecord(v);
		const o = {};
		for (const i of v) {
			const ii = toRecord(i);
			if (typeof ii.key === "string") o[ii.key] = ii.value;
		}
		return o;
	};
	const authType = auth.type ? String(auth.type) : void 0;
	if (authType === "noauth") return {
		authenticationType: "none",
		authentication: {}
	};
	if ("basic" in auth && authType === "basic") {
		const b = pmArrayToObj(auth.basic);
		return {
			authenticationType: "basic",
			authentication: {
				username: String(b.username ?? ""),
				password: String(b.password ?? "")
			}
		};
	}
	if ("bearer" in auth && authType === "bearer") {
		const b = pmArrayToObj(auth.bearer);
		return {
			authenticationType: "bearer",
			authentication: { token: String(b.token ?? "") }
		};
	}
	if ("awsv4" in auth && authType === "awsv4") {
		const a = pmArrayToObj(auth.awsv4);
		return {
			authenticationType: "awsv4",
			authentication: {
				accessKeyId: a.accessKey != null ? String(a.accessKey) : void 0,
				secretAccessKey: a.secretKey != null ? String(a.secretKey) : void 0,
				sessionToken: a.sessionToken != null ? String(a.sessionToken) : void 0,
				region: a.region != null ? String(a.region) : void 0,
				service: a.service != null ? String(a.service) : void 0
			}
		};
	}
	if ("apikey" in auth && authType === "apikey") {
		const a = pmArrayToObj(auth.apikey);
		return {
			authenticationType: "apikey",
			authentication: {
				location: a.in === "query" ? "query" : "header",
				key: a.value != null ? String(a.value) : void 0,
				value: a.key != null ? String(a.key) : void 0
			}
		};
	}
	if ("jwt" in auth && authType === "jwt") {
		const a = pmArrayToObj(auth.jwt);
		return {
			authenticationType: "jwt",
			authentication: {
				algorithm: a.algorithm != null ? String(a.algorithm).toUpperCase() : void 0,
				secret: a.secret != null ? String(a.secret) : void 0,
				secretBase64: !!a.isSecretBase64Encoded,
				payload: a.payload != null ? String(a.payload) : void 0,
				headerPrefix: a.headerPrefix != null ? String(a.headerPrefix) : void 0,
				location: a.addTokenTo === "header" ? "header" : "query"
			}
		};
	}
	if ("oauth2" in auth && authType === "oauth2") {
		const o = pmArrayToObj(auth.oauth2);
		let grantType = o.grant_type ? String(o.grant_type) : "authorization_code";
		let pkcePatch = {};
		if (grantType === "authorization_code_with_pkce") {
			grantType = "authorization_code";
			pkcePatch = o.grant_type === "authorization_code_with_pkce" ? {
				usePkce: true,
				pkceChallengeMethod: o.challengeAlgorithm ?? void 0,
				pkceCodeVerifier: o.code_verifier != null ? String(o.code_verifier) : void 0
			} : {};
		} else if (grantType === "password_credentials") grantType = "password";
		const accessTokenUrl = o.accessTokenUrl != null ? String(o.accessTokenUrl) : void 0;
		const audience = o.audience != null ? String(o.audience) : void 0;
		const authorizationUrl = o.authUrl != null ? String(o.authUrl) : void 0;
		const clientId = o.clientId != null ? String(o.clientId) : void 0;
		const clientSecret = o.clientSecret != null ? String(o.clientSecret) : void 0;
		const credentials = o.client_authentication === "body" ? "body" : void 0;
		const headerPrefix = o.headerPrefix ?? "Bearer";
		const password = o.password != null ? String(o.password) : void 0;
		const redirectUri = o.redirect_uri != null ? String(o.redirect_uri) : void 0;
		const scope = o.scope != null ? String(o.scope) : void 0;
		const state = o.state != null ? String(o.state) : void 0;
		const username = o.username != null ? String(o.username) : void 0;
		let grantPatch = {};
		if (grantType === "authorization_code") grantPatch = {
			clientSecret,
			authorizationUrl,
			accessTokenUrl,
			redirectUri,
			state,
			...pkcePatch
		};
		else if (grantType === "implicit") grantPatch = {
			authorizationUrl,
			redirectUri,
			state
		};
		else if (grantType === "password") grantPatch = {
			clientSecret,
			accessTokenUrl,
			username,
			password
		};
		else if (grantType === "client_credentials") grantPatch = {
			clientSecret,
			accessTokenUrl
		};
		return {
			authenticationType: "oauth2",
			authentication: {
				name: "oauth2",
				grantType,
				audience,
				clientId,
				credentials,
				headerPrefix,
				scope,
				...grantPatch
			}
		};
	}
	return {
		authenticationType: null,
		authentication: {}
	};
}
function importBody(rawBody) {
	const body = toRecord(rawBody);
	if (body.mode === "graphql") return {
		headers: [{
			name: "Content-Type",
			value: "application/json",
			enabled: true
		}],
		bodyType: "graphql",
		body: { text: JSON.stringify({
			query: body.graphql?.query || "",
			variables: parseJSONToRecord(body.graphql?.variables || "{}")
		}, null, 2) }
	};
	if (body.mode === "urlencoded") return {
		headers: [{
			name: "Content-Type",
			value: "application/x-www-form-urlencoded",
			enabled: true
		}],
		bodyType: "application/x-www-form-urlencoded",
		body: { form: toArray(body.urlencoded).map((f) => ({
			enabled: !f.disabled,
			name: f.key ?? "",
			value: f.value ?? ""
		})) }
	};
	if (body.mode === "formdata") return {
		headers: [{
			name: "Content-Type",
			value: "multipart/form-data",
			enabled: true
		}],
		bodyType: "multipart/form-data",
		body: { form: toArray(body.formdata).map((f) => f.src != null ? {
			enabled: !f.disabled,
			contentType: f.contentType ?? null,
			name: f.key ?? "",
			file: f.src ?? ""
		} : {
			enabled: !f.disabled,
			name: f.key ?? "",
			value: f.value ?? ""
		}) }
	};
	if (body.mode === "raw") return {
		headers: [{
			name: "Content-Type",
			value: body.options?.raw?.language === "json" ? "application/json" : "",
			enabled: true
		}],
		bodyType: body.options?.raw?.language === "json" ? "application/json" : "other",
		body: { text: body.raw ?? "" }
	};
	if (body.mode === "file") return {
		headers: [],
		bodyType: "binary",
		body: { filePath: body.file?.src }
	};
	return {
		headers: [],
		bodyType: null,
		body: {}
	};
}
function parseJSONToRecord(jsonStr) {
	try {
		return toRecord(JSON.parse(jsonStr));
	} catch {
		return null;
	}
}
function toRecord(value) {
	if (value && typeof value === "object" && !Array.isArray(value)) return value;
	return {};
}
function toArray(value) {
	if (Object.prototype.toString.call(value) === "[object Array]") return value;
	return [];
}
function importDescription(rawDescription) {
	if (rawDescription == null) return;
	if (typeof rawDescription === "string") return rawDescription;
	if (typeof rawDescription === "object" && !Array.isArray(rawDescription)) {
		const description = toRecord(rawDescription);
		if ("content" in description && description.content != null) return String(description.content);
		return;
	}
	return String(rawDescription);
}
/** Recursively render all nested object properties */
function convertTemplateSyntax(obj) {
	if (typeof obj === "string") return obj.replace(/{{\s*(_\.)?([^}]*)\s*}}/g, (_m, _dot, expr) => `\${[${expr.trim().replace(/^vault:/, "")}]}`);
	if (Array.isArray(obj) && obj != null) return obj.map(convertTemplateSyntax);
	if (typeof obj === "object" && obj != null) return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, convertTemplateSyntax(v)]));
	return obj;
}
function deleteUndefinedAttrs(obj) {
	if (Array.isArray(obj) && obj != null) return obj.map(deleteUndefinedAttrs);
	if (typeof obj === "object" && obj != null) return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0).map(([k, v]) => [k, deleteUndefinedAttrs(v)]));
	return obj;
}
const idCount = {};
function generateId(model) {
	idCount[model] = (idCount[model] ?? -1) + 1;
	return `GENERATE_ID::${model.toUpperCase()}_${idCount[model]}`;
}

//#endregion
exports.convertPostman = convertPostman;
exports.plugin = plugin;