UNPKG

oazapfts

Version:

OpenApi TypeScript client generator

1,443 lines (1,438 loc) 37.9 kB
import c from "typescript"; import T from "lodash"; const U = c.factory; function Ae(t) { const e = t.split(/{([\s\S]+?)}/g), n = T.chunk(e.slice(1), 2); return te( e[0], n.map(([i, r]) => ({ expression: U.createIdentifier(i), literal: r })) ); } function Ke(t, e) { const n = [ F( H( Object.entries(e || {}).map(([i, r]) => ({ name: i, initializer: q(r.default) })) ), { type: U.createTypeLiteralNode( Object.entries(e || {}).map(([i, r]) => x({ name: i, type: r.enum ? V(r.enum) : U.createUnionTypeNode([ h.string, h.number, h.boolean ]) })) ) } ) ]; return me(n, Ae(t)); } function je(t) { return t.variables ? Ke(t.url, t.variables) : U.createStringLiteral(t.url); } function ke(t) { if (!t) return "/"; const { url: e, variables: n } = t; return n ? e.replace( /\{(.+?)\}/g, (i, r) => n[r] ? String(n[r].default) : i ) : e; } function Le(t) { return U.createStringLiteral(ke(t[0])); } function Pe(t, e) { return t.description ? T.camelCase(t.description.replace(/\W+/, " ")) : `server${e + 1}`; } function Re(t) { return ee( t.map((e, n) => [ Pe(e, n), je(e) ]) ); } const o = c.factory, $e = [ "GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE" ], fe = { "*/*": "json", "application/json": "json", "application/x-www-form-urlencoded": "form", "multipart/form-data": "multipart" }; function Ie(t) { return typeof t == "string" && /^[^/]+\/[^/]+$/.test(t); } function Z(t) { return fe[t] === "json" || /\bjson\b/i.test(t); } function Ue(t) { if (t?.content) for (const e of Object.keys(t.content)) { const n = fe[e]; if (n) return n; if (Z(e)) return "json"; } } function qe({ style: t = "form", explode: e = !0, content: n }) { if (n) { const i = Object.keys(n); if (i.length !== 1) throw new Error( "Parameters with content property must specify one media type" ); if (!Z(i[0])) throw new Error( "Parameters with content property must specify a JSON compatible media type" ); return "json"; } return e && t === "deepObject" ? "deep" : e ? "explode" : t === "spaceDelimited" ? "space" : t === "pipeDelimited" ? "pipe" : "form"; } function Ce(t) { if (t && !t.match(/[^\w\s]/) && (t = T.camelCase(t), Q(t))) return t; } function De(t, e, n) { const i = Ce(n); return i || (e = e.replace(/\{(.+?)\}/, "by $1").replace(/\{(.+?)\}/, "and $1"), w(`${t} ${e}`)); } function Be(t) { return typeof t == "boolean" ? t : t && "nullable" in t ? !O(t) && t.nullable : !1; } function O(t) { return typeof t == "object" && t !== null && "$ref" in t; } function le(t) { if (!t.startsWith("#/")) throw new Error( `External refs are not supported (${t}). Make sure to call SwaggerParser.bundle() first.` ); return t.slice(2).split("/").map((e) => decodeURI(e.replace(/~1/g, "/").replace(/~0/g, "~"))); } function R(t) { return t.replace(/.+\//, ""); } function ze(t) { const e = R(t); return /^\d+/.test(e) ? le(t).join("_") : e; } function ue(t) { if (O(t)) return R(t.$ref); } const Me = { readOnly: "Read", writeOnly: "Write" }; function Ve(t) { return t ? Me[t] : ""; } function w(t, e = !1, n) { let i = T.camelCase(t) + Ve(n); return e && (i = T.upperFirst(i)), Q(i) ? i : "$" + i; } function _e(t, e) { const n = [], i = t.replace( /(.*?)\{(.+?)\}(.*?)(?=\{|$)/g, (r, s, u, f) => { const p = w(u); return n.push({ expression: C( o.createIdentifier("encodeURIComponent"), { args: [o.createIdentifier(p)] } ), literal: f }), s; } ); return e && n.push({ expression: e, literal: "" }), te(i, n); } function pe(t, e) { return C( o.createPropertyAccessExpression( o.createIdentifier("QS"), t ), { args: e } ); } function z(t, e, n) { return C( o.createPropertyAccessExpression( o.createIdentifier("oazapfts"), t ), { args: e, typeArgs: n } ); } function He(t) { const e = [], n = {}; return t.forEach((i) => { const r = /^(.+?)\[(.*?)\]/.exec(i.name); if (!r) { e.push(i); return; } const [, s, u] = r; let f = n[s]; f || (f = n[s] = { name: s, in: i.in, style: "deepObject", schema: { type: "object", properties: {} } }, e.push(f)), f.schema.properties[u] = i.schema; }), e; } function We(t) { return t in h; } class st { constructor(e, n = {}, i = !1) { this.spec = e, this.opts = n, this.isConverted = i, this.spec.components?.schemas && this.preprocessComponents(this.spec.components.schemas); } // see `preprocessComponents` for the definition of a discriminating schema discriminatingSchemas = /* @__PURE__ */ new Set(); aliases = []; enumAliases = []; enumRefs = {}; // Collect the types of all referenced schemas so we can export them later // Referenced schemas can be pointing at the following versions: // - "base": The regular type/interface e.g. ExampleSchema // - "readOnly": The readOnly version e.g. ExampleSchemaRead // - "writeOnly": The writeOnly version e.g. ExampleSchemaWrite refs = {}; // Maps a referenced schema to its readOnly/writeOnly status // This field should be used exclusively within the `checkSchemaOnlyMode` method refsOnlyMode = /* @__PURE__ */ new Map(); // Keep track of already used type aliases typeAliases = {}; reset() { this.aliases = [], this.enumAliases = [], this.refs = {}, this.typeAliases = {}; } resolve(e) { if (!O(e)) return e; const n = e.$ref, i = le(n), r = T.get(this.spec, i); if (typeof r > "u") throw new Error(`Can't find ${i}`); return r; } resolveArray(e) { return e ? e.map((n) => this.resolve(n)) : []; } skip(e) { return e && e.some((i) => this.opts?.exclude?.includes(i)) ? !0 : this.opts?.include ? !(e && e.some((r) => this.opts.include?.includes(r))) : !1; } findAvailableRef(e) { const n = (r) => { try { return this.resolve({ $ref: r }), !1; } catch { return !0; } }; if (n(e)) return e; let i = 2; for (; ; ) { const r = e + String(i); if (n(r)) return r; i += 1; } } getUniqueAlias(e) { let n = this.typeAliases[e] || 0; return n && (this.typeAliases[e] = ++n, e += n), this.typeAliases[e] = 1, e; } getEnumUniqueAlias(e, n) { return this.enumRefs[e] && this.enumRefs[e].values == n ? e : this.getUniqueAlias(e); } /** * Create a type alias for the schema referenced by the given ReferenceObject */ getRefAlias(e, n, i) { const r = i ? this.findAvailableRef(e.$ref + "Base") : e.$ref; if (!this.refs[r]) { let s = this.resolve(e); typeof s != "boolean" && i && (s = T.cloneDeep(s), delete s.discriminator); const u = typeof s != "boolean" && s.title || ze(r), f = w(u, !0); if (this.isTrueEnum(s, u)) return this.getTypeFromSchema(s, u); const p = this.getUniqueAlias(f); this.refs[r] = { base: o.createTypeReferenceNode(p, void 0), readOnly: void 0, writeOnly: void 0 }; const l = this.getTypeFromSchema(s, void 0); this.aliases.push( M({ modifiers: [P.export], name: p, type: l }) ); const { readOnly: m, writeOnly: g } = this.checkSchemaOnlyMode(s); if (m) { const S = this.getUniqueAlias( w(u, !0, "readOnly") ); this.refs[r].readOnly = o.createTypeReferenceNode( S, void 0 ); const N = this.getTypeFromSchema(s, u, "readOnly"); this.aliases.push( M({ modifiers: [P.export], name: S, type: N }) ); } if (g) { const S = this.getUniqueAlias( w(u, !0, "writeOnly") ); this.refs[r].writeOnly = o.createTypeReferenceNode( S, void 0 ); const N = this.getTypeFromSchema(s, u, "writeOnly"); this.aliases.push( M({ modifiers: [P.export], name: S, type: N }) ); } } return this.refs[r][n || "base"] ?? this.refs[r].base; } getUnionType(e, n, i) { if (n) { if (n.propertyName === void 0) throw new Error("Discriminators require a propertyName"); const r = new Set( Object.values(n.mapping || {}).map(R) ); return o.createUnionTypeNode( [ ...Object.entries(n.mapping || {}).map( ([s, u]) => [ s, { $ref: u } ] ), ...e.filter((s) => { if (!O(s)) throw new Error( "Discriminators require references, not inline schemas" ); return !r.has(R(s.$ref)); }).map((s) => { const u = R( s.$ref ), p = this.resolve( s ).properties?.[n.propertyName]; return [(p && "enum" in p ? p?.enum?.[0] : "") || u, s]; }) ].map( ([s, u]) => ( // Yields: { [discriminator.propertyName]: discriminatorValue } & variant o.createIntersectionTypeNode([ o.createTypeLiteralNode([ x({ name: n.propertyName, type: o.createLiteralTypeNode( o.createStringLiteral(s) ) }) ]), this.getTypeFromSchema(u, void 0, i) ]) ) ) ); } else return o.createUnionTypeNode( T.uniq( e.map( (r) => this.getTypeFromSchema(r, void 0, i) ) ) ); } /** * Creates a type node from a given schema. * Delegates to getBaseTypeFromSchema internally and * optionally adds a union with null. */ getTypeFromSchema(e, n, i) { const r = this.getBaseTypeFromSchema(e, n, i); return Be(e) ? o.createUnionTypeNode([r, h.null]) : r; } getEmptySchemaType() { return this.opts.useUnknown ? h.unknown : h.any; } /** * This is the very core of the OpenAPI to TS conversion - it takes a * schema and returns the appropriate type. */ getBaseTypeFromSchema(e, n, i) { if (!e && typeof e != "boolean") return this.getEmptySchemaType(); if (O(e)) return this.getRefAlias(e, i); if (e === !0) return this.getEmptySchemaType(); if (e === !1) return h.never; if (e.oneOf) { const r = { ...e }; return delete r.oneOf, this.getUnionType( e.oneOf.map( (s) => ( // ensure that base properties from the schema are included in the oneOf variants T.mergeWith({}, r, s, (u, f) => { if (T.isArray(u)) return u.concat(f); }) ) ), e.discriminator, i ); } if (e.anyOf) return this.getUnionType(e.anyOf, void 0, i); if (e.discriminator?.mapping) { const r = e.discriminator.mapping; return this.getUnionType( Object.values(r).map((s) => ({ $ref: s })), void 0, i ); } if (e.allOf) { const r = []; for (const s of e.allOf) if (O(s) && this.discriminatingSchemas.has(s.$ref)) { const f = this.resolve(s).discriminator, p = Object.entries(f.mapping ?? {}).filter(([, l]) => l === e["x-component-ref-path"]).map(([l]) => l); p.length > 0 && r.push( o.createTypeLiteralNode([ x({ name: f.propertyName, type: this.getTypeFromEnum(p) }) ]) ), r.push( this.getRefAlias( s, i, /* ignoreDiscriminator */ !0 ) ); } else r.push( this.getTypeFromSchema( { required: e.required, ...s }, void 0, i ) ); return (e.properties || e.additionalProperties) && r.push( this.getTypeFromProperties( e.properties || {}, e.required, e.additionalProperties, i ) ), o.createIntersectionTypeNode(r); } if (Array.isArray(e.type)) return o.createUnionTypeNode( e.type.map((r) => { const s = { ...e, type: r }; return "items" in s && r !== "array" && delete s.items, "properties" in s && r !== "object" && delete s.properties, this.getBaseTypeFromSchema(s, n, i); }) ); if ("items" in e) { const r = e.items; if (r.enum) { const s = this.isTrueEnum(r, n) ? this.getTrueEnum(r, n) : V(r.enum); return o.createArrayTypeNode(s); } return o.createArrayTypeNode( this.getTypeFromSchema(e.items, void 0, i) ); } if ("prefixItems" in e && e.prefixItems) return o.createTupleTypeNode( e.prefixItems.map((r) => this.getTypeFromSchema(r)) ); if (e.properties || e.additionalProperties) return this.getTypeFromProperties( e.properties || {}, e.required, e.additionalProperties, i ); if (e.enum) return this.isTrueEnum(e, n) ? this.getTrueEnum(e, n) : V(e.enum); if (e.format == "binary") return o.createTypeReferenceNode("Blob", []); if (e.const) return this.getTypeFromEnum([e.const]); if (e.type !== void 0) { if (e.type === null) return h.null; if (We(e.type)) return h[e.type]; } return this.getEmptySchemaType(); } isTrueEnum(e, n) { return !!(typeof e != "boolean" && e.enum && this.opts.useEnumType && n && e.type !== "boolean"); } /** * Creates literal type (or union) from an array of values */ getTypeFromEnum(e) { const n = e.map((i) => { if (i === null) return h.null; if (typeof i == "boolean") return i ? o.createLiteralTypeNode( c.factory.createToken(c.SyntaxKind.TrueKeyword) ) : o.createLiteralTypeNode( c.factory.createToken(c.SyntaxKind.FalseKeyword) ); if (typeof i == "number") return o.createLiteralTypeNode(o.createNumericLiteral(i)); if (typeof i == "string") return o.createLiteralTypeNode(o.createStringLiteral(i)); throw new Error(`Unexpected ${String(i)} of type ${typeof i} in enum`); }); return n.length > 1 ? o.createUnionTypeNode(n) : n[0]; } getEnumValuesString(e) { return e.join("_"); } /* Creates a enum "ref" if not used, reuse existing if values and name matches or creates a new one with a new name adding a number */ getTrueEnum(e, n) { if (typeof e == "boolean") throw new Error( "cannot get enum from boolean schema. schema must be an object" ); const r = (e.title || T.upperFirst(n)).split(/[^A-Za-z0-9$_]/g).map((g) => T.upperFirst(g)).join(""), s = this.getEnumValuesString( e.enum ? e.enum : [] ), u = this.getEnumUniqueAlias(r, s); if (this.enumRefs[r] && r === u) return this.enumRefs[r].type; const f = e.enum ? e.enum : [], p = e["x-enumNames"] ?? e["x-enum-varnames"]; if (p) { if (!Array.isArray(p)) throw new Error("enum names must be an array"); if (p.length !== f.length) throw new Error("enum names must have the same length as enum values"); } const l = f.map((g, S) => { if (e.type === "number" || e.type === "integer") { const N = p ? p[S] : String(g); return o.createEnumMember( o.createIdentifier(w(N, !0)), q(g) ); } return o.createEnumMember( o.createIdentifier(w(g, !0)), q(g) ); }); this.enumAliases.push( o.createEnumDeclaration([P.export], u, l) ); const m = o.createTypeReferenceNode(u, void 0); return this.enumRefs[r] = { values: s, type: o.createTypeReferenceNode(u, void 0) }, m; } /** * Checks if readOnly/writeOnly properties are present in the given schema. * Returns a tuple of booleans; the first one is about readOnly, the second * one is about writeOnly. */ checkSchemaOnlyMode(e, n = !0) { if (this.opts.mergeReadWriteOnly) return { readOnly: !1, writeOnly: !1 }; const i = (r, s) => { if (O(r)) { if (!n) return { readOnly: !1, writeOnly: !1 }; if (s.has(r.$ref)) return { readOnly: !1, writeOnly: !1 }; const l = this.refsOnlyMode.get(r.$ref); if (l) return l; s.add(r.$ref); const m = i(this.resolve(r), s); return s.delete(r.$ref), this.refsOnlyMode.set(r.$ref, m), m; } if (typeof r == "boolean") return { readOnly: !1, writeOnly: !1 }; let u = r.readOnly ?? !1, f = r.writeOnly ?? !1; const p = []; "items" in r && r.items ? p.push(r.items) : (p.push(...Object.values(r.properties ?? {})), p.push(...r.allOf ?? []), p.push(...r.anyOf ?? []), p.push(...r.oneOf ?? [])); for (const l of p) { if (u && f) break; const m = i(l, s); u = u || m.readOnly, f = f || m.writeOnly; } return { readOnly: u, writeOnly: f }; }; return i(e, /* @__PURE__ */ new Set()); } /** * Recursively creates a type literal with the given props. */ getTypeFromProperties(e, n, i, r) { const f = Object.keys(e).filter((p) => { const l = e[p], { readOnly: m, writeOnly: g } = this.checkSchemaOnlyMode(l, !1); switch (r) { case "readOnly": return m || !g; case "writeOnly": return g || !m; default: return !m && !g; } }).map((p) => { const l = e[p], m = n && n.includes(p); let g = this.getTypeFromSchema(l, p, r); !m && this.opts.unionUndefined && (g = o.createUnionTypeNode([g, h.undefined])); const S = x({ questionToken: !m, name: p, type: g }); if (typeof l != "boolean" && "description" in l && l.description) { const N = l.description.replace("*/", "*\\/"); c.addSyntheticLeadingComment( S, c.SyntaxKind.MultiLineCommentTrivia, // Ensures it is formatted like a JSDoc comment: /** description here */ `* ${N} `, !0 ); } return S; }); if (i) { const p = i === !0 ? this.getEmptySchemaType() : this.getTypeFromSchema(i, void 0, r); f.push(Te(p)); } return o.createTypeLiteralNode(f); } getTypeFromResponses(e, n) { return o.createUnionTypeNode( Object.entries(e).map(([i, r]) => { const s = i === "default" ? h.number : o.createLiteralTypeNode(o.createNumericLiteral(i)), u = [ x({ name: "status", type: s }) ], f = this.getTypeFromResponse(r, n); return f !== h.void && u.push( x({ name: "data", type: f }) ), o.createTypeLiteralNode(u); }) ); } getTypeFromResponse(e, n) { const i = this.resolve(e); return !i || !i.content ? h.void : this.getTypeFromSchema( this.getSchemaFromContent(i.content), void 0, n ); } getResponseType(e) { if (!e) return "text"; const n = Object.values(e).map( (r) => this.resolve(r) ); return n.some( (r) => Object.keys(r.content ?? {}).length > 0 ) ? n.some((r) => Object.keys(r.content ?? {}).some(Z)) ? "json" : n.some( (r) => Object.keys(r.content ?? []).some((s) => s.startsWith("text/")) ) ? "text" : "blob" : "text"; } getSchemaFromContent(e) { const n = Object.keys(e).find(Ie); if (n) { const { schema: i } = e[n]; if (i) return i; } return Object.keys(e).length === 0 || Object.keys(e).some((i) => i.startsWith("text/")) ? { type: "string" } : { type: "string", format: "binary" }; } getTypeFromParameter(e) { if (e.content) { const n = this.getSchemaFromContent(e.content); return this.getTypeFromSchema(n); } return this.getTypeFromSchema(O(e) ? e : e.schema); } wrapResult(e) { return this.opts?.optimistic ? z("ok", [e]) : e; } /** * Does three things: * 1. Add a `x-component-ref-path` property. * 2. Record discriminating schemas in `this.discriminatingSchemas`. A discriminating schema * refers to a schema that has a `discriminator` property which is neither used in conjunction * with `oneOf` nor `anyOf`. * 3. Make all mappings of discriminating schemas explicit to generate types immediately. */ preprocessComponents(e) { const n = "#/components/schemas/"; for (const r of Object.keys(e)) { const s = e[r]; O(s) || typeof s == "boolean" || (s["x-component-ref-path"] = n + r, typeof s != "boolean" && s.discriminator && !s.oneOf && !s.anyOf && this.discriminatingSchemas.add(n + r)); } const i = (r, s) => Object.values(r.mapping || {}).includes(s); for (const r of Object.keys(e)) { const s = e[r]; if (!(O(s) || typeof s == "boolean" || !s.allOf)) for (const u of s.allOf) { if (!O(u) || !this.discriminatingSchemas.has(u.$ref)) continue; const p = e[R(u.$ref)].discriminator; i(p, n + r) || (p.mapping || (p.mapping = {}), p.mapping[r] = n + r); } } } generateApi() { this.reset(); const e = c.createSourceFile( "ApiStub.ts", `/** * DO NOT MODIFY - This file has been generated using oazapfts. * See https://www.npmjs.com/package/oazapfts */ import * as Oazapfts from "@oazapfts/runtime"; import * as QS from "@oazapfts/runtime/query"; export const defaults: Oazapfts.Defaults<Oazapfts.CustomHeaders> = { headers: {}, baseUrl: "/", }; const oazapfts = Oazapfts.runtime(defaults); export const servers = {}; `, // replaced with ApiStub.ts during build c.ScriptTarget.Latest, /*setParentNodes*/ !1, c.ScriptKind.TS ), n = Y(e.statements, "servers"); Object.assign(n, { initializer: Re(this.spec.servers || []) }); const { initializer: i } = Y( e.statements, "defaults" ); if (!i || !c.isObjectLiteralExpression(i)) throw new Error("No object literal: defaults"); Oe( i, "baseUrl", Le(this.spec.servers || []) ); const r = [], s = {}; return this.spec.paths && Object.keys(this.spec.paths).forEach((u) => { if (!this.spec.paths) return; const f = this.spec.paths[u]; f && Object.keys(this.resolve(f)).forEach((p) => { const l = p.toUpperCase(); if (!$e.includes(l)) return; const m = f[p], { operationId: g, requestBody: S, responses: N, summary: xe, description: ve, tags: Ee } = m; if (this.skip(Ee)) return; let D = De(p, u, g); const ie = s[D] = (s[D] || 0) + 1; ie > 1 && (D += ie); const B = this.resolveArray(f.parameters); for (const d of this.resolveArray(m.parameters)) B.find( (j) => j.name === d.name && j.in === d.in ) || B.push(d); const k = this.isConverted ? He(B) : B, J = /* @__PURE__ */ new Map(); T.sortBy(k, "name.length").forEach((d) => { const b = w(d.name), E = [...J.values()].includes(b) ? T.upperFirst(d.in) : ""; J.set(d, b + E); }); const A = (d) => { const b = J.get(d); if (!b) throw new Error(`Can't find parameter: ${d.name}`); return b; }, L = []; let K, v; switch (this.opts.argumentStyle ?? "positional") { case "positional": const [d, b] = T.partition(k, "required"), j = d.map( (y) => F(A(this.resolve(y)), { type: this.getTypeFromParameter(y) }) ); if (L.push(...j), S) { K = this.resolve(S); const y = this.getSchemaFromContent(K.content), I = this.getTypeFromSchema( y, void 0, "writeOnly" ); v = w( I.name || ue(y) || "body" ), L.push( F(v, { type: I, questionToken: !K.required }) ); } b.length && L.push( F( H( b.map((y) => this.resolve(y)).map((y) => ({ name: A(y) })) ), { initializer: o.createObjectLiteralExpression(), type: o.createTypeLiteralNode( b.map( (y) => x({ name: A(this.resolve(y)), questionToken: !0, type: this.getTypeFromParameter(y) }) ) ) } ) ); break; case "object": const E = k.map( (y) => x({ name: A(this.resolve(y)), questionToken: !y.required, type: this.getTypeFromParameter(y) }) ); if (S) { K = this.resolve(S); const y = this.getSchemaFromContent(K.content), I = this.getTypeFromSchema( y, void 0, "writeOnly" ); v = w( I.name || ue(y) || "body" ), E.push( x({ name: v, questionToken: !K.required, type: I }) ); } if (E.length === 0) break; L.push( F( H([ ...k.map((y) => this.resolve(y)).map((y) => ({ name: A(y) })), ...v ? [{ name: v }] : [] ]), { type: o.createTypeLiteralNode(E) } ) ); break; } L.push( F("opts", { type: o.createTypeReferenceNode( "Oazapfts.RequestOpts", void 0 ), questionToken: !0 }) ); const G = this.getResponseType(N), se = k.filter((d) => d.in === "query"), oe = k.filter((d) => d.in === "header"); let ae; if (se.length) { const d = T.groupBy(se, qe); ae = pe( "query", Object.entries(d).map(([b, j]) => pe(b, [ ee( j.map((E) => [E.name, A(E)]) ) ])) ); } const Fe = _e(u, ae), $ = [ o.createSpreadAssignment(o.createIdentifier("opts")) ]; l !== "GET" && $.push( o.createPropertyAssignment( "method", o.createStringLiteral(l) ) ), v && $.push( _( "body", o.createIdentifier(v) ) ), oe.length && $.push( o.createPropertyAssignment( "headers", z("mergeHeaders", [ o.createPropertyAccessChain( o.createIdentifier("opts"), o.createToken(c.SyntaxKind.QuestionDotToken), "headers" ), o.createObjectLiteralExpression( [ ...oe.map( (d) => _( d.name, o.createIdentifier(A(d)) ) ) ], !0 ) ]) ) ); const ce = [Fe]; if ($.length) { const d = Ue(K), b = o.createObjectLiteralExpression($, !0); ce.push( d ? z(d, [b]) : b ); } r.push( Ne( he( D, { modifiers: [P.export] }, L, ye( o.createReturnStatement( this.wrapResult( z( { json: "fetchJson", text: "fetchText", blob: "fetchBlob" }[G], ce, G === "json" || G === "blob" ? [ this.getTypeFromResponses( N, "readOnly" ) || c.SyntaxKind.AnyKeyword ] : void 0 ) ) ) ) ), xe || ve ) ); }); }), Object.assign(e, { statements: we( e.statements, ...this.aliases, ...r, ...this.enumAliases ) }), e; } } const a = c.factory, de = a.createToken(c.SyntaxKind.QuestionToken); function W(t) { if (t) return t === !0 ? de : t; } const h = { any: a.createKeywordTypeNode(c.SyntaxKind.AnyKeyword), number: a.createKeywordTypeNode(c.SyntaxKind.NumberKeyword), integer: a.createKeywordTypeNode(c.SyntaxKind.NumberKeyword), object: a.createKeywordTypeNode(c.SyntaxKind.ObjectKeyword), string: a.createKeywordTypeNode(c.SyntaxKind.StringKeyword), boolean: a.createKeywordTypeNode(c.SyntaxKind.BooleanKeyword), undefined: a.createKeywordTypeNode(c.SyntaxKind.UndefinedKeyword), void: a.createKeywordTypeNode(c.SyntaxKind.VoidKeyword), never: a.createKeywordTypeNode(c.SyntaxKind.NeverKeyword), null: a.createLiteralTypeNode(a.createNull()), unknown: a.createKeywordTypeNode(c.SyntaxKind.UnknownKeyword) }; function Qe(t) { return h[t]; } const P = { async: a.createModifier(c.SyntaxKind.AsyncKeyword), export: a.createModifier(c.SyntaxKind.ExportKeyword) }; function q(t) { switch (typeof t) { case "string": return a.createStringLiteral(t); case "boolean": return t ? a.createTrue() : a.createFalse(); case "number": return String(t).charAt(0) === "-" ? a.createPrefixUnaryExpression( c.SyntaxKind.MinusToken, a.createNumericLiteral(String(-t)) ) : a.createNumericLiteral(String(t)); } } function V(t) { const e = t.map( (n) => n === null ? h.null : a.createLiteralTypeNode(q(n)) ); return e.length > 1 ? a.createUnionTypeNode(e) : e[0]; } function M({ modifiers: t, name: e, typeParameters: n, type: i }) { return a.createTypeAliasDeclaration( t, e, n, i ); } function Je({ modifiers: t, name: e, typeParameters: n, type: i, inheritedNodeNames: r }) { const s = r ? [ a.createHeritageClause( c.SyntaxKind.ExtendsKeyword, r.map((u) => { const f = typeof u == "string" ? u : u.escapedText.toString(); return a.createExpressionWithTypeArguments( a.createIdentifier( w(f, !0) ), void 0 ); }) ) ] : []; return a.createInterfaceDeclaration( t, e, n, s, i.members ); } function X(t) { return typeof t == "string" ? a.createIdentifier(t) : t; } function C(t, { typeArgs: e, args: n } = {}) { return a.createCallExpression(X(t), e, n); } function Ge(t, e) { return C( a.createPropertyAccessExpression(a.createThis(), t), e ); } function ee(t) { return a.createObjectLiteralExpression( t.map( ([e, n]) => _(e, X(n)) ), !0 ); } function _(t, e) { return c.isIdentifier(e) && e.text === t ? a.createShorthandPropertyAssignment(t) : a.createPropertyAssignment(ge(t), e); } function ye(...t) { return a.createBlock(t, !0); } function me(t, e, { modifiers: n, typeParameters: i, type: r, equalsGreaterThanToken: s } = {}) { return a.createArrowFunction( n, i, t, r, s, e ); } function he(t, { modifiers: e, asteriskToken: n, typeParameters: i, type: r }, s, u) { return a.createFunctionDeclaration( e, n, t, i, s, r, u ); } function Ye({ modifiers: t, name: e, typeParameters: n, heritageClauses: i, members: r }) { return a.createClassDeclaration( t, e, n, i, r ); } function Ze({ modifiers: t, parameters: e, body: n }) { return a.createConstructorDeclaration(t, e, n); } function Xe(t, { modifiers: e, asteriskToken: n, questionToken: i, typeParameters: r, type: s } = {}, u = [], f) { return a.createMethodDeclaration( e, n, t, W(i), r, u, s, f ); } function F(t, { modifiers: e, dotDotDotToken: n, questionToken: i, type: r, initializer: s }) { return a.createParameterDeclaration( e, n, t, W(i), r, s ); } function ge(t) { return typeof t == "string" ? Q(t) ? a.createIdentifier(t) : a.createStringLiteral(t) : t; } function x({ modifiers: t, name: e, questionToken: n, type: i }) { return a.createPropertySignature( t, ge(e), W(n), i ); } function Te(t, { modifiers: e, indexName: n = "key", indexType: i = h.string } = {}) { return a.createIndexSignature( e, [F(n, { type: i })], t ); } function H(t) { return a.createObjectBindingPattern( t.map( ({ dotDotDotToken: e, propertyName: n, name: i, initializer: r }) => a.createBindingElement( e, n, i, r ) ) ); } function te(t, e) { return e.length ? a.createTemplateExpression( a.createTemplateHead(t), e.map( ({ expression: n, literal: i }, r) => a.createTemplateSpan( n, r === e.length - 1 ? a.createTemplateTail(i) : a.createTemplateMiddle(i) ) ) ) : a.createStringLiteral(t); } function Se(t, e, n) { const i = t.find( (r) => r.kind === e && (!n || n(r)) ); if (!i) throw new Error(`Node not found: ${e}`); return i; } function re(t) { return c.isIdentifier(t) ? t.escapedText : c.isLiteralExpression(t) ? t.text : ""; } function be(t) { const e = c.getNameOfDeclaration(t.declarationList.declarations[0]); return e ? re(e) : ""; } function Y(t, e) { const n = Se( t, c.SyntaxKind.VariableStatement, (r) => be(r) === e ), [i] = n.declarationList.declarations; if (!i) throw new Error("Missing declaration"); return i; } function Oe(t, e, n) { const i = t.properties.find( (r) => c.isPropertyAssignment(r) && re(r.name) === e ); if (i && c.isPropertyAssignment(i)) Object.assign(i, { initializer: n }); else throw new Error(`No such property: ${e}`); } function we(t, ...e) { return a.createNodeArray([...t, ...e]); } function Ne(t, e) { return e ? c.addSyntheticLeadingComment( t, c.SyntaxKind.MultiLineCommentTrivia, `* * ${e.replace(/\n/g, ` * `)} `, !0 ) : t; } const ne = c.createPrinter({ newLine: c.NewLineKind.LineFeed }); function et(t) { const e = c.createSourceFile( "someFileName.ts", "", c.ScriptTarget.Latest, /*setParentNodes*/ !1, c.ScriptKind.TS ); return ne.printNode(c.EmitHint.Unspecified, t, e); } function tt(t) { const e = c.createSourceFile( "someFileName.ts", "", c.ScriptTarget.Latest, /*setParentNodes*/ !1, c.ScriptKind.TS ); return t.map((n) => ne.printNode(c.EmitHint.Unspecified, n, e)).join(` `); } function rt(t) { return ne.printFile(t); } function Q(t) { if (!t.length || t.trim() !== t) return !1; const e = c.parseIsolatedEntityName(t, c.ScriptTarget.Latest); return !!e && e.kind === c.SyntaxKind.Identifier && c.identifierToKeywordKind(e) === void 0; } const ot = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, addComment: Ne, appendNodes: we, block: ye, changePropertyValue: Oe, createArrowFunction: me, createCall: C, createClassDeclaration: Ye, createConstructor: Ze, createEnumTypeNode: V, createFunctionDeclaration: he, createIndexSignature: Te, createInterfaceAliasDeclaration: Je, createKeywordType: Qe, createLiteral: q, createMethod: Xe, createMethodCall: Ge, createObjectBinding: H, createObjectLiteral: ee, createParameter: F, createPropertyAssignment: _, createPropertySignature: x, createQuestionToken: W, createTemplateString: te, createTypeAliasDeclaration: M, findFirstVariableDeclaration: Y, findNode: Se, getFirstDeclarationName: be, getName: re, isValidIdentifier: Q, keywordType: h, modifier: P, printFile: rt, printNode: et, printNodes: tt, questionToken: de, toExpression: X }, Symbol.toStringTag, { value: "Module" })); export { Q as $, st as A, Je as B, X as C, C as D, Ge as E, ee as F, _ as G, ye as H, me as I, he as J, Ye as K, Ze as L, Xe as M, F as N, x as O, Te as P, H as Q, te as R, Se as S, re as T, be as U, Y as V, Oe as W, we as X, Ne as Y, et as Z, tt as _, Z as a, Le as a0, qe as b, Ce as c, De as d, Be as e, O as f, Ue as g, ue as h, Ie as i, w as j, _e as k, pe as l, z as m, W as n, h as o, rt as p, de as q, le as r, He as s, ot as t, Qe as u, $e as v, P as w, q as x, V as y, M as z }; //# sourceMappingURL=tscodegen-BjtNU8_R.js.map