@icure/api 7.1.7 → 7.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"crypto-utils.js","sourceRoot":"","sources":["../../../icc-x-api/utils/crypto-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,6BAA4B;AAG5B,wDAA4G;AAC5G,+CAAoC;AACpC,+CAAyC;AAGzC,SAAgB,aAAa,CAAI,cAAmD,EAAE,GAAW,EAAE,IAA0B;IAC3H,MAAM,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC,CAAA;IACpC,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,MAAM,GAAG,CAAC,GAAS,EAAE;YACzB,IAAI;gBACF,OAAO,MAAM,IAAI,EAAE,CAAA;aACpB;oBAAS;gBACR,OAAO,cAAc,CAAC,GAAG,CAAC,CAAA;aAC3B;QACH,CAAC,CAAA,CAAC,EAAE,CAAA;QACJ,cAAc,CAAC,GAAG,CAAC,GAAG,MAAM,CAAA;QAC5B,OAAO,MAAM,CAAA;KACd;SAAM;QACL,OAAO,cAAc,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,cAAc,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC,CAAA;KAChF;AACH,CAAC;AAfD,sCAeC;AAED,SAAgB,SAAS,CAAC,GAAQ;IAChC,OAAO,IAAA,kBAAI,EAAC;QACV,IAAI;QACJ;YACE,CAAC,IAAI,EAAE,IAAI,CAAC;YACZ,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,oBAAoB,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;YAC9C;gBACE,IAAI;gBACJ;oBACE;wBACE,IAAI;wBACJ;4BACE,CAAC,IAAI,EAAE,IAAI,CAAC;4BACZ,CAAC,IAAI,EAAE,IAAA,qBAAM,EAAC,IAAA,wBAAS,EAAC,GAAG,CAA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AAC,OAAO,CAAC,KAAK,CAAC,EAAE;oBACxB,0IAA0I;oBAC1I,iIAAiI;oBACjI,IAAI,CAAC,GAAG,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;iBAC/F;qBAAM;oBACL,IAAI,CAAC,GAAG,CAAC,GAAG,MAAM,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;iBAClD;aACF;iBAAM;gBACL,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;aAClB;SACF;QACD,IAAI,GAAG,CAAC,aAAa,EAAE;YACrB,MAAM,SAAS,GAAG,MAAM,SAAS,CAAC,IAAA,wBAAS,EAAC,IAAA,kBAAG,EAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;YACpE,uCAAY,IAAI,GAAK,SAAS,EAAE;SACjC;;YAAM,OAAO,IAAI,CAAA;IACpB,CAAC;CAAA;AAxBD,sCAwBC;AAED;;;;GAIG;AACH,SAAgB,wBAAwB,CAAC,aAAyB;IAChE,IAAI,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAA;IAClI,OAAO;QACL,UAAU,EAAE,aAAa;QACzB,SAAS,EAAE,SAAS,CAAC,IAAA,qBAAM,EAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,CAAC;KACtD,CAAA;AACH,CAAC;AAND,4DAMC","sourcesContent":["import * as mm from 'moment'\nimport { Moment } from 'moment'\nimport * as _ from 'lodash'\nimport { a2b, b2a, b64Url2ua, hex2ua, string2ua, ua2b64Url, ua2hex, ua2string } from '../utils/binary-utils'\nimport { pack } from './asn1-packer'\nimport { parseAsn1 } from './asn1-parser'\nimport { KeyPair } from '../crypto/RSA'\n\nexport function notConcurrent<T>(concurrencyMap: { [key: string]: PromiseLike<any> }, key: string, proc: () => PromiseLike<T>): PromiseLike<T> {\n const inFlight = concurrencyMap[key]\n if (!inFlight) {\n const newJob = (async () => {\n try {\n return await proc()\n } finally {\n delete concurrencyMap[key]\n }\n })()\n concurrencyMap[key] = newJob\n return newJob\n } else {\n return concurrencyMap[key].then(() => notConcurrent(concurrencyMap, key, proc))\n }\n}\n\nexport function jwk2pkcs8(jwk: any): string {\n return pack([\n 0x30,\n [\n [0x02, '00'],\n [0x30, [[0x06, '2a864886f70d010101'], [0x05]]], // pragma: allowlist secret\n [\n 0x04,\n [\n [\n 0x30,\n [\n [0x02, '00'],\n [0x02, ua2hex(b64Url2ua(jwk.n))],\n [0x02, ua2hex(b64Url2ua(jwk.e))],\n [0x02, ua2hex(b64Url2ua(jwk.d))],\n [0x02, ua2hex(b64Url2ua(jwk.p))],\n [0x02, ua2hex(b64Url2ua(jwk.q))],\n [0x02, ua2hex(b64Url2ua(jwk.dp))],\n [0x02, ua2hex(b64Url2ua(jwk.dq))],\n [0x02, ua2hex(b64Url2ua(jwk.qi))],\n ],\n ],\n ],\n ],\n ],\n ])\n}\n\nexport function jwk2spki(jwk: any): string {\n return pack([\n 0x30,\n [\n [0x30, [[0x06, '2a864886f70d010101'], [0x05]]], // pragma: allowlist secret\n [\n 0x03,\n [\n [\n 0x30,\n [\n [0x02, ua2hex(b64Url2ua(jwk.n))],\n [0x02, ua2hex(b64Url2ua(jwk.e))],\n ],\n ],\n ],\n ],\n ],\n ])\n}\n\nexport function spkiToJwk(buf: Uint8Array): { kty: string; alg: string; n: string; e: string; ext: boolean } {\n const asn1 = parseAsn1(new Uint8Array(buf))\n\n var modulus: Uint8Array | undefined = undefined\n var exponent: Uint8Array | undefined = undefined\n if (\n asn1.type === 0x30 &&\n asn1.children?.[0]?.type === 0x30 &&\n asn1.children?.[0]?.children?.[0]?.type === 0x06 &&\n ua2hex(asn1.children?.[0]?.children?.[0]?.value ?? new Uint8Array(0)) === '2a864886f70d010101' // pragma: allowlist secret\n ) {\n modulus = asn1.children?.[1]?.children?.[0]?.children?.[0]?.value\n exponent = asn1.children?.[1]?.children?.[0]?.children?.[1]?.value\n } else if (asn1.type === 0x30 && asn1.children?.[0]?.type === 0x02 && asn1.children?.[1]?.type === 0x02) {\n modulus = asn1.children?.[0]?.value\n exponent = asn1.children?.[1]?.value\n }\n\n if (!modulus || !exponent) {\n throw new Error('Invalid spki format')\n }\n return {\n kty: 'RSA',\n alg: 'RSA-OAEP',\n ext: true,\n n: ua2b64Url(minimalRep(modulus)),\n e: ua2b64Url(minimalRep(exponent)),\n }\n}\n\nexport function pkcs8ToJwk(buf: Uint8Array | ArrayBuffer) {\n const parsed = parseAsn1(new Uint8Array(buf))\n const seq =\n parsed.children?.length === 3 && parsed.children[2].type === 0x04 && parsed.children[2].children?.length === 1\n ? parsed.children[2].children[0]\n : parsed\n return {\n kty: 'RSA',\n n: ua2b64Url(minimalRep(seq.children![1].value as Uint8Array)),\n e: ua2b64Url(minimalRep(seq.children![2].value as Uint8Array)),\n d: ua2b64Url(minimalRep(seq.children![3].value as Uint8Array)),\n p: ua2b64Url(minimalRep(seq.children![4].value as Uint8Array)),\n q: ua2b64Url(minimalRep(seq.children![5].value as Uint8Array)),\n dp: ua2b64Url(minimalRep(seq.children![6].value as Uint8Array)),\n dq: ua2b64Url(minimalRep(seq.children![7].value as Uint8Array)),\n qi: ua2b64Url(minimalRep(seq.children![8].value as Uint8Array)),\n }\n}\n\nfunction minimalRep(b: Uint8Array) {\n let i = 0\n while (b[i] === 0) {\n i++\n }\n return b.slice(i)\n}\n\n/**\n * Provide a view over the given Uint8Array where any trailing null bytes at\n * the end are truncated.\n *\n * This can be used to ignore null bytes at the end of a padded UTF-8 string\n * without needing to copy that string, assuming code point U+0000 is encoded\n * in one null byte according to standards rather than in a multi-byte\n * overlong form.\n */\nexport function truncateTrailingNulls(a: Uint8Array) {\n let end = a.byteLength - 1\n while (a[end] === 0 && end >= 0) {\n end--\n }\n // end is now either the last non-null position in a or -1; in the latter\n // case the returned array will have length 0.\n return a.subarray(0, end + 1)\n}\n\n/**\n *\n * @param buffer1 {Uint8Array}\n * @param buffer2{ Uint8Array}\n * @returns {ArrayBuffer}\n */\nexport function appendBuffer(buffer1: ArrayBuffer, buffer2: ArrayBuffer): ArrayBuffer {\n const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength)\n tmp.set(new Uint8Array(buffer1), 0)\n tmp.set(new Uint8Array(buffer2), buffer1.byteLength)\n return tmp.buffer as ArrayBuffer\n}\n\n//Convenience methods for dates management\nexport function after(d1: number | null | undefined, d2: number | null | undefined): boolean {\n return d1 === null || d2 === null || d1 === undefined || d2 === undefined || moment(d1)!.isAfter(moment(d2)!)\n}\n\nexport function before(d1: number | null | undefined, d2: number | null | undefined): boolean {\n return d1 === null || d2 === null || d1 === undefined || d2 === undefined || moment(d1)!.isBefore(moment(d2)!)\n}\n\nfunction moment(epochOrLongCalendar: number): Moment | null {\n if (!epochOrLongCalendar && epochOrLongCalendar !== 0) {\n return null\n }\n if (epochOrLongCalendar >= 18000101 && epochOrLongCalendar < 25400000) {\n return mm('' + epochOrLongCalendar, 'YYYYMMDD')\n } else if (epochOrLongCalendar >= 18000101000000) {\n return mm('' + epochOrLongCalendar, 'YYYYMMDDHHmmss')\n } else {\n return mm(epochOrLongCalendar)\n }\n}\n\n/**\n * Configuration for the encryption of an object.\n * @param topLevelFields the fields of the object to encrypt. All the fields will be encrypted in a single encryptedSelf field which is added to the\n * object.\n * @param nestedObjectsKeys the name of fields which are expected to contain a nested object (or undefined). Allows to specify\n */\nexport type EncryptedFieldsManifest = {\n topLevelFields: { fieldName: string; fieldPath: string }[]\n nestedObjectsKeys: {\n [objectFieldName: string]: EncryptedFieldsManifest\n }\n mapsValuesKeys: {\n [mapFieldName: string]: EncryptedFieldsManifest\n }\n arraysValuesKeys: {\n [arrayFieldName: string]: EncryptedFieldsManifest\n }\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n *\n * Parse the encrypted fields configuration for a specific entity type.\n *\n * ## Grammar\n *\n * The grammar for each encrypted field is the following:\n * ```\n * fieldName :=\n * regex([a-zA-Z_][a-zA-Z0-9_]+)\n * encryptedField :=\n * fieldName\n * | fieldName + (\".\" | \".*.\" | \"[].\") + encryptedField\n * ```\n *\n * This grammar allows you to specify the fields to encrypt for the object and recursively for nested objects.\n * - A string containing only a single `fieldName` will encrypt the field with the given name.\n * - A string starting with `fieldName.` allows to specify the encrypted fields of a nested object. The encrypted values of the\n * fields in the nested object will be saved in the nested object.\n * - A string starting with `fieldName.*.` treats `fieldName` as a map/dictionary data structure and allows to specify the encrypted fields of the\n * values of the map. Note that the values of the map must be objects as well. The encrypted content of each map value is stored in that value.\n * - A string starting with `fieldName[].` treats `fieldName` as an array and allows to specify the encrypted fields of the values of the array.\n * Note that the values of the array must be objects as well. The encrypted content of each array element is stored in that element.\n *\n * ## Example\n *\n * Consider the following object and encryption keys:\n * ```javascript\n * const obj = {\n * a: { x: 0, y: 1 },\n * b: \"hello\",\n * c: [ { public: \"a\", secret: \"b\" }, { public: \"c\", secret: \"d\" } ],\n * d: \"ok\",\n * e: {\n * info: \"something\",\n * private: \"secret\",\n * dataMap: {\n * \"en\": {\n * a: 1,\n * b: 2\n * },\n * \"fr\": {\n * a: 3,\n * b: 4\n * }\n * }\n * }\n * }\n * const encryptedFields = [\n * \"a\",\n * \"c[].secret\",\n * \"d\",\n * \"e.private\",\n * \"e.datamap.*.a\"\n * ]\n * ```\n * If you use them with the crypt method you will get the following result:\n * ```json\n * {\n * b: \"hello\",\n * c: [\n * { public: \"a\", encryptedSelf: \"...encrypted data of c[0]\" },\n * { public: \"c\", encryptedSelf: \"...encrypted data of c[1]\" }\n * ],\n * e: {\n * info: \"something\",\n * dataMap: {\n * \"en\": { b: 2, encryptedSelf: \"...encrypted data of e.dataMap['en']\" },\n * \"fr\": { b: 4, encryptedSelf: \"...encrypted data of e.dataMap['fr']\" }\n * },\n * encryptedSelf: \"...encrypted data of e\"\n * },\n * encryptedSelf: \"...encrypted data of obj\"\n * }\n * ```\n *\n * ## Shortened representation\n *\n * You can also group encrypted fields having the same prefix by concatenating to the prefix the JSON representation of an array of all the postfixes.\n * For example the following encrypted fields:\n * ```javascript\n * const encryptedFields = [\"a.b.c.d.e.f1\", \"a.b.c.d.e.f2\", \"a.b.c.d.e.f3\", \"a.b.c.d.e.f4\"]\n * ```\n * can be shortened to\n * ```javascript\n * const encryptedFields = ['a.b.c.d.e.[\"f1\",\"f2\",\"f3\",\"f4\"]'] // Note the use of single quotes to avoid escaping the double quotes\n * ```\n * If you use the shortened representation you may need to escape nested json representations. In that case the use of `JSON.stringify` is\n * recommended.\n *\n * @param encryptedFields\n * @param path\n */\nexport function parseEncryptedFields(encryptedFields: string[], path: string): EncryptedFieldsManifest {\n const groupedData = {\n topLevelFields: new Set<string>(),\n nestedObjectsKeys: {} as { [objectFieldName: string]: string[] },\n mapsValuesKeys: {} as { [mapFieldName: string]: string[] },\n arraysValuesKeys: {} as { [arrayFieldName: string]: string[] },\n }\n const encryptedFieldRegex = /^([_a-zA-Z][_a-zA-Z0-9]*)(?:(\\.\\*\\.|\\[]\\.|\\.)(?:[_a-zA-Z].*|\\[.*]))?$/\n const addSubkeyToGroupedData = (\n currFieldName: string,\n currFieldSeparator: string,\n currEncryptedField: string,\n groupedDataKey: 'nestedObjectsKeys' | 'mapsValuesKeys' | 'arraysValuesKeys'\n ) => {\n const existingOrNew = groupedData[groupedDataKey][currFieldName] ?? (groupedData[groupedDataKey][currFieldName] = [])\n const subKey = currEncryptedField.slice(currFieldName.length + currFieldSeparator.length)\n if (subKey.startsWith('[')) {\n let parsedJson: any[]\n try {\n parsedJson = JSON.parse(subKey)\n } catch {\n throw new Error(`Invalid encrypted field ${path}${currEncryptedField} (not a valid JSON subkey)`)\n }\n if (Array.isArray(parsedJson) && parsedJson.every((x) => typeof x == 'string')) {\n parsedJson.forEach((x) => existingOrNew.push(x))\n } else throw new Error(`Invalid encrypted field ${path}${currEncryptedField} (not an array of strings)`)\n } else {\n existingOrNew.push(subKey)\n }\n }\n for (const currEncryptedField of encryptedFields) {\n const currFieldMatch = currEncryptedField.match(encryptedFieldRegex)\n if (!!currFieldMatch) {\n const currFieldName = currFieldMatch[1]\n const currFieldSeparator = currFieldMatch[2]\n if (!currFieldSeparator) {\n if (groupedData.topLevelFields.has(currFieldName)) throw new Error(`Duplicate encrypted field ${path}${currFieldName}`)\n if (\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.mapsValuesKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n groupedData.topLevelFields.add(currFieldName)\n } else if (currFieldSeparator == '.') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.mapsValuesKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'nestedObjectsKeys')\n } else if (currFieldSeparator == '.*.') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'mapsValuesKeys')\n } else if (currFieldSeparator == '[].') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.mapsValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'arraysValuesKeys')\n } else throw new Error(`Internal error: unknown separator ${currFieldSeparator} passed regex validation in ${path}${currEncryptedField}`)\n } else throw new Error(`Invalid encrypted field ${path}${currEncryptedField}`)\n }\n return {\n topLevelFields: Array.from(groupedData.topLevelFields).map((fieldName) => ({ fieldName, fieldPath: path + fieldName })),\n nestedObjectsKeys: Object.fromEntries(\n Object.entries(groupedData.nestedObjectsKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '.'),\n ])\n ),\n mapsValuesKeys: Object.fromEntries(\n Object.entries(groupedData.mapsValuesKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '.*.'),\n ])\n ),\n arraysValuesKeys: Object.fromEntries(\n Object.entries(groupedData.arraysValuesKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '[].'),\n ])\n ),\n }\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Encrypt the object graph recursively. Generally return an updated SHALLOW copy, although some fields may be deep copied if they also needed to be\n * recursively encrypted.\n * @param obj the object to encrypt\n * @param cryptor takes in input an object consisting only of the fields to encrypt of obj, and returns the encrypted object.\n * @param keys the keys to encrypt for the\n * @param path path of the current object, used for error messages.\n * @return a shallow copy of the object with a new encryptedSelfField and without the encrypted fields.\n */\nexport async function encryptObject(\n obj: { [key: string]: any },\n cryptor: (obj: { [key: string]: any }) => Promise<ArrayBuffer>,\n keys: EncryptedFieldsManifest,\n path: string = 'obj'\n): Promise<{ [key: string]: any }> {\n const shallowClone = { ...obj }\n const currEncryptedFields: { [key: string]: any } = {}\n for (const { fieldName } of keys.topLevelFields) {\n const fieldValue = shallowClone[fieldName]\n if (fieldValue !== undefined) {\n // we keep null values\n currEncryptedFields[fieldName] = fieldValue\n delete shallowClone[fieldName]\n }\n }\n shallowClone['encryptedSelf'] = b2a(ua2string(await cryptor(currEncryptedFields)))\n for (const [fieldName, subKeys] of Object.entries(keys.nestedObjectsKeys)) {\n const fieldValue = shallowClone[fieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!isPojo(fieldValue)) throw new Error(`Expected field ${path}.${fieldName} to be a non-array object`)\n shallowClone[fieldName] = await encryptObject(fieldValue, cryptor, subKeys, path + '.' + fieldName)\n }\n }\n for (const [mapFieldName, subKeys] of Object.entries(keys.mapsValuesKeys)) {\n const fieldValue = shallowClone[mapFieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!isPojo(fieldValue)) throw new Error(`Expected field ${path}.${mapFieldName} to be a non-array object`)\n const newMap: { [key: string]: any } = {}\n for (const [key, value] of Object.entries(fieldValue as object)) {\n if (value === null || value === undefined) {\n newMap[key] = value\n } else {\n if (!isPojo(value)) throw new Error(`Expected field ${path}.${mapFieldName}.${key} to be a non-array object`)\n newMap[key] = await encryptObject(value, cryptor, subKeys, path + '.' + mapFieldName + '.' + key)\n }\n }\n shallowClone[mapFieldName] = newMap\n }\n }\n for (const [arrayFieldName, subKeys] of Object.entries(keys.arraysValuesKeys)) {\n const fieldValue = shallowClone[arrayFieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!Array.isArray(fieldValue)) throw new Error(`Expected field ${path}.${arrayFieldName} to be an array`)\n const newArray: any[] = Array(fieldValue.length)\n for (let i = 0; i < fieldValue.length; i++) {\n const value = fieldValue[i]\n if (value === null || value === undefined) {\n newArray[i] = value\n } else {\n if (!isPojo(value)) throw new Error(`Expected field ${path}.${arrayFieldName}[${i}] to be a non-array object`)\n newArray[i] = await encryptObject(value, cryptor, subKeys, path + '.' + arrayFieldName + '[' + i + ']')\n }\n }\n shallowClone[arrayFieldName] = newArray\n }\n }\n return shallowClone\n}\n\n/**\n * Check if value is a non-null object that is not an array.\n */\nfunction isPojo(value: any): boolean {\n // This break if for some reason we have object versions of String/Number/Boolean\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Decrypt object graph recursively.\n *\n * @param obj the object to decrypt\n * @param decryptor the decryptor function (returns a promise)\n * @return a deep copy of the object with the decrypted fields and removed encryptedSelf field\n */\nexport async function decryptObject(\n obj: { [key: string]: any },\n decryptor: (obj: Uint8Array) => Promise<{ [key: string]: any }>\n): Promise<{ [key: string]: any }> {\n const copy: { [key: string]: any } = {}\n for (const [key, value] of Object.entries(obj)) {\n if (key === 'encryptedSelf') {\n copy[key] = value\n } else if (typeof value === 'object' && value !== null) {\n if (Array.isArray(value)) {\n // Note: nested arrays (and primitives) are returned as is and not they are not recursively decrypted. This is because we currently do not\n // support encryption of elements from arrays in arrays (we only support arrays in objects in arrays). In future this may change.\n copy[key] = await Promise.all(value.map((v) => (isPojo(v) ? decryptObject(v, decryptor) : v)))\n } else {\n copy[key] = await decryptObject(value, decryptor)\n }\n } else {\n copy[key] = value\n }\n }\n if (obj.encryptedSelf) {\n const decrypted = await decryptor(string2ua(a2b(obj.encryptedSelf)))\n return { ...copy, ...decrypted }\n } else return copy\n}\n\n/**\n * Extracts the full jwk key pair from the jwk representation of the private key.\n * @param privateKeyJwk private key in jwk representation\n * @throws if the key is missing the public modulus or public exponent.\n */\nexport function keyPairFromPrivateKeyJwk(privateKeyJwk: JsonWebKey): KeyPair<JsonWebKey> {\n if (!privateKeyJwk.n || !privateKeyJwk.e) throw new Error('Incomplete private JsonWebKey: missing public modulus and/or exponent')\n return {\n privateKey: privateKeyJwk,\n publicKey: spkiToJwk(hex2ua(jwk2spki(privateKeyJwk))),\n }\n}\n"]}
1
+ {"version":3,"file":"crypto-utils.js","sourceRoot":"","sources":["../../../icc-x-api/utils/crypto-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,6BAA4B;AAG5B,wDAA4G;AAC5G,+CAAoC;AACpC,+CAAyC;AAGzC,SAAgB,aAAa,CAAI,cAAmD,EAAE,GAAW,EAAE,IAA0B;IAC3H,MAAM,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC,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C,KAAK,CAAC,EAAE;oBACpE,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA,CAAC,wHAAwH;iBAC3I;qBAAM;oBACL,IAAI,CAAC,GAAG,CAAC,GAAG,MAAM,aAAa,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;iBAClD;aACF;iBAAM;gBACL,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;aAClB;SACF;QACD,IAAI,GAAG,CAAC,aAAa,EAAE;YACrB,MAAM,SAAS,GAAG,MAAM,SAAS,CAAC,IAAA,wBAAS,EAAC,IAAA,kBAAG,EAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;YACpE,uCAAY,IAAI,GAAK,SAAS,EAAE;SACjC;;YAAM,OAAO,IAAI,CAAA;IACpB,CAAC;CAAA;AA1BD,sCA0BC;AAED;;;;GAIG;AACH,SAAgB,wBAAwB,CAAC,aAAyB;IAChE,IAAI,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAA;IAClI,OAAO;QACL,UAAU,EAAE,aAAa;QACzB,SAAS,EAAE,SAAS,CAAC,IAAA,qBAAM,EAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,CAAC;KACtD,CAAA;AACH,CAAC;AAND,4DAMC","sourcesContent":["import * as mm from 'moment'\nimport { Moment } from 'moment'\nimport * as _ from 'lodash'\nimport { a2b, b2a, b64Url2ua, hex2ua, string2ua, ua2b64Url, ua2hex, ua2string } from '../utils/binary-utils'\nimport { pack } from './asn1-packer'\nimport { parseAsn1 } from './asn1-parser'\nimport { KeyPair } from '../crypto/RSA'\n\nexport function notConcurrent<T>(concurrencyMap: { [key: string]: PromiseLike<any> }, key: string, proc: () => PromiseLike<T>): PromiseLike<T> {\n const inFlight = concurrencyMap[key]\n if (!inFlight) {\n const newJob = (async () => {\n try {\n return await proc()\n } finally {\n delete concurrencyMap[key]\n }\n })()\n concurrencyMap[key] = newJob\n return newJob\n } else {\n return concurrencyMap[key].then(() => notConcurrent(concurrencyMap, key, proc))\n }\n}\n\nexport function jwk2pkcs8(jwk: any): string {\n return pack([\n 0x30,\n [\n [0x02, '00'],\n [0x30, [[0x06, '2a864886f70d010101'], [0x05]]], // pragma: allowlist secret\n [\n 0x04,\n [\n [\n 0x30,\n [\n [0x02, '00'],\n [0x02, ua2hex(b64Url2ua(jwk.n))],\n [0x02, ua2hex(b64Url2ua(jwk.e))],\n [0x02, ua2hex(b64Url2ua(jwk.d))],\n [0x02, ua2hex(b64Url2ua(jwk.p))],\n [0x02, ua2hex(b64Url2ua(jwk.q))],\n [0x02, ua2hex(b64Url2ua(jwk.dp))],\n [0x02, ua2hex(b64Url2ua(jwk.dq))],\n [0x02, ua2hex(b64Url2ua(jwk.qi))],\n ],\n ],\n ],\n ],\n ],\n ])\n}\n\nexport function jwk2spki(jwk: any): string {\n return pack([\n 0x30,\n [\n [0x30, [[0x06, '2a864886f70d010101'], [0x05]]], // pragma: allowlist secret\n [\n 0x03,\n [\n [\n 0x30,\n [\n [0x02, ua2hex(b64Url2ua(jwk.n))],\n [0x02, ua2hex(b64Url2ua(jwk.e))],\n ],\n ],\n ],\n ],\n ],\n ])\n}\n\nexport function spkiToJwk(buf: Uint8Array): { kty: string; alg: string; n: string; e: string; ext: boolean } {\n const asn1 = parseAsn1(new Uint8Array(buf))\n\n var modulus: Uint8Array | undefined = undefined\n var exponent: Uint8Array | undefined = undefined\n if (\n asn1.type === 0x30 &&\n asn1.children?.[0]?.type === 0x30 &&\n asn1.children?.[0]?.children?.[0]?.type === 0x06 &&\n ua2hex(asn1.children?.[0]?.children?.[0]?.value ?? new Uint8Array(0)) === '2a864886f70d010101' // pragma: allowlist secret\n ) {\n modulus = asn1.children?.[1]?.children?.[0]?.children?.[0]?.value\n exponent = asn1.children?.[1]?.children?.[0]?.children?.[1]?.value\n } else if (asn1.type === 0x30 && asn1.children?.[0]?.type === 0x02 && asn1.children?.[1]?.type === 0x02) {\n modulus = asn1.children?.[0]?.value\n exponent = asn1.children?.[1]?.value\n }\n\n if (!modulus || !exponent) {\n throw new Error('Invalid spki format')\n }\n return {\n kty: 'RSA',\n alg: 'RSA-OAEP',\n ext: true,\n n: ua2b64Url(minimalRep(modulus)),\n e: ua2b64Url(minimalRep(exponent)),\n }\n}\n\nexport function pkcs8ToJwk(buf: Uint8Array | ArrayBuffer) {\n const parsed = parseAsn1(new Uint8Array(buf))\n const seq =\n parsed.children?.length === 3 && parsed.children[2].type === 0x04 && parsed.children[2].children?.length === 1\n ? parsed.children[2].children[0]\n : parsed\n return {\n kty: 'RSA',\n n: ua2b64Url(minimalRep(seq.children![1].value as Uint8Array)),\n e: ua2b64Url(minimalRep(seq.children![2].value as Uint8Array)),\n d: ua2b64Url(minimalRep(seq.children![3].value as Uint8Array)),\n p: ua2b64Url(minimalRep(seq.children![4].value as Uint8Array)),\n q: ua2b64Url(minimalRep(seq.children![5].value as Uint8Array)),\n dp: ua2b64Url(minimalRep(seq.children![6].value as Uint8Array)),\n dq: ua2b64Url(minimalRep(seq.children![7].value as Uint8Array)),\n qi: ua2b64Url(minimalRep(seq.children![8].value as Uint8Array)),\n }\n}\n\nfunction minimalRep(b: Uint8Array) {\n let i = 0\n while (b[i] === 0) {\n i++\n }\n return b.slice(i)\n}\n\n/**\n * Provide a view over the given Uint8Array where any trailing null bytes at\n * the end are truncated.\n *\n * This can be used to ignore null bytes at the end of a padded UTF-8 string\n * without needing to copy that string, assuming code point U+0000 is encoded\n * in one null byte according to standards rather than in a multi-byte\n * overlong form.\n */\nexport function truncateTrailingNulls(a: Uint8Array) {\n let end = a.byteLength - 1\n while (a[end] === 0 && end >= 0) {\n end--\n }\n // end is now either the last non-null position in a or -1; in the latter\n // case the returned array will have length 0.\n return a.subarray(0, end + 1)\n}\n\n/**\n *\n * @param buffer1 {Uint8Array}\n * @param buffer2{ Uint8Array}\n * @returns {ArrayBuffer}\n */\nexport function appendBuffer(buffer1: ArrayBuffer, buffer2: ArrayBuffer): ArrayBuffer {\n const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength)\n tmp.set(new Uint8Array(buffer1), 0)\n tmp.set(new Uint8Array(buffer2), buffer1.byteLength)\n return tmp.buffer as ArrayBuffer\n}\n\n//Convenience methods for dates management\nexport function after(d1: number | null | undefined, d2: number | null | undefined): boolean {\n return d1 === null || d2 === null || d1 === undefined || d2 === undefined || moment(d1)!.isAfter(moment(d2)!)\n}\n\nexport function before(d1: number | null | undefined, d2: number | null | undefined): boolean {\n return d1 === null || d2 === null || d1 === undefined || d2 === undefined || moment(d1)!.isBefore(moment(d2)!)\n}\n\nfunction moment(epochOrLongCalendar: number): Moment | null {\n if (!epochOrLongCalendar && epochOrLongCalendar !== 0) {\n return null\n }\n if (epochOrLongCalendar >= 18000101 && epochOrLongCalendar < 25400000) {\n return mm('' + epochOrLongCalendar, 'YYYYMMDD')\n } else if (epochOrLongCalendar >= 18000101000000) {\n return mm('' + epochOrLongCalendar, 'YYYYMMDDHHmmss')\n } else {\n return mm(epochOrLongCalendar)\n }\n}\n\n/**\n * Configuration for the encryption of an object.\n * @param topLevelFields the fields of the object to encrypt. All the fields will be encrypted in a single encryptedSelf field which is added to the\n * object.\n * @param nestedObjectsKeys the name of fields which are expected to contain a nested object (or undefined). Allows to specify\n */\nexport type EncryptedFieldsManifest = {\n topLevelFields: { fieldName: string; fieldPath: string }[]\n nestedObjectsKeys: {\n [objectFieldName: string]: EncryptedFieldsManifest\n }\n mapsValuesKeys: {\n [mapFieldName: string]: EncryptedFieldsManifest\n }\n arraysValuesKeys: {\n [arrayFieldName: string]: EncryptedFieldsManifest\n }\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n *\n * Parse the encrypted fields configuration for a specific entity type.\n *\n * ## Grammar\n *\n * The grammar for each encrypted field is the following:\n * ```\n * fieldName :=\n * regex([a-zA-Z_][a-zA-Z0-9_]+)\n * encryptedField :=\n * fieldName\n * | fieldName + (\".\" | \".*.\" | \"[].\") + encryptedField\n * ```\n *\n * This grammar allows you to specify the fields to encrypt for the object and recursively for nested objects.\n * - A string containing only a single `fieldName` will encrypt the field with the given name.\n * - A string starting with `fieldName.` allows to specify the encrypted fields of a nested object. The encrypted values of the\n * fields in the nested object will be saved in the nested object.\n * - A string starting with `fieldName.*.` treats `fieldName` as a map/dictionary data structure and allows to specify the encrypted fields of the\n * values of the map. Note that the values of the map must be objects as well. The encrypted content of each map value is stored in that value.\n * - A string starting with `fieldName[].` treats `fieldName` as an array and allows to specify the encrypted fields of the values of the array.\n * Note that the values of the array must be objects as well. The encrypted content of each array element is stored in that element.\n *\n * ## Example\n *\n * Consider the following object and encryption keys:\n * ```javascript\n * const obj = {\n * a: { x: 0, y: 1 },\n * b: \"hello\",\n * c: [ { public: \"a\", secret: \"b\" }, { public: \"c\", secret: \"d\" } ],\n * d: \"ok\",\n * e: {\n * info: \"something\",\n * private: \"secret\",\n * dataMap: {\n * \"en\": {\n * a: 1,\n * b: 2\n * },\n * \"fr\": {\n * a: 3,\n * b: 4\n * }\n * }\n * }\n * }\n * const encryptedFields = [\n * \"a\",\n * \"c[].secret\",\n * \"d\",\n * \"e.private\",\n * \"e.datamap.*.a\"\n * ]\n * ```\n * If you use them with the crypt method you will get the following result:\n * ```json\n * {\n * b: \"hello\",\n * c: [\n * { public: \"a\", encryptedSelf: \"...encrypted data of c[0]\" },\n * { public: \"c\", encryptedSelf: \"...encrypted data of c[1]\" }\n * ],\n * e: {\n * info: \"something\",\n * dataMap: {\n * \"en\": { b: 2, encryptedSelf: \"...encrypted data of e.dataMap['en']\" },\n * \"fr\": { b: 4, encryptedSelf: \"...encrypted data of e.dataMap['fr']\" }\n * },\n * encryptedSelf: \"...encrypted data of e\"\n * },\n * encryptedSelf: \"...encrypted data of obj\"\n * }\n * ```\n *\n * ## Shortened representation\n *\n * You can also group encrypted fields having the same prefix by concatenating to the prefix the JSON representation of an array of all the postfixes.\n * For example the following encrypted fields:\n * ```javascript\n * const encryptedFields = [\"a.b.c.d.e.f1\", \"a.b.c.d.e.f2\", \"a.b.c.d.e.f3\", \"a.b.c.d.e.f4\"]\n * ```\n * can be shortened to\n * ```javascript\n * const encryptedFields = ['a.b.c.d.e.[\"f1\",\"f2\",\"f3\",\"f4\"]'] // Note the use of single quotes to avoid escaping the double quotes\n * ```\n * If you use the shortened representation you may need to escape nested json representations. In that case the use of `JSON.stringify` is\n * recommended.\n *\n * @param encryptedFields\n * @param path\n */\nexport function parseEncryptedFields(encryptedFields: string[], path: string): EncryptedFieldsManifest {\n const groupedData = {\n topLevelFields: new Set<string>(),\n nestedObjectsKeys: {} as { [objectFieldName: string]: string[] },\n mapsValuesKeys: {} as { [mapFieldName: string]: string[] },\n arraysValuesKeys: {} as { [arrayFieldName: string]: string[] },\n }\n const encryptedFieldRegex = /^([_a-zA-Z][_a-zA-Z0-9]*)(?:(\\.\\*\\.|\\[]\\.|\\.)(?:[_a-zA-Z].*|\\[.*]))?$/\n const addSubkeyToGroupedData = (\n currFieldName: string,\n currFieldSeparator: string,\n currEncryptedField: string,\n groupedDataKey: 'nestedObjectsKeys' | 'mapsValuesKeys' | 'arraysValuesKeys'\n ) => {\n const existingOrNew = groupedData[groupedDataKey][currFieldName] ?? (groupedData[groupedDataKey][currFieldName] = [])\n const subKey = currEncryptedField.slice(currFieldName.length + currFieldSeparator.length)\n if (subKey.startsWith('[')) {\n let parsedJson: any[]\n try {\n parsedJson = JSON.parse(subKey)\n } catch {\n throw new Error(`Invalid encrypted field ${path}${currEncryptedField} (not a valid JSON subkey)`)\n }\n if (Array.isArray(parsedJson) && parsedJson.every((x) => typeof x == 'string')) {\n parsedJson.forEach((x) => existingOrNew.push(x))\n } else throw new Error(`Invalid encrypted field ${path}${currEncryptedField} (not an array of strings)`)\n } else {\n existingOrNew.push(subKey)\n }\n }\n for (const currEncryptedField of encryptedFields) {\n const currFieldMatch = currEncryptedField.match(encryptedFieldRegex)\n if (!!currFieldMatch) {\n const currFieldName = currFieldMatch[1]\n const currFieldSeparator = currFieldMatch[2]\n if (!currFieldSeparator) {\n if (groupedData.topLevelFields.has(currFieldName)) throw new Error(`Duplicate encrypted field ${path}${currFieldName}`)\n if (\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.mapsValuesKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n groupedData.topLevelFields.add(currFieldName)\n } else if (currFieldSeparator == '.') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.mapsValuesKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'nestedObjectsKeys')\n } else if (currFieldSeparator == '.*.') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'mapsValuesKeys')\n } else if (currFieldSeparator == '[].') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.mapsValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'arraysValuesKeys')\n } else throw new Error(`Internal error: unknown separator ${currFieldSeparator} passed regex validation in ${path}${currEncryptedField}`)\n } else throw new Error(`Invalid encrypted field ${path}${currEncryptedField}`)\n }\n return {\n topLevelFields: Array.from(groupedData.topLevelFields).map((fieldName) => ({ fieldName, fieldPath: path + fieldName })),\n nestedObjectsKeys: Object.fromEntries(\n Object.entries(groupedData.nestedObjectsKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '.'),\n ])\n ),\n mapsValuesKeys: Object.fromEntries(\n Object.entries(groupedData.mapsValuesKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '.*.'),\n ])\n ),\n arraysValuesKeys: Object.fromEntries(\n Object.entries(groupedData.arraysValuesKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '[].'),\n ])\n ),\n }\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Encrypt the object graph recursively. Generally return an updated SHALLOW copy, although some fields may be deep copied if they also needed to be\n * recursively encrypted.\n * @param obj the object to encrypt\n * @param cryptor takes in input an object consisting only of the fields to encrypt of obj, and returns the encrypted object.\n * @param keys the keys to encrypt for the\n * @param path path of the current object, used for error messages.\n * @return a shallow copy of the object with a new encryptedSelfField and without the encrypted fields.\n */\nexport async function encryptObject(\n obj: { [key: string]: any },\n cryptor: (obj: { [key: string]: any }) => Promise<ArrayBuffer>,\n keys: EncryptedFieldsManifest,\n path: string = 'obj'\n): Promise<{ [key: string]: any }> {\n const shallowClone = { ...obj }\n const currEncryptedFields: { [key: string]: any } = {}\n for (const { fieldName } of keys.topLevelFields) {\n const fieldValue = shallowClone[fieldName]\n if (fieldValue !== undefined) {\n // we keep null values\n currEncryptedFields[fieldName] = fieldValue\n delete shallowClone[fieldName]\n }\n }\n shallowClone['encryptedSelf'] = b2a(ua2string(await cryptor(currEncryptedFields)))\n for (const [fieldName, subKeys] of Object.entries(keys.nestedObjectsKeys)) {\n const fieldValue = shallowClone[fieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!isPojo(fieldValue)) throw new Error(`Expected field ${path}.${fieldName} to be a non-array object`)\n shallowClone[fieldName] = await encryptObject(fieldValue, cryptor, subKeys, path + '.' + fieldName)\n }\n }\n for (const [mapFieldName, subKeys] of Object.entries(keys.mapsValuesKeys)) {\n const fieldValue = shallowClone[mapFieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!isPojo(fieldValue)) throw new Error(`Expected field ${path}.${mapFieldName} to be a non-array object`)\n const newMap: { [key: string]: any } = {}\n for (const [key, value] of Object.entries(fieldValue as object)) {\n if (value === null || value === undefined) {\n newMap[key] = value\n } else {\n if (!isPojo(value)) throw new Error(`Expected field ${path}.${mapFieldName}.${key} to be a non-array object`)\n newMap[key] = await encryptObject(value, cryptor, subKeys, path + '.' + mapFieldName + '.' + key)\n }\n }\n shallowClone[mapFieldName] = newMap\n }\n }\n for (const [arrayFieldName, subKeys] of Object.entries(keys.arraysValuesKeys)) {\n const fieldValue = shallowClone[arrayFieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!Array.isArray(fieldValue)) throw new Error(`Expected field ${path}.${arrayFieldName} to be an array`)\n const newArray: any[] = Array(fieldValue.length)\n for (let i = 0; i < fieldValue.length; i++) {\n const value = fieldValue[i]\n if (value === null || value === undefined) {\n newArray[i] = value\n } else {\n if (!isPojo(value)) throw new Error(`Expected field ${path}.${arrayFieldName}[${i}] to be a non-array object`)\n newArray[i] = await encryptObject(value, cryptor, subKeys, path + '.' + arrayFieldName + '[' + i + ']')\n }\n }\n shallowClone[arrayFieldName] = newArray\n }\n }\n return shallowClone\n}\n\n/**\n * Check if value is a non-null object that is not an array.\n */\nfunction isPojo(value: any): boolean {\n // This break if for some reason we have object versions of String/Number/Boolean\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Decrypt object graph recursively.\n *\n * @param obj the object to decrypt\n * @param decryptor the decryptor function (returns a promise)\n * @return a deep copy of the object with the decrypted fields and removed encryptedSelf field\n */\nexport async function decryptObject(\n obj: { [key: string]: any },\n decryptor: (obj: Uint8Array) => Promise<{ [key: string]: any }>\n): Promise<{ [key: string]: any }> {\n const copy: { [key: string]: any } = {}\n for (const [key, value] of Object.entries(obj)) {\n if (key === 'encryptedSelf') {\n copy[key] = value\n } else if (typeof value === 'object' && value !== null) {\n if (Array.isArray(value)) {\n // Note: nested arrays (and primitives) are returned as is and not they are not recursively decrypted. This is because we currently do not\n // support encryption of elements from arrays in arrays (we only support arrays in objects in arrays). In future this may change.\n copy[key] = await Promise.all(value.map((v) => (isPojo(v) ? decryptObject(v, decryptor) : v)))\n } else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n copy[key] = value // No direct decryption of array buffer data. Array buffer should be converted to b64 string and encrypted as json data.\n } else {\n copy[key] = await decryptObject(value, decryptor)\n }\n } else {\n copy[key] = value\n }\n }\n if (obj.encryptedSelf) {\n const decrypted = await decryptor(string2ua(a2b(obj.encryptedSelf)))\n return { ...copy, ...decrypted }\n } else return copy\n}\n\n/**\n * Extracts the full jwk key pair from the jwk representation of the private key.\n * @param privateKeyJwk private key in jwk representation\n * @throws if the key is missing the public modulus or public exponent.\n */\nexport function keyPairFromPrivateKeyJwk(privateKeyJwk: JsonWebKey): KeyPair<JsonWebKey> {\n if (!privateKeyJwk.n || !privateKeyJwk.e) throw new Error('Incomplete private JsonWebKey: missing public modulus and/or exponent')\n return {\n privateKey: privateKeyJwk,\n publicKey: spkiToJwk(hex2ua(jwk2spki(privateKeyJwk))),\n }\n}\n"]}
@@ -10,9 +10,10 @@ import { HealthcareParty } from "../../icc-api/model/HealthcareParty";
10
10
  import { Device } from "../../icc-api/model/Device";
11
11
  import { Contact } from "../../icc-api/model/Contact";
12
12
  export type EventTypes = 'CREATE' | 'UPDATE' | 'DELETE';
13
- type SubscriptionOptions = {
13
+ export type SubscriptionOptions = {
14
14
  connectionMaxRetry?: number;
15
15
  connectionRetryIntervalMs?: number;
16
+ debug?: boolean;
16
17
  };
17
18
  export declare function subscribeToEntityEvents(basePath: string, authApi: IccAuthApi, entityClass: 'Patient', eventTypes: EventTypes[], filter: AbstractFilter<Patient> | undefined, eventFired: (entity: Patient) => Promise<void>, options: SubscriptionOptions, decryptor: (encrypted: Patient) => Promise<Patient>): Promise<WebSocketWrapper>;
18
19
  export declare function subscribeToEntityEvents(basePath: string, authApi: IccAuthApi, entityClass: 'Service', eventTypes: EventTypes[], filter: AbstractFilter<Service> | undefined, eventFired: (entity: Service) => Promise<void>, options: SubscriptionOptions, decryptor: (encrypted: Service) => Promise<Service>): Promise<WebSocketWrapper>;
@@ -39,6 +40,7 @@ export declare class WebSocketWrapper {
39
40
  private readonly retryDelay;
40
41
  private readonly statusCallbacks;
41
42
  private readonly messageCallback;
43
+ private readonly debug;
42
44
  private readonly pingLifetime;
43
45
  private socket;
44
46
  private retries;
@@ -47,7 +49,7 @@ export declare class WebSocketWrapper {
47
49
  private intervalIds;
48
50
  private readonly methodPath;
49
51
  private constructor();
50
- static create(url: string, authProvider: WebSocketAuthProvider, maxRetries?: number, retryDelay?: number, statusCallbacks?: ConnectionStatusFunctions, messageCallback?: WebSocketWrapperMessageCallback): Promise<WebSocketWrapper>;
52
+ static create(url: string, authProvider: WebSocketAuthProvider, maxRetries?: number, retryDelay?: number, statusCallbacks?: ConnectionStatusFunctions, messageCallback?: WebSocketWrapperMessageCallback, debug?: boolean): Promise<WebSocketWrapper>;
51
53
  send(data: Buffer | ArrayBuffer | string): void;
52
54
  close(): void;
53
55
  addStatusCallback(status: ConnectionStatus, callback: ConnectionStatusFunction[ConnectionStatus]): void;
@@ -8,16 +8,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var _a;
12
11
  Object.defineProperty(exports, "__esModule", { value: true });
13
12
  exports.WebSocketWrapper = exports.subscribeToEntityEvents = void 0;
14
13
  const WebSocketNode = require("ws");
15
- const loglevel_1 = require("loglevel");
16
14
  const User_1 = require("../../icc-api/model/User");
17
15
  const browser_or_node_1 = require("browser-or-node");
18
16
  const HealthcareParty_1 = require("../../icc-api/model/HealthcareParty");
19
17
  const Device_1 = require("../../icc-api/model/Device");
20
- loglevel_1.default.setLevel((_a = process.env.WEBSOCKET_LOG_LEVEL) !== null && _a !== void 0 ? _a : 'info');
21
18
  function subscribeToEntityEvents(basePath, authApi, entityClass, eventTypes, filter, eventFired, options = {}, decryptor) {
22
19
  var _a, _b;
23
20
  const config = {
@@ -70,20 +67,20 @@ function subscribeToEntityEvents(basePath, authApi, entityClass, eventTypes, fil
70
67
  yield config[entityClass].decryptor(data).then((o) => eventFired(o));
71
68
  }
72
69
  catch (e) {
73
- loglevel_1.default.error(e);
70
+ console.error(e);
74
71
  }
75
- }));
72
+ }), options.debug);
76
73
  }
77
74
  exports.subscribeToEntityEvents = subscribeToEntityEvents;
78
75
  class WebSocketWrapper {
79
- constructor(url, authProvider, maxRetries = 3, retryDelay = 1000, statusCallbacks = {}, messageCallback = () => {
80
- }) {
76
+ constructor(url, authProvider, maxRetries = 3, retryDelay = 1000, statusCallbacks = {}, messageCallback = () => { }, debug = false) {
81
77
  this.url = url;
82
78
  this.authProvider = authProvider;
83
79
  this.maxRetries = maxRetries;
84
80
  this.retryDelay = retryDelay;
85
81
  this.statusCallbacks = statusCallbacks;
86
82
  this.messageCallback = messageCallback;
83
+ this.debug = debug;
87
84
  this.pingLifetime = 20000;
88
85
  this.socket = null;
89
86
  this.retries = 0;
@@ -92,9 +89,9 @@ class WebSocketWrapper {
92
89
  this.intervalIds = [];
93
90
  this.methodPath = new URL(url).pathname;
94
91
  }
95
- static create(url, authProvider, maxRetries, retryDelay, statusCallbacks, messageCallback) {
92
+ static create(url, authProvider, maxRetries, retryDelay, statusCallbacks, messageCallback, debug) {
96
93
  return __awaiter(this, void 0, void 0, function* () {
97
- const ws = new WebSocketWrapper(url, authProvider, maxRetries, retryDelay, statusCallbacks, messageCallback);
94
+ const ws = new WebSocketWrapper(url, authProvider, maxRetries, retryDelay, statusCallbacks, messageCallback, debug);
98
95
  yield ws.connect();
99
96
  return ws;
100
97
  });
@@ -141,23 +138,26 @@ class WebSocketWrapper {
141
138
  });
142
139
  this.socket = new WebsocketAdapter(socket);
143
140
  this.socket.on('open', () => __awaiter(this, void 0, void 0, function* () {
144
- loglevel_1.default.debug('WebSocket connection opened');
141
+ if (this.debug)
142
+ console.debug('WebSocket connection opened');
145
143
  this.intervalIds.push(setTimeout(() => {
146
144
  this.retries = 0;
147
145
  }, (this.maxRetries + 1) * this.retryDelay));
148
146
  this.callStatusCallbacks('CONNECTED');
149
147
  }));
150
148
  this.socket.on('message', (event) => {
151
- loglevel_1.default.debug('WebSocket message received', event);
149
+ if (this.debug)
150
+ console.debug('WebSocket message received', event);
152
151
  // Handle ping messages
153
152
  if (event === 'ping') {
154
- loglevel_1.default.debug('Received ping, sending pong');
153
+ if (this.debug)
154
+ console.debug('Received ping, sending pong');
155
155
  this.send('pong');
156
156
  this.lastPingReceived = Date.now();
157
157
  this.intervalIds.push(setTimeout(() => {
158
158
  var _a;
159
159
  if (Date.now() - this.lastPingReceived > this.pingLifetime) {
160
- loglevel_1.default.error(`No ping received in the last ${this.pingLifetime} ms`);
160
+ console.error(`No ping received in the last ${this.pingLifetime} ms`);
161
161
  (_a = this.socket) === null || _a === void 0 ? void 0 : _a.close();
162
162
  }
163
163
  }, this.pingLifetime));
@@ -169,11 +169,12 @@ class WebSocketWrapper {
169
169
  this.messageCallback(data);
170
170
  }
171
171
  catch (error) {
172
- loglevel_1.default.error('Failed to parse WebSocket message', error);
172
+ console.error('Failed to parse WebSocket message', error);
173
173
  }
174
174
  });
175
175
  this.socket.on('close', ({ code, reason }) => {
176
- loglevel_1.default.debug('WebSocket connection closed', code, reason === null || reason === void 0 ? void 0 : reason.toString());
176
+ if (this.debug)
177
+ console.debug('WebSocket connection closed', code, reason === null || reason === void 0 ? void 0 : reason.toString());
177
178
  this.callStatusCallbacks('CLOSED');
178
179
  this.intervalIds.forEach((id) => clearTimeout(id));
179
180
  this.intervalIds = [];
@@ -186,7 +187,7 @@ class WebSocketWrapper {
186
187
  }), this.retryDelay);
187
188
  });
188
189
  this.socket.on('error', (err) => __awaiter(this, void 0, void 0, function* () {
189
- loglevel_1.default.error('WebSocket error', err);
190
+ console.error('WebSocket error', err);
190
191
  this.callStatusCallbacks('ERROR', err);
191
192
  if (this.socket) {
192
193
  this.socket.close();
@@ -292,9 +293,9 @@ class WebsocketAdapter {
292
293
  dataAsString = event.data;
293
294
  }
294
295
  else
295
- loglevel_1.default.error("Unexpected event type: " + event.type);
296
+ console.error("Unexpected event type: " + event.type);
296
297
  if (!dataAsString) {
297
- loglevel_1.default.error("Failed to parse WebSocket message");
298
+ console.error("Failed to parse WebSocket message");
298
299
  return;
299
300
  }
300
301
  callback(dataAsString);
@@ -302,7 +303,7 @@ class WebsocketAdapter {
302
303
  }
303
304
  }
304
305
  else {
305
- loglevel_1.default.error("Websocket is not defined");
306
+ console.error("Websocket is not defined");
306
307
  throw new Error('Websocket is not defined');
307
308
  }
308
309
  }
@@ -1 +1 @@
1
- {"version":3,"file":"websocket.js","sourceRoot":"","sources":["../../../icc-x-api/utils/websocket.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,oCAAmC;AACnC,uCAA0C;AAG1C,mDAA6C;AAC7C,qDAAiD;AAKjD,yEAAmE;AACnE,uDAAiD;AAWjD,kBAAG,CAAC,QAAQ,CAAC,MAAC,OAAO,CAAC,GAAG,CAAC,mBAAoC,mCAAI,MAAM,CAAC,CAAA;AAgFzE,SAAgB,uBAAuB,CACrC,QAAgB,EAChB,OAAmB,EACnB,WAAyB,EACzB,UAAwB,EACxB,MAAqC,EACrC,UAAwC,EACxC,UAA+B,EAAE,EACjC,SAAwC;;IAExC,MAAM,MAAM,GAAG;QACb,IAAI,EAAE;YACJ,aAAa,EAAE,gCAAgC;YAC/C,SAAS,EAAE,CAAC,IAAU,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,WAAI,mBAAK,IAAI,EAAO,CAAC;SACrE;QACD,OAAO,EAAE;YACP,aAAa,EAAE,mCAAmC;YAClD,SAAS,EAAE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AE;gBACb,KAAK,SAAS;oBACZ,OAAO,IAAI,CAAC,SAAS,CAAC,QAAoC,CAAC,CAAA;gBAC7D,KAAK,MAAM;oBACT,OAAO,IAAI,CAAC,MAAM,CAAC,QAAiC,CAAC,CAAA;gBACvD,KAAK,OAAO;oBACV,OAAO,IAAI,CAAC,OAAO,CAAC,QAAkC,CAAC,CAAA;gBACzD,KAAK,OAAO;oBACV,OAAO,IAAI,CAAC,OAAO,CAAC,QAAkC,CAAC,CAAA;aAC1D;SACF;IACH,CAAC;CACF","sourcesContent":["import * as WebSocketNode from 'ws'\nimport log, {LogLevelDesc} from 'loglevel'\nimport {Patient} from \"../../icc-api/model/Patient\"\nimport {AbstractFilter} from \"../filters/filters\"\nimport {User} from \"../../icc-api/model/User\"\nimport {isBrowser, isNode} from \"browser-or-node\"\nimport {IccAuthApi} from \"../../icc-api\"\nimport {Service} from \"../../icc-api/model/Service\"\nimport {HealthElement} from \"../../icc-api/model/HealthElement\"\nimport {MaintenanceTask} from \"../../icc-api/model/MaintenanceTask\"\nimport {HealthcareParty} from \"../../icc-api/model/HealthcareParty\"\nimport {Device} from \"../../icc-api/model/Device\"\nimport {Contact} from \"../../icc-api/model/Contact\"\n\nexport type EventTypes = 'CREATE' | 'UPDATE' | 'DELETE'\ntype Subscribable = 'Patient' | 'Service' | 'User' | 'HealthElement' | 'MaintenanceTask' | 'HealthcareParty' | 'Device' | 'Contact'\ntype SubscribableEntity = Patient | Service | User | HealthElement | MaintenanceTask | HealthcareParty | Device | Contact\ntype SubscriptionOptions = {\n connectionMaxRetry?: number\n connectionRetryIntervalMs?: number\n}\n\nlog.setLevel((process.env.WEBSOCKET_LOG_LEVEL as LogLevelDesc) ?? 'info')\n\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'Patient',\n eventTypes: EventTypes[],\n filter: AbstractFilter<Patient> | undefined,\n eventFired: (entity: Patient) => Promise<void>,\n options: SubscriptionOptions,\n decryptor: (encrypted: Patient) => Promise<Patient>\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'Service',\n eventTypes: EventTypes[],\n filter: AbstractFilter<Service> | undefined,\n eventFired: (entity: Service) => Promise<void>,\n options: SubscriptionOptions,\n decryptor: (encrypted: Service) => Promise<Service>\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'Contact',\n eventTypes: EventTypes[],\n filter: AbstractFilter<Contact> | undefined,\n eventFired: (entity: Contact) => Promise<void>,\n options: SubscriptionOptions,\n decryptor: (encrypted: Contact) => Promise<Contact>\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'HealthElement',\n eventTypes: EventTypes[],\n filter: AbstractFilter<HealthElement> | undefined,\n eventFired: (entity: HealthElement) => Promise<void>,\n options: SubscriptionOptions,\n decryptor: (encrypted: HealthElement) => Promise<HealthElement>\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'User',\n eventTypes: EventTypes[],\n filter: AbstractFilter<User> | undefined,\n eventFired: (entity: User) => Promise<void>,\n options: SubscriptionOptions\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'MaintenanceTask',\n eventTypes: EventTypes[],\n filter: AbstractFilter<MaintenanceTask> | undefined,\n eventFired: (entity: MaintenanceTask) => Promise<void>,\n options: SubscriptionOptions,\n decryptor: (encrypted: MaintenanceTask) => Promise<MaintenanceTask>\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'HealthcareParty',\n eventTypes: EventTypes[],\n filter: AbstractFilter<HealthcareParty> | undefined,\n eventFired: (entity: HealthcareParty) => Promise<void>,\n options: SubscriptionOptions,\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'Device',\n eventTypes: EventTypes[],\n filter: AbstractFilter<Device> | undefined,\n eventFired: (entity: Device) => Promise<void>,\n options: SubscriptionOptions,\n): Promise<WebSocketWrapper>\n\nexport function subscribeToEntityEvents<T extends SubscribableEntity>(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: Subscribable,\n eventTypes: EventTypes[],\n filter: AbstractFilter<T> | undefined,\n eventFired: (entity: T) => Promise<void>,\n options: SubscriptionOptions = {},\n decryptor?: (encrypted: T) => Promise<T>\n): Promise<WebSocketWrapper> {\n const config = {\n User: {\n qualifiedName: 'org.taktik.icure.entities.User',\n decryptor: (data: User) => Promise.resolve(new User({...data}) as T),\n },\n Patient: {\n qualifiedName: 'org.taktik.icure.entities.Patient',\n decryptor: (data: Patient) => decryptor!(data as Patient as T),\n },\n Service: {\n qualifiedName: 'org.taktik.icure.entities.embed.Service',\n decryptor: (data: Service) => decryptor!(data as Service as T),\n },\n HealthElement: {\n qualifiedName: 'org.taktik.icure.entities.HealthElement',\n decryptor: (data: HealthElement) =>\n decryptor!(data as HealthElement as T),\n },\n MaintenanceTask: {\n qualifiedName: 'org.taktik.icure.entities.MaintenanceTask',\n decryptor: (data: MaintenanceTask) =>\n decryptor!(data as MaintenanceTask as T),\n },\n HealthcareParty: {\n qualifiedName: 'org.taktik.icure.entities.HealthcareParty',\n decryptor: (data: HealthcareParty) =>\n Promise.resolve(new HealthcareParty({...data}) as HealthcareParty as T),\n },\n Device: {\n qualifiedName: 'org.taktik.icure.entities.Device',\n decryptor: (data: Device) =>\n Promise.resolve(new Device({...data}) as Device as T),\n },\n Contact: {\n qualifiedName: 'org.taktik.icure.entities.Contact',\n decryptor: (data: Contact) => decryptor!(data as Contact as T),\n },\n }\n\n return WebSocketWrapper.create(\n basePath.replace('http', 'ws').replace('rest', 'ws') + '/notification/subscribe',\n new WebSocketAuthProviderImpl(authApi),\n options.connectionMaxRetry ?? 5,\n options.connectionRetryIntervalMs ?? 1_000,\n {\n CONNECTED: [\n async (ws: WebSocketWrapper) => {\n const subscription = {\n eventTypes,\n entityClass: config[entityClass].qualifiedName,\n filter: {filter}\n }\n\n ws.send(JSON.stringify(subscription))\n },\n ],\n },\n async (data: any) => {\n try {\n await config[entityClass].decryptor(data).then((o) => eventFired(o))\n } catch (e) {\n log.error(e)\n }\n }\n )\n}\n\nexport type ConnectionStatus = 'NOT_CONNECTED' | 'CONNECTED' | 'CLOSED' | 'ERROR'\nexport type StatusCallback = (ws: WebSocketWrapper) => void\nexport type ErrorStatusCallback = (ws: WebSocketWrapper, error?: Error) => void\nexport type ConnectionStatusFunction = {\n [K in ConnectionStatus]: K extends 'ERROR' ? ErrorStatusCallback : StatusCallback\n}\nexport type ConnectionStatusFunctions = {\n [K in ConnectionStatus]?: K extends 'ERROR' ? Array<ErrorStatusCallback> : Array<StatusCallback>\n}\nexport type WebSocketWrapperMessageCallback = (data: any) => void\n\nexport class WebSocketWrapper {\n private readonly pingLifetime: number = 20_000\n private socket: WebsocketAdapter | null = null\n private retries = 0\n private closed = false\n private lastPingReceived = Date.now()\n private intervalIds: (NodeJS.Timeout | number)[] = []\n private readonly methodPath: string\n\n private constructor(\n private readonly url: string,\n private readonly authProvider: WebSocketAuthProvider,\n private readonly maxRetries = 3,\n private readonly retryDelay = 1000,\n private readonly statusCallbacks: ConnectionStatusFunctions = {},\n private readonly messageCallback: WebSocketWrapperMessageCallback = () => {\n }\n ) {\n this.methodPath = new URL(url).pathname\n }\n\n public static async create(\n url: string,\n authProvider: WebSocketAuthProvider,\n maxRetries?: number,\n retryDelay?: number,\n statusCallbacks?: ConnectionStatusFunctions,\n messageCallback?: WebSocketWrapperMessageCallback\n ): Promise<WebSocketWrapper> {\n const ws = new WebSocketWrapper(url, authProvider, maxRetries, retryDelay, statusCallbacks, messageCallback)\n await ws.connect()\n return ws\n }\n\n public send(data: Buffer | ArrayBuffer | string) {\n if (this.socket && this.socket.readyState === ReadyState.OPEN) {\n this.socket.send(data)\n }\n }\n\n public close() {\n if (this.socket) {\n this.closed = true\n this.socket.close(1000, 'Client closed connection')\n }\n }\n\n public addStatusCallback(status: ConnectionStatus, callback: ConnectionStatusFunction[ConnectionStatus]) {\n switch (status) {\n case 'CONNECTED':\n case 'CLOSED':\n if (!this.statusCallbacks[status]) this.statusCallbacks[status] = []\n this.statusCallbacks?.[status]?.push(callback)\n break\n case 'ERROR':\n this.statusCallbacks?.ERROR?.push(callback)\n break\n }\n }\n\n private async connect() {\n if (this.retries >= this.maxRetries) {\n throw new Error('WebSocket connection failed after ' + this.maxRetries + ' retries')\n }\n\n const bearerToken = await this.authProvider.getBearerToken()\n\n const socket = isNode && !!bearerToken ? new WebSocketNode(this.url, {\n headers: {\n Authorization: bearerToken,\n },\n })\n : await this.authProvider.getIcureOtt(this.methodPath).then((icureOttToken) => {\n const address = `${this.url};tokenid=${icureOttToken}`\n return isNode ? new WebSocketNode(address) : new WebSocket(address)\n })\n\n this.socket = new WebsocketAdapter(socket)\n\n this.socket.on('open', async () => {\n log.debug('WebSocket connection opened')\n\n this.intervalIds.push(\n setTimeout(() => {\n this.retries = 0\n }, (this.maxRetries + 1) * this.retryDelay)\n )\n\n this.callStatusCallbacks('CONNECTED')\n })\n\n this.socket.on('message', (event: string) => {\n log.debug('WebSocket message received', event)\n\n // Handle ping messages\n if (event === 'ping') {\n log.debug('Received ping, sending pong')\n\n this.send('pong')\n this.lastPingReceived = Date.now()\n\n this.intervalIds.push(\n setTimeout(() => {\n if (Date.now() - this.lastPingReceived > this.pingLifetime) {\n log.error(`No ping received in the last ${this.pingLifetime} ms`)\n this.socket?.close()\n }\n }, this.pingLifetime)\n )\n\n return\n }\n\n // Call the message callback for other messages\n try {\n const data = JSON.parse(event)\n this.messageCallback(data)\n } catch (error) {\n log.error('Failed to parse WebSocket message', error)\n }\n })\n\n this.socket.on('close', ({code, reason}) => {\n log.debug('WebSocket connection closed', code, reason?.toString())\n\n this.callStatusCallbacks('CLOSED')\n\n this.intervalIds.forEach((id) => clearTimeout(id as number))\n this.intervalIds = []\n\n if (this.closed) {\n return\n }\n\n setTimeout(async () => {\n ++this.retries\n return await this.connect()\n }, this.retryDelay)\n })\n\n this.socket.on('error', async (err) => {\n log.error('WebSocket error', err)\n\n this.callStatusCallbacks('ERROR', err)\n\n if (this.socket) {\n this.socket.close()\n }\n })\n }\n\n private callStatusCallbacks(event: ConnectionStatus, error?: Error) {\n switch (event) {\n case 'CONNECTED':\n case 'CLOSED':\n this.statusCallbacks?.[event]?.forEach((callback) => callback(this))\n break\n case 'ERROR':\n this.statusCallbacks?.ERROR?.forEach((callback) => callback(this, error))\n break\n }\n }\n}\n\ninterface WebSocketAuthProvider {\n getBearerToken(): Promise<string | undefined>\n\n getIcureOtt(icureMethodPath: string): Promise<string>\n}\n\nclass WebSocketAuthProviderImpl {\n constructor(private readonly authApi: IccAuthApi) {\n }\n\n async getBearerToken(): Promise<string | undefined> {\n const headers = await this.authApi.authenticationProvider.getAuthService().getAuthHeaders()\n return headers.find((header) => header.header === 'Authorization' && header.data.startsWith('Bearer '))?.data\n }\n\n async getIcureOtt(icureMethodPath: string): Promise<string> {\n return await this.authApi.token('GET', icureMethodPath)\n }\n}\n\ntype EventCallback = {\n open: (event: any) => void,\n message: (event: string) => void,\n close: (event: {code: number, reason: string}) => void,\n error: (error: any) => void\n}\n\nenum ReadyState {\n CONNECTING = 0,\n OPEN = 1,\n CLOSING = 2,\n CLOSED = 3\n}\n\nclass WebsocketAdapter {\n constructor(\n private readonly websocket: WebSocketNode | WebSocket,\n ) {\n }\n\n public get readyState(): number {\n if (this.websocket) {\n if (isNode) {\n switch ((this.websocket as WebSocketNode).readyState) {\n case WebSocketNode.CONNECTING:\n return ReadyState.CONNECTING\n case WebSocketNode.OPEN:\n return ReadyState.OPEN\n case WebSocketNode.CLOSING:\n return ReadyState.CLOSING\n case WebSocketNode.CLOSED:\n return ReadyState.CLOSED\n }\n } else {\n switch ((this.websocket as WebSocket).readyState) {\n case WebSocket.CONNECTING:\n return ReadyState.CONNECTING\n case WebSocket.OPEN:\n return ReadyState.OPEN\n case WebSocket.CLOSING:\n return ReadyState.CLOSING\n case WebSocket.CLOSED:\n return ReadyState.CLOSED\n }\n }\n }\n return ReadyState.CLOSED\n }\n\n /**\n * This is not throwing an error if the websocket is not open, because the purpose of the websocket wrapper is custom to notifications needs (subscribe and ping pong only)\n * If in the future we need to use it for other purposes, we will have to throw an error and update the implementation of ping pong in the notification\n * @param data the data to send\n */\n public send(data: Buffer | ArrayBuffer | string) {\n if (this.websocket && this.readyState === ReadyState.OPEN) {\n this.websocket.send(data)\n }\n }\n\n public close(code?: number, reason?: string) {\n if (this.websocket) {\n this.websocket.close(code, reason)\n }\n }\n\n private onMessage(callback: (event: string) => void) {\n if (this.websocket) {\n if (isNode) {\n (this.websocket as WebSocketNode).on('message', (x) => callback(x.toString('utf8')))\n } else {\n (this.websocket as WebSocket).addEventListener('message', async (event) => {\n let dataAsString: string | undefined\n if (event.type === 'message') {\n dataAsString = event.data\n } else log.error(\"Unexpected event type: \" + event.type)\n if (!dataAsString) {\n log.error(\"Failed to parse WebSocket message\")\n return\n }\n\n callback(dataAsString)\n })\n }\n }\n else {\n log.error(\"Websocket is not defined\")\n throw new Error('Websocket is not defined')\n }\n }\n\n private onOpen(callback: (event: any) => void) {\n if (this.websocket) {\n if (isNode) {\n (this.websocket as WebSocketNode).on('open', callback)\n } else {\n (this.websocket as WebSocket).addEventListener('open', callback)\n }\n }\n }\n\n private onClose(callback: (event: {code: number, reason: string}) => void) {\n if (this.websocket) {\n if (isNode) {\n (this.websocket as WebSocketNode).on('close', callback)\n } else {\n (this.websocket as WebSocket).addEventListener('close', callback)\n }\n }\n }\n\n private onError(callback: (error: any) => void) {\n if (this.websocket) {\n if (isNode) {\n (this.websocket as WebSocketNode).on('error', callback)\n } else {\n (this.websocket as WebSocket).addEventListener('error', callback)\n }\n }\n }\n\n\n public on<K extends keyof EventCallback>(event: K, callback: EventCallback[K]) {\n if (this.websocket) {\n switch (event) {\n case 'message':\n return this.onMessage(callback as EventCallback['message'])\n case 'open':\n return this.onOpen(callback as EventCallback['open'])\n case 'close':\n return this.onClose(callback as EventCallback['close'])\n case 'error':\n return this.onError(callback as EventCallback['error'])\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"websocket.js","sourceRoot":"","sources":["../../../icc-x-api/utils/websocket.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAAmC;AAGnC,mDAA6C;AAC7C,qDAAsC;AAKtC,yEAAmE;AACnE,uDAAiD;AA0FjD,SAAgB,uBAAuB,CACrC,QAAgB,EAChB,OAAmB,EACnB,WAAyB,EACzB,UAAwB,EACxB,MAAqC,EACrC,UAAwC,EACxC,UAA+B,EAAE,EACjC,SAAwC;;IAExC,MAAM,MAAM,GAAG;QACb,IAAI,EAAE;YACJ,aAAa,EAAE,gCAAgC;YAC/C,SAAS,EAAE,CAAC,IAAU,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,WAAI,mBAAK,IAAI,EAAO,CAAC;SACrE;QACD,OAAO,EAAE;YACP,aAAa,EAAE,mCAAmC;YAClD,SAAS,EAAE,CAAC,IAAa,EAAE,EAAE,CAAC,SAAU,CAAC,IAAoB,CAAC;SAC/D;QACD,OAAO,EAAE;YACP,aAAa,EAAE,yCAAyC;YACxD,SAAS,EAAE,CAAC,IAAa,EAAE,EAAE,CAAC,SAAU,CAAC,IAAoB,CAAC;SAC/D;QACD,aAAa,EAAE;YACb,aAAa,EAAE,yCAAyC;YACxD,SAAS,EAAE,CAAC,IAAmB,EAAE,EAAE,CACjC,SAAU,CAAC,IAA0B,CAAC;SACzC;QACD,eAAe,EAAE;YACf,aAAa,EAAE,2CAA2C;YAC1D,SAAS,EAAE,CAAC,IAAqB,EAAE,EAAE,CACnC,SAAU,CAAC,IAA4B,CAAC;SAC3C;QACD,eAAe,EAAE;YACf,aAAa,EAAE,2CAA2C;YAC1D,SAAS,EAAE,CA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QAAkC,CAAC,CAAA;aAC1D;SACF;IACH,CAAC;CACF","sourcesContent":["import * as WebSocketNode from 'ws'\nimport {Patient} from \"../../icc-api/model/Patient\"\nimport {AbstractFilter} from \"../filters/filters\"\nimport {User} from \"../../icc-api/model/User\"\nimport {isNode} from \"browser-or-node\"\nimport {IccAuthApi} from \"../../icc-api\"\nimport {Service} from \"../../icc-api/model/Service\"\nimport {HealthElement} from \"../../icc-api/model/HealthElement\"\nimport {MaintenanceTask} from \"../../icc-api/model/MaintenanceTask\"\nimport {HealthcareParty} from \"../../icc-api/model/HealthcareParty\"\nimport {Device} from \"../../icc-api/model/Device\"\nimport {Contact} from \"../../icc-api/model/Contact\"\n\nexport type EventTypes = 'CREATE' | 'UPDATE' | 'DELETE'\ntype Subscribable = 'Patient' | 'Service' | 'User' | 'HealthElement' | 'MaintenanceTask' | 'HealthcareParty' | 'Device' | 'Contact'\ntype SubscribableEntity = Patient | Service | User | HealthElement | MaintenanceTask | HealthcareParty | Device | Contact\nexport type SubscriptionOptions = {\n connectionMaxRetry?: number\n connectionRetryIntervalMs?: number\n debug?: boolean\n}\n\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'Patient',\n eventTypes: EventTypes[],\n filter: AbstractFilter<Patient> | undefined,\n eventFired: (entity: Patient) => Promise<void>,\n options: SubscriptionOptions,\n decryptor: (encrypted: Patient) => Promise<Patient>\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'Service',\n eventTypes: EventTypes[],\n filter: AbstractFilter<Service> | undefined,\n eventFired: (entity: Service) => Promise<void>,\n options: SubscriptionOptions,\n decryptor: (encrypted: Service) => Promise<Service>\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'Contact',\n eventTypes: EventTypes[],\n filter: AbstractFilter<Contact> | undefined,\n eventFired: (entity: Contact) => Promise<void>,\n options: SubscriptionOptions,\n decryptor: (encrypted: Contact) => Promise<Contact>\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'HealthElement',\n eventTypes: EventTypes[],\n filter: AbstractFilter<HealthElement> | undefined,\n eventFired: (entity: HealthElement) => Promise<void>,\n options: SubscriptionOptions,\n decryptor: (encrypted: HealthElement) => Promise<HealthElement>\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'User',\n eventTypes: EventTypes[],\n filter: AbstractFilter<User> | undefined,\n eventFired: (entity: User) => Promise<void>,\n options: SubscriptionOptions\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'MaintenanceTask',\n eventTypes: EventTypes[],\n filter: AbstractFilter<MaintenanceTask> | undefined,\n eventFired: (entity: MaintenanceTask) => Promise<void>,\n options: SubscriptionOptions,\n decryptor: (encrypted: MaintenanceTask) => Promise<MaintenanceTask>\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'HealthcareParty',\n eventTypes: EventTypes[],\n filter: AbstractFilter<HealthcareParty> | undefined,\n eventFired: (entity: HealthcareParty) => Promise<void>,\n options: SubscriptionOptions,\n): Promise<WebSocketWrapper>\nexport function subscribeToEntityEvents(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: 'Device',\n eventTypes: EventTypes[],\n filter: AbstractFilter<Device> | undefined,\n eventFired: (entity: Device) => Promise<void>,\n options: SubscriptionOptions,\n): Promise<WebSocketWrapper>\n\nexport function subscribeToEntityEvents<T extends SubscribableEntity>(\n basePath: string,\n authApi: IccAuthApi,\n entityClass: Subscribable,\n eventTypes: EventTypes[],\n filter: AbstractFilter<T> | undefined,\n eventFired: (entity: T) => Promise<void>,\n options: SubscriptionOptions = {},\n decryptor?: (encrypted: T) => Promise<T>\n): Promise<WebSocketWrapper> {\n const config = {\n User: {\n qualifiedName: 'org.taktik.icure.entities.User',\n decryptor: (data: User) => Promise.resolve(new User({...data}) as T),\n },\n Patient: {\n qualifiedName: 'org.taktik.icure.entities.Patient',\n decryptor: (data: Patient) => decryptor!(data as Patient as T),\n },\n Service: {\n qualifiedName: 'org.taktik.icure.entities.embed.Service',\n decryptor: (data: Service) => decryptor!(data as Service as T),\n },\n HealthElement: {\n qualifiedName: 'org.taktik.icure.entities.HealthElement',\n decryptor: (data: HealthElement) =>\n decryptor!(data as HealthElement as T),\n },\n MaintenanceTask: {\n qualifiedName: 'org.taktik.icure.entities.MaintenanceTask',\n decryptor: (data: MaintenanceTask) =>\n decryptor!(data as MaintenanceTask as T),\n },\n HealthcareParty: {\n qualifiedName: 'org.taktik.icure.entities.HealthcareParty',\n decryptor: (data: HealthcareParty) =>\n Promise.resolve(new HealthcareParty({...data}) as HealthcareParty as T),\n },\n Device: {\n qualifiedName: 'org.taktik.icure.entities.Device',\n decryptor: (data: Device) =>\n Promise.resolve(new Device({...data}) as Device as T),\n },\n Contact: {\n qualifiedName: 'org.taktik.icure.entities.Contact',\n decryptor: (data: Contact) => decryptor!(data as Contact as T),\n },\n }\n\n return WebSocketWrapper.create(\n basePath.replace('http', 'ws').replace('rest', 'ws') + '/notification/subscribe',\n new WebSocketAuthProviderImpl(authApi),\n options.connectionMaxRetry ?? 5,\n options.connectionRetryIntervalMs ?? 1_000,\n {\n CONNECTED: [\n async (ws: WebSocketWrapper) => {\n const subscription = {\n eventTypes,\n entityClass: config[entityClass].qualifiedName,\n filter: {filter}\n }\n\n ws.send(JSON.stringify(subscription))\n },\n ],\n },\n async (data: any) => {\n try {\n await config[entityClass].decryptor(data).then((o) => eventFired(o))\n } catch (e) {\n console.error(e)\n }\n },\n options.debug,\n )\n}\n\nexport type ConnectionStatus = 'NOT_CONNECTED' | 'CONNECTED' | 'CLOSED' | 'ERROR'\nexport type StatusCallback = (ws: WebSocketWrapper) => void\nexport type ErrorStatusCallback = (ws: WebSocketWrapper, error?: Error) => void\nexport type ConnectionStatusFunction = {\n [K in ConnectionStatus]: K extends 'ERROR' ? ErrorStatusCallback : StatusCallback\n}\nexport type ConnectionStatusFunctions = {\n [K in ConnectionStatus]?: K extends 'ERROR' ? Array<ErrorStatusCallback> : Array<StatusCallback>\n}\nexport type WebSocketWrapperMessageCallback = (data: any) => void\n\nexport class WebSocketWrapper {\n private readonly pingLifetime: number = 20_000\n private socket: WebsocketAdapter | null = null\n private retries = 0\n private closed = false\n private lastPingReceived = Date.now()\n private intervalIds: (NodeJS.Timeout | number)[] = []\n private readonly methodPath: string\n\n private constructor(\n private readonly url: string,\n private readonly authProvider: WebSocketAuthProvider,\n private readonly maxRetries = 3,\n private readonly retryDelay = 1000,\n private readonly statusCallbacks: ConnectionStatusFunctions = {},\n private readonly messageCallback: WebSocketWrapperMessageCallback = () => {},\n private readonly debug: boolean = false\n) {\n this.methodPath = new URL(url).pathname\n }\n\n public static async create(\n url: string,\n authProvider: WebSocketAuthProvider,\n maxRetries?: number,\n retryDelay?: number,\n statusCallbacks?: ConnectionStatusFunctions,\n messageCallback?: WebSocketWrapperMessageCallback,\n debug?: boolean,\n ): Promise<WebSocketWrapper> {\n const ws = new WebSocketWrapper(url, authProvider, maxRetries, retryDelay, statusCallbacks, messageCallback, debug)\n await ws.connect()\n return ws\n }\n\n public send(data: Buffer | ArrayBuffer | string) {\n if (this.socket && this.socket.readyState === ReadyState.OPEN) {\n this.socket.send(data)\n }\n }\n\n public close() {\n if (this.socket) {\n this.closed = true\n this.socket.close(1000, 'Client closed connection')\n }\n }\n\n public addStatusCallback(status: ConnectionStatus, callback: ConnectionStatusFunction[ConnectionStatus]) {\n switch (status) {\n case 'CONNECTED':\n case 'CLOSED':\n if (!this.statusCallbacks[status]) this.statusCallbacks[status] = []\n this.statusCallbacks?.[status]?.push(callback)\n break\n case 'ERROR':\n this.statusCallbacks?.ERROR?.push(callback)\n break\n }\n }\n\n private async connect() {\n if (this.retries >= this.maxRetries) {\n throw new Error('WebSocket connection failed after ' + this.maxRetries + ' retries')\n }\n\n const bearerToken = await this.authProvider.getBearerToken()\n\n const socket = isNode && !!bearerToken ? new WebSocketNode(this.url, {\n headers: {\n Authorization: bearerToken,\n },\n })\n : await this.authProvider.getIcureOtt(this.methodPath).then((icureOttToken) => {\n const address = `${this.url};tokenid=${icureOttToken}`\n return isNode ? new WebSocketNode(address) : new WebSocket(address)\n })\n\n this.socket = new WebsocketAdapter(socket)\n\n this.socket.on('open', async () => {\n if (this.debug) console.debug('WebSocket connection opened')\n\n this.intervalIds.push(\n setTimeout(() => {\n this.retries = 0\n }, (this.maxRetries + 1) * this.retryDelay)\n )\n\n this.callStatusCallbacks('CONNECTED')\n })\n\n this.socket.on('message', (event: string) => {\n if (this.debug) console.debug('WebSocket message received', event)\n\n // Handle ping messages\n if (event === 'ping') {\n if (this.debug) console.debug('Received ping, sending pong')\n\n this.send('pong')\n this.lastPingReceived = Date.now()\n\n this.intervalIds.push(\n setTimeout(() => {\n if (Date.now() - this.lastPingReceived > this.pingLifetime) {\n console.error(`No ping received in the last ${this.pingLifetime} ms`)\n this.socket?.close()\n }\n }, this.pingLifetime)\n )\n\n return\n }\n\n // Call the message callback for other messages\n try {\n const data = JSON.parse(event)\n this.messageCallback(data)\n } catch (error) {\n console.error('Failed to parse WebSocket message', error)\n }\n })\n\n this.socket.on('close', ({code, reason}) => {\n if (this.debug) console.debug('WebSocket connection closed', code, reason?.toString())\n\n this.callStatusCallbacks('CLOSED')\n\n this.intervalIds.forEach((id) => clearTimeout(id as number))\n this.intervalIds = []\n\n if (this.closed) {\n return\n }\n\n setTimeout(async () => {\n ++this.retries\n return await this.connect()\n }, this.retryDelay)\n })\n\n this.socket.on('error', async (err) => {\n console.error('WebSocket error', err)\n\n this.callStatusCallbacks('ERROR', err)\n\n if (this.socket) {\n this.socket.close()\n }\n })\n }\n\n private callStatusCallbacks(event: ConnectionStatus, error?: Error) {\n switch (event) {\n case 'CONNECTED':\n case 'CLOSED':\n this.statusCallbacks?.[event]?.forEach((callback) => callback(this))\n break\n case 'ERROR':\n this.statusCallbacks?.ERROR?.forEach((callback) => callback(this, error))\n break\n }\n }\n}\n\ninterface WebSocketAuthProvider {\n getBearerToken(): Promise<string | undefined>\n\n getIcureOtt(icureMethodPath: string): Promise<string>\n}\n\nclass WebSocketAuthProviderImpl {\n constructor(private readonly authApi: IccAuthApi) {\n }\n\n async getBearerToken(): Promise<string | undefined> {\n const headers = await this.authApi.authenticationProvider.getAuthService().getAuthHeaders()\n return headers.find((header) => header.header === 'Authorization' && header.data.startsWith('Bearer '))?.data\n }\n\n async getIcureOtt(icureMethodPath: string): Promise<string> {\n return await this.authApi.token('GET', icureMethodPath)\n }\n}\n\ntype EventCallback = {\n open: (event: any) => void,\n message: (event: string) => void,\n close: (event: {code: number, reason: string}) => void,\n error: (error: any) => void\n}\n\nenum ReadyState {\n CONNECTING = 0,\n OPEN = 1,\n CLOSING = 2,\n CLOSED = 3\n}\n\nclass WebsocketAdapter {\n constructor(\n private readonly websocket: WebSocketNode | WebSocket,\n ) {\n }\n\n public get readyState(): number {\n if (this.websocket) {\n if (isNode) {\n switch ((this.websocket as WebSocketNode).readyState) {\n case WebSocketNode.CONNECTING:\n return ReadyState.CONNECTING\n case WebSocketNode.OPEN:\n return ReadyState.OPEN\n case WebSocketNode.CLOSING:\n return ReadyState.CLOSING\n case WebSocketNode.CLOSED:\n return ReadyState.CLOSED\n }\n } else {\n switch ((this.websocket as WebSocket).readyState) {\n case WebSocket.CONNECTING:\n return ReadyState.CONNECTING\n case WebSocket.OPEN:\n return ReadyState.OPEN\n case WebSocket.CLOSING:\n return ReadyState.CLOSING\n case WebSocket.CLOSED:\n return ReadyState.CLOSED\n }\n }\n }\n return ReadyState.CLOSED\n }\n\n /**\n * This is not throwing an error if the websocket is not open, because the purpose of the websocket wrapper is custom to notifications needs (subscribe and ping pong only)\n * If in the future we need to use it for other purposes, we will have to throw an error and update the implementation of ping pong in the notification\n * @param data the data to send\n */\n public send(data: Buffer | ArrayBuffer | string) {\n if (this.websocket && this.readyState === ReadyState.OPEN) {\n this.websocket.send(data)\n }\n }\n\n public close(code?: number, reason?: string) {\n if (this.websocket) {\n this.websocket.close(code, reason)\n }\n }\n\n private onMessage(callback: (event: string) => void) {\n if (this.websocket) {\n if (isNode) {\n (this.websocket as WebSocketNode).on('message', (x) => callback(x.toString('utf8')))\n } else {\n (this.websocket as WebSocket).addEventListener('message', async (event) => {\n let dataAsString: string | undefined\n if (event.type === 'message') {\n dataAsString = event.data\n } else console.error(\"Unexpected event type: \" + event.type)\n if (!dataAsString) {\n console.error(\"Failed to parse WebSocket message\")\n return\n }\n\n callback(dataAsString)\n })\n }\n }\n else {\n console.error(\"Websocket is not defined\")\n throw new Error('Websocket is not defined')\n }\n }\n\n private onOpen(callback: (event: any) => void) {\n if (this.websocket) {\n if (isNode) {\n (this.websocket as WebSocketNode).on('open', callback)\n } else {\n (this.websocket as WebSocket).addEventListener('open', callback)\n }\n }\n }\n\n private onClose(callback: (event: {code: number, reason: string}) => void) {\n if (this.websocket) {\n if (isNode) {\n (this.websocket as WebSocketNode).on('close', callback)\n } else {\n (this.websocket as WebSocket).addEventListener('close', callback)\n }\n }\n }\n\n private onError(callback: (error: any) => void) {\n if (this.websocket) {\n if (isNode) {\n (this.websocket as WebSocketNode).on('error', callback)\n } else {\n (this.websocket as WebSocket).addEventListener('error', callback)\n }\n }\n }\n\n\n public on<K extends keyof EventCallback>(event: K, callback: EventCallback[K]) {\n if (this.websocket) {\n switch (event) {\n case 'message':\n return this.onMessage(callback as EventCallback['message'])\n case 'open':\n return this.onOpen(callback as EventCallback['open'])\n case 'close':\n return this.onClose(callback as EventCallback['close'])\n case 'error':\n return this.onError(callback as EventCallback['error'])\n }\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@icure/api",
3
- "version": "7.1.7",
3
+ "version": "7.1.9",
4
4
  "description": "Typescript version of iCure standalone API client",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -9,7 +9,6 @@
9
9
  "date-fns": "^2.23.0",
10
10
  "libphonenumber-js": "^1.7.18",
11
11
  "lodash": "^4.17.21",
12
- "loglevel": "^1.8.1",
13
12
  "moment": "^2.22.1",
14
13
  "text-encoding": "^0.7.0",
15
14
  "uuid": "^8.3.2",