UNPKG

@s3pweb/keycloak-admin-client-cjs

Version:
1,448 lines (1,415 loc) 333 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // node_modules/tinyduration/dist/index.js var require_dist = __commonJS({ "node_modules/tinyduration/dist/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.serialize = exports2.parse = exports2.MultipleFractionsError = exports2.InvalidDurationError = void 0; var DEFAULT_PARSE_CONFIG = { allowMultipleFractions: true }; var units = [ { unit: "years", symbol: "Y" }, { unit: "months", symbol: "M" }, { unit: "weeks", symbol: "W" }, { unit: "days", symbol: "D" }, { unit: "hours", symbol: "H" }, { unit: "minutes", symbol: "M" }, { unit: "seconds", symbol: "S" } ]; var r = (name, unit) => `((?<${name}>-?\\d*[\\.,]?\\d+)${unit})?`; var durationRegex = new RegExp([ "(?<negative>-)?P", r("years", "Y"), r("months", "M"), r("weeks", "W"), r("days", "D"), "(T", r("hours", "H"), r("minutes", "M"), r("seconds", "S"), ")?" // end optional time ].join("")); function parseNum(s2) { if (s2 === "" || s2 === void 0 || s2 === null) { return void 0; } return parseFloat(s2.replace(",", ".")); } exports2.InvalidDurationError = new Error("Invalid duration"); exports2.MultipleFractionsError = new Error("Multiple fractions specified"); function parse(durationStr, config = DEFAULT_PARSE_CONFIG) { const match = durationRegex.exec(durationStr); if (!match || !match.groups) { throw exports2.InvalidDurationError; } let empty = true; let decimalFractionCount = 0; const values = {}; for (const { unit } of units) { if (match.groups[unit]) { empty = false; values[unit] = parseNum(match.groups[unit]); if (!config.allowMultipleFractions && !Number.isInteger(values[unit])) { decimalFractionCount++; if (decimalFractionCount > 1) { throw exports2.MultipleFractionsError; } } } } if (empty) { throw exports2.InvalidDurationError; } const duration = values; if (match.groups.negative) { duration.negative = true; } return duration; } exports2.parse = parse; var s = (number, component) => { if (!number) { return void 0; } let numberAsString = number.toString(); const exponentIndex = numberAsString.indexOf("e"); if (exponentIndex > -1) { const magnitude = parseInt(numberAsString.slice(exponentIndex + 2), 10); numberAsString = number.toFixed(magnitude + exponentIndex - 2); } return numberAsString + component; }; function serialize(duration) { if (!duration.years && !duration.months && !duration.weeks && !duration.days && !duration.hours && !duration.minutes && !duration.seconds) { return "PT0S"; } return [ duration.negative && "-", "P", s(duration.years, "Y"), s(duration.months, "M"), s(duration.weeks, "W"), s(duration.days, "D"), (duration.hours || duration.minutes || duration.seconds) && "T", s(duration.hours, "H"), s(duration.minutes, "M"), s(duration.seconds, "S") ].filter(Boolean).join(""); } exports2.serialize = serialize; } }); // dist/index.d.ts var index_d_exports = {}; __export(index_d_exports, { KeycloakAdminClient: () => lib_default, RequiredActionAlias: () => RequiredActionAlias }); module.exports = __toCommonJS(index_d_exports); // node_modules/url-template/lib/url-template.js function encodeReserved(str) { return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { if (!/%[0-9A-Fa-f]/.test(part)) { part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); } return part; }).join(""); } function encodeUnreserved(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return "%" + c.charCodeAt(0).toString(16).toUpperCase(); }); } function encodeValue(operator, value, key) { value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); if (key) { return encodeUnreserved(key) + "=" + value; } else { return value; } } function isDefined(value) { return value !== void 0 && value !== null; } function isKeyOperator(operator) { return operator === ";" || operator === "&" || operator === "?"; } function getValues(context, operator, key, modifier) { var value = context[key], result = []; if (isDefined(value) && value !== "") { if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { value = value.toString(); if (modifier && modifier !== "*") { value = value.substring(0, parseInt(modifier, 10)); } result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null)); } else { if (modifier === "*") { if (Array.isArray(value)) { value.filter(isDefined).forEach(function(value2) { result.push(encodeValue(operator, value2, isKeyOperator(operator) ? key : null)); }); } else { Object.keys(value).forEach(function(k) { if (isDefined(value[k])) { result.push(encodeValue(operator, value[k], k)); } }); } } else { var tmp = []; if (Array.isArray(value)) { value.filter(isDefined).forEach(function(value2) { tmp.push(encodeValue(operator, value2)); }); } else { Object.keys(value).forEach(function(k) { if (isDefined(value[k])) { tmp.push(encodeUnreserved(k)); tmp.push(encodeValue(operator, value[k].toString())); } }); } if (isKeyOperator(operator)) { result.push(encodeUnreserved(key) + "=" + tmp.join(",")); } else if (tmp.length !== 0) { result.push(tmp.join(",")); } } } } else { if (operator === ";") { if (isDefined(value)) { result.push(encodeUnreserved(key)); } } else if (value === "" && (operator === "&" || operator === "?")) { result.push(encodeUnreserved(key) + "="); } else if (value === "") { result.push(""); } } return result; } function parseTemplate(template) { var operators = ["+", "#", ".", "/", ";", "?", "&"]; return { expand: function(context) { return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function(_, expression, literal) { if (expression) { var operator = null, values = []; if (operators.indexOf(expression.charAt(0)) !== -1) { operator = expression.charAt(0); expression = expression.substr(1); } expression.split(/,/g).forEach(function(variable) { var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); values.push.apply(values, getValues(context, operator, tmp[1], tmp[2] || tmp[3])); }); if (operator && operator !== "+") { var separator = ","; if (operator === "?") { separator = "&"; } else if (operator !== "#") { separator = operator; } return (values.length !== 0 ? operator : "") + values.join(separator); } else { return values.join(","); } } else { return encodeReserved(literal); } }); } }; } // node_modules/@keycloak/keycloak-admin-client/lib/utils/fetchWithError.js var ERROR_FIELDS = ["error", "errorMessage"]; var NetworkError = class extends Error { response; responseData; constructor(message, options) { super(message); this.response = options.response; this.responseData = options.responseData; } }; async function fetchWithError(input, init) { const response = await fetch(input, init); if (!response.ok) { const responseData = await parseResponse(response); const message = getErrorMessage(responseData); console.error(message, response.status, responseData); throw new NetworkError(message, { response, responseData }); } return response; } async function parseResponse(response) { if (!response.body) { return ""; } const data = await response.text(); try { return JSON.parse(data); } catch { return data; } } function getErrorMessage(data) { if (typeof data !== "object" || data === null) { return "Unable to determine error message."; } for (const key of ERROR_FIELDS) { const value = data[key]; if (typeof value === "string") { return value; } } return "Network response was not OK."; } // node_modules/@keycloak/keycloak-admin-client/lib/utils/joinPath.js var PATH_SEPARATOR = "/"; function joinPath(...paths) { const normalizedPaths = paths.map((path, index) => { const isFirst = index === 0; const isLast = index === paths.length - 1; if (!isFirst && path.startsWith(PATH_SEPARATOR)) { path = path.slice(1); } if (!isLast && path.endsWith(PATH_SEPARATOR)) { path = path.slice(0, -1); } return path; }, []); return normalizedPaths.join(PATH_SEPARATOR); } // node_modules/@keycloak/keycloak-admin-client/lib/utils/stringifyQueryParams.js function stringifyQueryParams(params) { const searchParams = new URLSearchParams(); for (const [key, value] of Object.entries(params)) { if (value === void 0 || value === null) { continue; } if (typeof value === "string" && value.length === 0) { continue; } if (Array.isArray(value) && value.length === 0) { continue; } if (Array.isArray(value)) { value.forEach((item) => searchParams.append(key, item.toString())); } else { searchParams.append(key, value.toString()); } } return searchParams.toString(); } // node_modules/@keycloak/keycloak-admin-client/lib/resources/agent.js var SLASH = "/"; var pick = (value, keys) => Object.fromEntries(Object.entries(value).filter(([key]) => keys.includes(key))); var omit = (value, keys) => Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key))); var Agent = class { #client; #basePath; #getBaseParams; #getBaseUrl; constructor({ client, path = "/", getUrlParams = () => ({}), getBaseUrl = () => client.baseUrl }) { this.#client = client; this.#getBaseParams = getUrlParams; this.#getBaseUrl = getBaseUrl; this.#basePath = path; } request({ method, path = "", urlParamKeys = [], queryParamKeys = [], catchNotFound = false, keyTransform, payloadKey, returnResourceIdInLocationHeader, ignoredKeys, headers }) { return async (payload = {}, options) => { const baseParams = this.#getBaseParams?.() ?? {}; const queryParams = queryParamKeys.length > 0 ? pick(payload, queryParamKeys) : void 0; const allUrlParamKeys = [...Object.keys(baseParams), ...urlParamKeys]; const urlParams = { ...baseParams, ...pick(payload, allUrlParamKeys) }; if (!(payload instanceof FormData)) { const omittedKeys = ignoredKeys ? [...allUrlParamKeys, ...queryParamKeys].filter((key) => !ignoredKeys.includes(key)) : [...allUrlParamKeys, ...queryParamKeys]; payload = omit(payload, omittedKeys); } if (keyTransform) { this.#transformKey(payload, keyTransform); this.#transformKey(queryParams, keyTransform); } return this.#requestWithParams({ method, path, payload, urlParams, queryParams, // catchNotFound precedence: global > local > default catchNotFound, ...this.#client.getGlobalRequestArgOptions() ?? options ?? {}, payloadKey, returnResourceIdInLocationHeader, headers }); }; } updateRequest({ method, path = "", urlParamKeys = [], queryParamKeys = [], catchNotFound = false, keyTransform, payloadKey, returnResourceIdInLocationHeader, headers }) { return async (query = {}, payload = {}) => { const baseParams = this.#getBaseParams?.() ?? {}; const queryParams = queryParamKeys ? pick(query, queryParamKeys) : void 0; const allUrlParamKeys = [...Object.keys(baseParams), ...urlParamKeys]; const urlParams = { ...baseParams, ...pick(query, allUrlParamKeys) }; if (keyTransform) { this.#transformKey(queryParams, keyTransform); } return this.#requestWithParams({ method, path, payload, urlParams, queryParams, catchNotFound, payloadKey, returnResourceIdInLocationHeader, headers }); }; } async #requestWithParams({ method, path, payload, urlParams, queryParams, catchNotFound, payloadKey, returnResourceIdInLocationHeader, headers }) { const requestOptions = { ...this.#client.getRequestOptions() }; const requestHeaders = new Headers([ ...new Headers(requestOptions.headers).entries(), ["authorization", `Bearer ${await this.#client.getAccessToken()}`], ["accept", "application/json, text/plain, */*"], ...new Headers(headers).entries() ]); const searchParams = {}; if (method === "GET") { Object.assign(searchParams, payload); } else if (requestHeaders.get("content-type") === "text/plain") { requestOptions.body = payload; } else if (payload instanceof FormData) { requestOptions.body = payload; } else { requestOptions.body = payloadKey && typeof payload[payloadKey] === "string" ? payload[payloadKey] : JSON.stringify(payloadKey ? payload[payloadKey] : payload); } if (requestOptions.body && !requestHeaders.has("content-type") && !(payload instanceof FormData)) { requestHeaders.set("content-type", "application/json"); } if (queryParams) { Object.assign(searchParams, queryParams); } const url = new URL(this.#getBaseUrl()); const pathTemplate = parseTemplate(joinPath(this.#basePath, path)); url.pathname = joinPath(url.pathname, pathTemplate.expand(urlParams)); url.search = stringifyQueryParams(searchParams); try { const res = await fetchWithError(url, { ...requestOptions, headers: requestHeaders, method, ...this.#client.timeout ? { signal: AbortSignal.timeout(this.#client.timeout) } : {} }); if (returnResourceIdInLocationHeader) { const locationHeader = res.headers.get("location"); if (typeof locationHeader !== "string") { throw new Error(`location header is not found in request: ${res.url}`); } const resourceId = locationHeader.split(SLASH).pop(); if (!resourceId) { throw new Error(`resourceId is not found in Location header from request: ${res.url}`); } const { field } = returnResourceIdInLocationHeader; return { [field]: resourceId }; } if (Object.entries(headers || []).find(([key, value]) => key.toLowerCase() === "accept" && value === "application/octet-stream")) { return await res.arrayBuffer(); } return await parseResponse(res); } catch (err) { if (err instanceof NetworkError && err.response.status === 404 && catchNotFound) { return null; } throw err; } } #transformKey(payload, keyMapping) { if (!payload) { return; } Object.keys(keyMapping).some((key) => { if (typeof payload[key] === "undefined") { return false; } const newKey = keyMapping[key]; payload[newKey] = payload[key]; delete payload[key]; }); } }; // node_modules/@keycloak/keycloak-admin-client/lib/resources/resource.js var Resource = class { #agent; constructor(client, settings = {}) { this.#agent = new Agent({ client, ...settings }); } makeRequest = (args) => { return this.#agent.request(args); }; // update request will take three types: query, payload and response makeUpdateRequest = (args) => { return this.#agent.updateRequest(args); }; }; // node_modules/@keycloak/keycloak-admin-client/lib/resources/attackDetection.js var AttackDetection = class extends Resource { findOne = this.makeRequest({ method: "GET", path: "/users/{id}", urlParamKeys: ["id"], catchNotFound: true }); del = this.makeRequest({ method: "DELETE", path: "/users/{id}", urlParamKeys: ["id"] }); delAll = this.makeRequest({ method: "DELETE", path: "/users" }); constructor(client) { super(client, { path: "/admin/realms/{realm}/attack-detection/brute-force", getUrlParams: () => ({ realm: client.realmName }), getBaseUrl: () => client.baseUrl }); } }; // node_modules/@keycloak/keycloak-admin-client/lib/resources/authenticationManagement.js var AuthenticationManagement = class extends Resource { /** * Authentication Management * https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_authentication_management_resource */ // Register a new required action registerRequiredAction = this.makeRequest({ method: "POST", path: "/register-required-action" }); // Get required actions. Returns a list of required actions. getRequiredActions = this.makeRequest({ method: "GET", path: "/required-actions" }); // Get required action for alias getRequiredActionForAlias = this.makeRequest({ method: "GET", path: "/required-actions/{alias}", urlParamKeys: ["alias"], catchNotFound: true }); getClientAuthenticatorProviders = this.makeRequest({ method: "GET", path: "/client-authenticator-providers" }); getAuthenticatorProviders = this.makeRequest({ method: "GET", path: "/authenticator-providers" }); getFormActionProviders = this.makeRequest({ method: "GET", path: "/form-action-providers" }); // Update required action updateRequiredAction = this.makeUpdateRequest({ method: "PUT", path: "/required-actions/{alias}", urlParamKeys: ["alias"] }); // Delete required action deleteRequiredAction = this.makeRequest({ method: "DELETE", path: "/required-actions/{alias}", urlParamKeys: ["alias"] }); // Lower required action’s priority lowerRequiredActionPriority = this.makeRequest({ method: "POST", path: "/required-actions/{alias}/lower-priority", urlParamKeys: ["alias"] }); // Raise required action’s priority raiseRequiredActionPriority = this.makeRequest({ method: "POST", path: "/required-actions/{alias}/raise-priority", urlParamKeys: ["alias"] }); // Get unregistered required actions Returns a list of unregistered required actions. getUnregisteredRequiredActions = this.makeRequest({ method: "GET", path: "/unregistered-required-actions" }); getFlows = this.makeRequest({ method: "GET", path: "/flows" }); getFlow = this.makeRequest({ method: "GET", path: "/flows/{flowId}", urlParamKeys: ["flowId"] }); getFormProviders = this.makeRequest({ method: "GET", path: "/form-providers" }); createFlow = this.makeRequest({ method: "POST", path: "/flows", returnResourceIdInLocationHeader: { field: "id" } }); copyFlow = this.makeRequest({ method: "POST", path: "/flows/{flow}/copy", urlParamKeys: ["flow"] }); deleteFlow = this.makeRequest({ method: "DELETE", path: "/flows/{flowId}", urlParamKeys: ["flowId"] }); updateFlow = this.makeUpdateRequest({ method: "PUT", path: "/flows/{flowId}", urlParamKeys: ["flowId"] }); getExecutions = this.makeRequest({ method: "GET", path: "/flows/{flow}/executions", urlParamKeys: ["flow"] }); addExecution = this.makeUpdateRequest({ method: "POST", path: "/flows/{flow}/executions", urlParamKeys: ["flow"] }); addExecutionToFlow = this.makeRequest({ method: "POST", path: "/flows/{flow}/executions/execution", urlParamKeys: ["flow"], returnResourceIdInLocationHeader: { field: "id" } }); addFlowToFlow = this.makeRequest({ method: "POST", path: "/flows/{flow}/executions/flow", urlParamKeys: ["flow"], returnResourceIdInLocationHeader: { field: "id" } }); updateExecution = this.makeUpdateRequest({ method: "PUT", path: "/flows/{flow}/executions", urlParamKeys: ["flow"] }); delExecution = this.makeRequest({ method: "DELETE", path: "/executions/{id}", urlParamKeys: ["id"] }); lowerPriorityExecution = this.makeRequest({ method: "POST", path: "/executions/{id}/lower-priority", urlParamKeys: ["id"] }); raisePriorityExecution = this.makeRequest({ method: "POST", path: "/executions/{id}/raise-priority", urlParamKeys: ["id"] }); // Get required actions provider's configuration description getRequiredActionConfigDescription = this.makeRequest({ method: "GET", path: "/required-actions/{alias}/config-description", urlParamKeys: ["alias"] }); // Get the configuration of the RequiredAction provider in the current Realm. getRequiredActionConfig = this.makeRequest({ method: "GET", path: "/required-actions/{alias}/config", urlParamKeys: ["alias"] }); // Remove the configuration from the RequiredAction provider in the current Realm. removeRequiredActionConfig = this.makeRequest({ method: "DELETE", path: "/required-actions/{alias}/config", urlParamKeys: ["alias"] }); // Update the configuration from the RequiredAction provider in the current Realm. updateRequiredActionConfig = this.makeUpdateRequest({ method: "PUT", path: "/required-actions/{alias}/config", urlParamKeys: ["alias"] }); getConfigDescription = this.makeRequest({ method: "GET", path: "config-description/{providerId}", urlParamKeys: ["providerId"] }); createConfig = this.makeRequest({ method: "POST", path: "/executions/{id}/config", urlParamKeys: ["id"], returnResourceIdInLocationHeader: { field: "id" } }); updateConfig = this.makeRequest({ method: "PUT", path: "/config/{id}", urlParamKeys: ["id"] }); getConfig = this.makeRequest({ method: "GET", path: "/config/{id}", urlParamKeys: ["id"] }); delConfig = this.makeRequest({ method: "DELETE", path: "/config/{id}", urlParamKeys: ["id"] }); constructor(client) { super(client, { path: "/admin/realms/{realm}/authentication", getUrlParams: () => ({ realm: client.realmName }), getBaseUrl: () => client.baseUrl }); } }; // node_modules/@keycloak/keycloak-admin-client/lib/resources/cache.js var Cache = class extends Resource { clearUserCache = this.makeRequest({ method: "POST", path: "/clear-user-cache" }); clearKeysCache = this.makeRequest({ method: "POST", path: "/clear-keys-cache" }); clearCrlCache = this.makeRequest({ method: "POST", path: "/clear-crl-cache" }); clearRealmCache = this.makeRequest({ method: "POST", path: "/clear-realm-cache" }); constructor(client) { super(client, { path: "/admin/realms/{realm}", getUrlParams: () => ({ realm: client.realmName }), getBaseUrl: () => client.baseUrl }); } }; // node_modules/@keycloak/keycloak-admin-client/lib/resources/clientPolicies.js var ClientPolicies = class extends Resource { constructor(client) { super(client, { path: "/admin/realms/{realm}/client-policies", getUrlParams: () => ({ realm: client.realmName }), getBaseUrl: () => client.baseUrl }); } /* Client Profiles */ listProfiles = this.makeRequest({ method: "GET", path: "/profiles", queryParamKeys: ["include-global-profiles"], keyTransform: { includeGlobalProfiles: "include-global-profiles" } }); createProfiles = this.makeRequest({ method: "PUT", path: "/profiles" }); /* Client Policies */ listPolicies = this.makeRequest({ method: "GET", path: "/policies", queryParamKeys: ["include-global-policies"], keyTransform: { includeGlobalPolicies: "include-global-policies" } }); updatePolicy = this.makeRequest({ method: "PUT", path: "/policies" }); }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/parseNodeFactoryRegistry.js var ParseNodeFactoryRegistry = class { constructor() { this.jsonContentType = "application/json"; this.contentTypeAssociatedFactories = /* @__PURE__ */ new Map(); } getValidContentType() { throw new Error("The registry supports multiple content types. Get the registered factory instead."); } /** * Creates a {@link ParseNode} from the given {@link ArrayBuffer} and content type. * @param contentType the content type of the {@link ArrayBuffer}. * @param content the {@link ArrayBuffer} to read from. * @returns a {@link ParseNode} that can deserialize the given {@link ArrayBuffer}. */ getRootParseNode(contentType, content) { if (!contentType) { throw new Error("content type cannot be undefined or empty"); } if (!content) { throw new Error("content cannot be undefined or empty"); } const vendorSpecificContentType = contentType.split(";")[0]; let factory = this.contentTypeAssociatedFactories.get(vendorSpecificContentType); if (factory) { return factory.getRootParseNode(vendorSpecificContentType, content); } const cleanedContentType = vendorSpecificContentType.replace(/[^/]+\+/gi, ""); factory = this.contentTypeAssociatedFactories.get(cleanedContentType); if (factory) { return factory.getRootParseNode(cleanedContentType, content); } throw new Error(`Content type ${cleanedContentType} does not have a factory registered to be parsed`); } /** * Registers the default deserializer to the registry. * @param type the class of the factory to be registered. * @param backingStoreFactory The backing store factory to use. */ registerDefaultDeserializer(type, backingStoreFactory) { if (!type) throw new Error("Type is required"); const deserializer = new type(backingStoreFactory); this.contentTypeAssociatedFactories.set(deserializer.getValidContentType(), deserializer); } /** * Deserializes a buffer into a parsable object * @param bufferOrString the value to serialize * @param factory the factory for the model type * @returns the deserialized parsable object */ deserializeFromJson(bufferOrString, factory) { return this.deserialize(this.jsonContentType, bufferOrString, factory); } /** * Deserializes a buffer into a collection of parsable object * @param bufferOrString the value to serialize * @param factory the factory for the model type * @returns the deserialized collection of parsable objects */ deserializeCollectionFromJson(bufferOrString, factory) { return this.deserializeCollection(this.jsonContentType, bufferOrString, factory); } /** * Deserializes a buffer into a parsable object * @param contentType the content type to serialize to * @param bufferOrString the value to serialize * @param factory the factory for the model type * @returns the deserialized parsable object */ deserialize(contentType, bufferOrString, factory) { if (typeof bufferOrString === "string") { bufferOrString = this.getBufferFromString(bufferOrString); } const reader = this.getParseNode(contentType, bufferOrString, factory); return reader.getObjectValue(factory); } /** * Deserializes a buffer into a parsable object * @param contentType the content type to serialize to * @param buffer the value to deserialize * @param factory the factory for the model type * @returns the deserialized parsable object */ getParseNode(contentType, buffer, factory) { if (!contentType) { throw new Error("content type cannot be undefined or empty"); } if (!buffer) { throw new Error("buffer cannot be undefined"); } if (!factory) { throw new Error("factory cannot be undefined"); } return this.getRootParseNode(contentType, buffer); } /** * Deserializes a buffer into a collection of parsable object * @param contentType the content type to serialize to * @param bufferOrString the value to serialize * @param factory the factory for the model type * @returns the deserialized collection of parsable objects */ deserializeCollection(contentType, bufferOrString, factory) { if (typeof bufferOrString === "string") { bufferOrString = this.getBufferFromString(bufferOrString); } const reader = this.getParseNode(contentType, bufferOrString, factory); return reader.getCollectionOfObjectValues(factory); } /** * Deserializes a buffer into a a collection of parsable object * @param value the string to get a buffer from * @returns the ArrayBuffer representation of the string */ getBufferFromString(value) { const encoder = new TextEncoder(); return encoder.encode(value).buffer; } }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/parseNodeProxyFactory.js var ParseNodeProxyFactory = class { getValidContentType() { return this._concrete.getValidContentType(); } /** * Creates a new proxy factory that wraps the specified concrete factory while composing the before and after callbacks. * @param _concrete the concrete factory to wrap * @param _onBefore the callback to invoke before the deserialization of any model object. * @param _onAfter the callback to invoke after the deserialization of any model object. */ constructor(_concrete, _onBefore, _onAfter) { this._concrete = _concrete; this._onBefore = _onBefore; this._onAfter = _onAfter; if (!_concrete) { throw new Error("_concrete cannot be undefined"); } } getRootParseNode(contentType, content) { const node = this._concrete.getRootParseNode(contentType, content); const originalBefore = node.onBeforeAssignFieldValues; const originalAfter = node.onAfterAssignFieldValues; node.onBeforeAssignFieldValues = (value) => { if (this._onBefore) this._onBefore(value); if (originalBefore) originalBefore(value); }; node.onAfterAssignFieldValues = (value) => { if (this._onAfter) this._onAfter(value); if (originalAfter) originalAfter(value); }; return node; } }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/serializationWriterFactoryRegistry.js var SerializationWriterFactoryRegistry = class { constructor() { this.jsonContentType = "application/json"; this.contentTypeAssociatedFactories = /* @__PURE__ */ new Map(); } getValidContentType() { throw new Error("The registry supports multiple content types. Get the registered factory instead."); } getSerializationWriter(contentType) { if (!contentType) { throw new Error("content type cannot be undefined or empty"); } const vendorSpecificContentType = contentType.split(";")[0]; let factory = this.contentTypeAssociatedFactories.get(vendorSpecificContentType); if (factory) { return factory.getSerializationWriter(vendorSpecificContentType); } const cleanedContentType = vendorSpecificContentType.replace(/[^/]+\+/gi, ""); factory = this.contentTypeAssociatedFactories.get(cleanedContentType); if (factory) { return factory.getSerializationWriter(cleanedContentType); } throw new Error(`Content type ${cleanedContentType} does not have a factory registered to be serialized`); } /** * Registers the default serializer to the registry. * @param type the class of the factory to be registered. */ registerDefaultSerializer(type) { if (!type) throw new Error("Type is required"); const serializer = new type(); this.contentTypeAssociatedFactories.set(serializer.getValidContentType(), serializer); } /** * Serializes a parsable object into a buffer * @param value the value to serialize * @param serializationFunction the serialization function for the model type * @returns a buffer containing the serialized value */ serializeToJson(value, serializationFunction) { return this.serialize(this.jsonContentType, value, serializationFunction); } /** * Serializes a parsable object into a string representation * @param value the value to serialize * @param serializationFunction the serialization function for the model type * @returns a string representing the serialized value */ serializeToJsonAsString(value, serializationFunction) { return this.serializeToString(this.jsonContentType, value, serializationFunction); } /** * Serializes a collection of parsable objects into a buffer * @param values the value to serialize * @param serializationFunction the serialization function for the model type * @returns a string representing the serialized value */ serializeCollectionToJson(values, serializationFunction) { return this.serializeCollection(this.jsonContentType, values, serializationFunction); } /** * Serializes a collection of parsable objects into a string representation * @param values the value to serialize * @param serializationFunction the serialization function for the model type * @returns a string representing the serialized value */ serializeCollectionToJsonAsString(values, serializationFunction) { return this.serializeCollectionToString(this.jsonContentType, values, serializationFunction); } /** * Serializes a parsable object into a buffer * @param contentType the content type to serialize to * @param value the value to serialize * @param serializationFunction the serialization function for the model type * @returns a buffer containing the serialized value */ serialize(contentType, value, serializationFunction) { const writer = this.getSerializationFactoryWriter(contentType, value, serializationFunction); writer.writeObjectValue(void 0, value, serializationFunction); return writer.getSerializedContent(); } /** * Serializes a parsable object into a string representation * @param contentType the content type to serialize to * @param value the value to serialize * @param serializationFunction the serialization function for the model type * @returns a string representing the serialized value */ serializeToString(contentType, value, serializationFunction) { const buffer = this.serialize(contentType, value, serializationFunction); return this.getStringValueFromBuffer(buffer); } /** * Serializes a collection of parsable objects into a buffer * @param contentType the content type to serialize to * @param values the value to serialize * @param serializationFunction the serialization function for the model type * @returns a string representing the serialized value */ serializeCollection(contentType, values, serializationFunction) { const writer = this.getSerializationFactoryWriter(contentType, values, serializationFunction); writer.writeCollectionOfObjectValues(void 0, values, serializationFunction); return writer.getSerializedContent(); } /** * Serializes a collection of parsable objects into a string representation * @param contentType the content type to serialize to * @param values the value to serialize * @param serializationFunction the serialization function for the model type * @returns a string representing the serialized value */ serializeCollectionToString(contentType, values, serializationFunction) { const buffer = this.serializeCollection(contentType, values, serializationFunction); return this.getStringValueFromBuffer(buffer); } /** * Gets a serialization writer for a given content type * @param contentType the content type to serialize to * @param value the value to serialize * @param serializationFunction the serialization function for the model type * @returns the serialization writer for the given content type */ getSerializationFactoryWriter(contentType, value, serializationFunction) { if (!contentType) { throw new Error("content type cannot be undefined or empty"); } if (!value) { throw new Error("value cannot be undefined"); } if (!serializationFunction) { throw new Error("serializationFunction cannot be undefined"); } return this.getSerializationWriter(contentType); } /** * Gets a string value from a buffer * @param buffer the buffer to get a string from * @returns the string representation of the buffer */ getStringValueFromBuffer(buffer) { const decoder = new TextDecoder(); return decoder.decode(buffer); } }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/serializationWriterProxyFactory.js var SerializationWriterProxyFactory = class { getValidContentType() { return this._concrete.getValidContentType(); } /** * Creates a new proxy factory that wraps the specified concrete factory while composing the before and after callbacks. * @param _concrete the concrete factory to wrap * @param _onBefore the callback to invoke before the serialization of any model object. * @param _onAfter the callback to invoke after the serialization of any model object. * @param _onStart the callback to invoke when the serialization of a model object starts */ constructor(_concrete, _onBefore, _onAfter, _onStart) { this._concrete = _concrete; this._onBefore = _onBefore; this._onAfter = _onAfter; this._onStart = _onStart; if (!_concrete) { throw new Error("_concrete cannot be undefined"); } } getSerializationWriter(contentType) { const writer = this._concrete.getSerializationWriter(contentType); const originalBefore = writer.onBeforeObjectSerialization; const originalAfter = writer.onAfterObjectSerialization; const originalStart = writer.onStartObjectSerialization; writer.onBeforeObjectSerialization = (value) => { if (this._onBefore) this._onBefore(value); if (originalBefore) originalBefore(value); }; writer.onAfterObjectSerialization = (value) => { if (this._onAfter) this._onAfter(value); if (originalAfter) originalAfter(value); }; writer.onStartObjectSerialization = (value, writer_) => { if (this._onStart) this._onStart(value, writer_); if (originalStart) originalStart(value, writer_); }; return writer; } }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/untypedNode.js var createUntypedNodeFromDiscriminatorValue = (_parseNode) => { return deserializeIntoUntypedNode; }; var isUntypedNode = (node) => { const potentialNode = node; return (potentialNode === null || potentialNode === void 0 ? void 0 : potentialNode.getValue) !== void 0; }; var deserializeIntoUntypedNode = (untypedNode = {}) => { return { value: (_n) => { untypedNode.value = null; }, getValue: (_n) => { untypedNode.getValue = () => untypedNode.value; } }; }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/untypedNumber.js function isUntypedNumber(node) { const proposedNode = node; return proposedNode && typeof proposedNode.value === "number"; } function createUntypedNumber(value) { return { value, getValue: () => value }; } // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/untypedArray.js var isUntypedArray = (node) => { const proposedNode = node; return proposedNode && proposedNode.value instanceof Array && proposedNode.value.every((item) => isUntypedNode(item)); }; var createUntypedArray = (value) => { return { value, getValue: () => value }; }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/untypedNull.js function isUntypedNull(node) { return node.value === null; } function createUntypedNull() { return { value: null, getValue: () => null }; } // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/untypedObject.js var isUntypedObject = (node) => { const proposedNode = node; return proposedNode && proposedNode.value instanceof Object && proposedNode.value instanceof Array === false && Object.values(proposedNode.value).every((item) => isUntypedNode(item)); }; var createUntypedObject = (value) => { return { value, getValue: () => value }; }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/untypedString.js function isUntypedString(node) { const proposedNode = node; return proposedNode && typeof proposedNode.value === "string"; } function createUntypedString(value) { return { value, getValue: () => value }; } // node_modules/@microsoft/kiota-abstractions/dist/es/src/serialization/untypedBoolean.js function isUntypedBoolean(node) { const proposedNode = node; return proposedNode && typeof proposedNode.value === "boolean"; } function createUntypedBoolean(value) { return { value, getValue: () => value }; } // node_modules/@microsoft/kiota-abstractions/dist/es/src/store/backingStoreParseNodeFactory.js var BackingStoreParseNodeFactory = class extends ParseNodeProxyFactory { /** * Initializes a new instance of the BackingStoreParseNodeFactory class given the concrete implementation. * @param concrete the concrete implementation of the ParseNodeFactory */ constructor(concrete) { super(concrete, (value) => { const backedModel = value; if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) { backedModel.backingStore.initializationCompleted = false; } }, (value) => { const backedModel = value; if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) { backedModel.backingStore.initializationCompleted = true; } }); } }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/store/backingStoreSerializationWriterProxyFactory.js var BackingStoreSerializationWriterProxyFactory = class extends SerializationWriterProxyFactory { /** * Initializes a new instance of the BackingStoreSerializationWriterProxyFactory class given a concrete implementation of SerializationWriterFactory. * @param concrete a concrete implementation of SerializationWriterFactory to wrap. */ constructor(concrete) { super(concrete, (value) => { const backedModel = value; if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) { backedModel.backingStore.returnOnlyChangedValues = true; } }, (value) => { const backedModel = value; if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) { backedModel.backingStore.returnOnlyChangedValues = false; backedModel.backingStore.initializationCompleted = true; } }, (value, writer) => { const backedModel = value; if (backedModel === null || backedModel === void 0 ? void 0 : backedModel.backingStore) { const keys = backedModel.backingStore.enumerateKeysForValuesChangedToNull(); for (const key of keys) { writer.writeNullValue(key); } } }); } }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/utils/enumUtils.js var reverseRecord = (input) => { const entries = Object.entries(input).map(([key, value]) => [value, key]); return Object.fromEntries(entries); }; var getEnumValueFromStringValue = (stringValue, originalType) => { const reversed = reverseRecord(originalType); return originalType[reversed[stringValue]]; }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/utils/guidUtils.js var guidValidator = /^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$/i; var parseGuidString = (source) => { if (source && guidValidator.test(source)) { return source; } return void 0; }; var createGuid = () => [gen(2), gen(1), gen(1), gen(1), gen(3)].join("-"); var gen = (count) => { let out = ""; for (let i = 0; i < count; i++) { out += ((1 + Math.random()) * 65536 | 0).toString(16).substring(1); } return out; }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/utils/inNodeEnv.js var inNodeEnv = () => { try { return !!Buffer && !!process; } catch (err) { return !(err instanceof ReferenceError); } }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/store/inMemoryBackingStore.js var InMemoryBackingStore = class { constructor() { this.subscriptions = /* @__PURE__ */ new Map(); this.store = /* @__PURE__ */ new Map(); this.returnOnlyChangedValues = false; this._initializationCompleted = true; } get(key) { const wrapper = this.store.get(key); if (wrapper && (this.returnOnlyChangedValues && wrapper.changed || !this.returnOnlyChangedValues)) { return wrapper.value; } return void 0; } set(key, value) { const oldValueWrapper = this.store.get(key); const oldValue = oldValueWrapper === null || oldValueWrapper === void 0 ? void 0 : oldValueWrapper.value; if (oldValueWrapper) { oldValueWrapper.value = value; oldValueWrapper.changed = this.initializationCompleted; } else { this.store.set(key, { changed: this.initializationCompleted, value }); } this.subscriptions.forEach((sub) => { sub(key, oldValue, value); }); } enumerate() { let filterableArray = [...this.store.entries()]; if (this.returnOnlyChangedValues) { filterableArray = filterableArray.filter(([_, v]) => v.changed); } return filterableArray.map(([key, value]) => { return { key, value }; }); } enumerateKeysForValuesChangedToNull() { const keys = []; for (const [key, entry] of this.store) { if (entry.changed && !entry.value) { keys.push(key); } } return keys; } subscribe(callback, subscriptionId) { if (!callback) { throw new Error("callback cannot be undefined"); } subscriptionId = subscriptionId !== null && subscriptionId !== void 0 ? subscriptionId : createGuid(); this.subscriptions.set(subscriptionId, callback); return subscriptionId; } unsubscribe(subscriptionId) { this.subscriptions.delete(subscriptionId); } clear() { this.store.clear(); } set initializationCompleted(value) { this._initializationCompleted = value; this.store.forEach((v) => { v.changed = !value; }); } get initializationCompleted() { return this._initializationCompleted; } }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/store/inMemoryBackingStoreFactory.js var InMemoryBackingStoreFactory = class { createBackingStore() { return new InMemoryBackingStore(); } }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/store/backedModelProxy.js var createBackedModelProxyHandler = (backingStoreFactory) => { const backingStore = backingStoreFactory.createBackingStore(); const handler = { get: (_target, prop) => { if (prop === "backingStore") { return backingStore; } return backingStore.get(prop.toString()); }, set: (target, prop, value, receiver) => { if (prop === "backingStore") { console.warn(`BackingStore - Ignoring attempt to set 'backingStore' property`); return true; } Reflect.set(target, prop, value, receiver); backingStore.set(prop.toString(), value); return true; } }; return handler; }; // node_modules/@microsoft/kiota-abstractions/dist/es/src/store/backingStoreUtils.js var BackingStoreKey = "backingStoreEnabled"; function isBackingStoreEnabled(fields) { return Object.keys(fields).includes(BackingStoreKey); } // node_modules/@microsoft/kiota-abstractions/dist/es/src/apiClientBuilder.js function enableBackingStoreForSerializationWriterFactory(serializationWriterFactoryRegistry, parseNodeFactoryRegistry,