@icure/api 8.8.0 → 8.8.2
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.
- package/icc-api/api/IccAccesslogApi.d.ts +48 -0
- package/icc-api/api/IccAccesslogApi.js +100 -0
- package/icc-api/api/IccAccesslogApi.js.map +1 -1
- package/icc-api/api/IccAgendaApi.d.ts +25 -0
- package/icc-api/api/IccAgendaApi.js +49 -0
- package/icc-api/api/IccAgendaApi.js.map +1 -1
- package/icc-api/api/IccCalendarItemApi.d.ts +25 -0
- package/icc-api/api/IccCalendarItemApi.js +49 -0
- package/icc-api/api/IccCalendarItemApi.js.map +1 -1
- package/icc-api/api/IccCalendarItemTypeApi.d.ts +25 -0
- package/icc-api/api/IccCalendarItemTypeApi.js +49 -0
- package/icc-api/api/IccCalendarItemTypeApi.js.map +1 -1
- package/icc-api/api/IccCodeApi.d.ts +25 -0
- package/icc-api/api/IccCodeApi.js +49 -0
- package/icc-api/api/IccCodeApi.js.map +1 -1
- package/icc-api/api/IccContactApi.d.ts +48 -0
- package/icc-api/api/IccContactApi.js +100 -0
- package/icc-api/api/IccContactApi.js.map +1 -1
- package/icc-api/api/IccDeviceApi.d.ts +48 -0
- package/icc-api/api/IccDeviceApi.js +100 -0
- package/icc-api/api/IccDeviceApi.js.map +1 -1
- package/icc-api/api/IccDocumentApi.d.ts +48 -0
- package/icc-api/api/IccDocumentApi.js +100 -0
- package/icc-api/api/IccDocumentApi.js.map +1 -1
- package/icc-api/api/IccFormApi.d.ts +48 -0
- package/icc-api/api/IccFormApi.js +101 -4
- package/icc-api/api/IccFormApi.js.map +1 -1
- package/icc-api/api/IccHcpartyApi.d.ts +48 -0
- package/icc-api/api/IccHcpartyApi.js +100 -0
- package/icc-api/api/IccHcpartyApi.js.map +1 -1
- package/icc-api/api/IccHelementApi.d.ts +48 -0
- package/icc-api/api/IccHelementApi.js +100 -0
- package/icc-api/api/IccHelementApi.js.map +1 -1
- package/icc-api/api/IccInsuranceApi.d.ts +50 -2
- package/icc-api/api/IccInsuranceApi.js +100 -0
- package/icc-api/api/IccInsuranceApi.js.map +1 -1
- package/icc-api/api/IccInvoiceApi.d.ts +48 -0
- package/icc-api/api/IccInvoiceApi.js +100 -0
- package/icc-api/api/IccInvoiceApi.js.map +1 -1
- package/icc-api/api/IccMessageApi.d.ts +48 -0
- package/icc-api/api/IccMessageApi.js +100 -0
- package/icc-api/api/IccMessageApi.js.map +1 -1
- package/icc-api/api/IccPatientApi.d.ts +48 -0
- package/icc-api/api/IccPatientApi.js +100 -0
- package/icc-api/api/IccPatientApi.js.map +1 -1
- package/icc-api/api/IccPlaceApi.d.ts +25 -0
- package/icc-api/api/IccPlaceApi.js +49 -0
- package/icc-api/api/IccPlaceApi.js.map +1 -1
- package/icc-api/api/IccReceiptApi.d.ts +25 -0
- package/icc-api/api/IccReceiptApi.js +49 -0
- package/icc-api/api/IccReceiptApi.js.map +1 -1
- package/icc-api/api/IccTopicApi.d.ts +48 -0
- package/icc-api/api/IccTopicApi.js +100 -0
- package/icc-api/api/IccTopicApi.js.map +1 -1
- package/icc-api/api/IccUserApi.d.ts +25 -0
- package/icc-api/api/IccUserApi.js +49 -0
- package/icc-api/api/IccUserApi.js.map +1 -1
- package/icc-api/model/ConflictResolutionRequest.d.ts +18 -0
- package/icc-api/model/ConflictResolutionRequest.js +17 -0
- package/icc-api/model/ConflictResolutionRequest.js.map +1 -0
- package/icc-api/model/ConflictResolutionResult.d.ts +22 -0
- package/icc-api/model/ConflictResolutionResult.js +24 -0
- package/icc-api/model/ConflictResolutionResult.js.map +1 -0
- package/icc-api/model/models.d.ts +2 -0
- package/icc-api/model/models.js +2 -0
- package/icc-api/model/models.js.map +1 -1
- package/icc-x-api/icc-accesslog-x-api.d.ts +31 -0
- package/icc-x-api/icc-accesslog-x-api.js +57 -0
- package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
- package/icc-x-api/icc-calendar-item-x-api.d.ts +15 -0
- package/icc-x-api/icc-calendar-item-x-api.js +28 -0
- package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
- package/icc-x-api/icc-contact-x-api.d.ts +31 -0
- package/icc-x-api/icc-contact-x-api.js +60 -1
- package/icc-x-api/icc-contact-x-api.js.map +1 -1
- package/icc-x-api/icc-document-x-api.d.ts +31 -0
- package/icc-x-api/icc-document-x-api.js +64 -0
- package/icc-x-api/icc-document-x-api.js.map +1 -1
- package/icc-x-api/icc-form-x-api.d.ts +31 -0
- package/icc-x-api/icc-form-x-api.js +58 -0
- package/icc-x-api/icc-form-x-api.js.map +1 -1
- package/icc-x-api/icc-helement-x-api.d.ts +31 -0
- package/icc-x-api/icc-helement-x-api.js +57 -0
- package/icc-x-api/icc-helement-x-api.js.map +1 -1
- package/icc-x-api/icc-invoice-x-api.d.ts +31 -0
- package/icc-x-api/icc-invoice-x-api.js +58 -0
- package/icc-x-api/icc-invoice-x-api.js.map +1 -1
- package/icc-x-api/icc-message-x-api.d.ts +31 -0
- package/icc-x-api/icc-message-x-api.js +64 -0
- package/icc-x-api/icc-message-x-api.js.map +1 -1
- package/icc-x-api/icc-patient-x-api.d.ts +31 -0
- package/icc-x-api/icc-patient-x-api.js +57 -0
- package/icc-x-api/icc-patient-x-api.js.map +1 -1
- package/icc-x-api/icc-topic-x-api.d.ts +31 -0
- package/icc-x-api/icc-topic-x-api.js +58 -0
- package/icc-x-api/icc-topic-x-api.js.map +1 -1
- package/icc-x-api/utils/formatting-util.d.ts +10 -4
- package/icc-x-api/utils/formatting-util.js +47 -6
- package/icc-x-api/utils/formatting-util.js.map +1 -1
- package/package.json +1 -1
|
@@ -201,4 +201,35 @@ export declare class IccTopicXApi extends IccTopicApi implements EncryptedEntity
|
|
|
201
201
|
}, topicId: string): Promise<Topic>;
|
|
202
202
|
subscribeToTopicEvents(eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[], filter: AbstractFilter<Topic> | undefined, eventFired: (message: Topic) => Promise<void>, options?: SubscriptionOptions): Promise<Connection>;
|
|
203
203
|
createDelegationDeAnonymizationMetadata(entity: Topic, delegates: string[]): Promise<void>;
|
|
204
|
+
/**
|
|
205
|
+
* Like {@link getConflictsForEntity} but additionally decrypts the conflicting revisions for the given user.
|
|
206
|
+
* @param user the current user.
|
|
207
|
+
* @param entityId the id of the topic to retrieve the conflicts for.
|
|
208
|
+
* @return the decrypted conflicting revisions of the topic.
|
|
209
|
+
*/
|
|
210
|
+
getConflictsForEntityWithUser(user: models.User, entityId: string): Promise<Array<models.Topic>>;
|
|
211
|
+
/**
|
|
212
|
+
* Like {@link declareConflictWinner} but encrypts the winning revision before sending it and decrypts the saved
|
|
213
|
+
* winner returned by the backend.
|
|
214
|
+
* @param user the current user.
|
|
215
|
+
* @param request the {@link models.ConflictResolutionRequest} carrying the (decrypted) winning revision and the conflicts to purge.
|
|
216
|
+
* @return the {@link models.ConflictResolutionResult} with the decrypted saved winner and the conflicts that are still unresolved.
|
|
217
|
+
*/
|
|
218
|
+
declareConflictWinnerWithUser(user: models.User, request: models.ConflictResolutionRequest<models.Topic>): Promise<models.ConflictResolutionResult<models.Topic>>;
|
|
219
|
+
/**
|
|
220
|
+
* Like {@link getConflictsForEntityWithUser} but targets the entity of the group with the given id.
|
|
221
|
+
* @param user the current user.
|
|
222
|
+
* @param groupId the id of the group the topic belongs to.
|
|
223
|
+
* @param entityId the id of the topic to retrieve the conflicts for.
|
|
224
|
+
* @return the decrypted conflicting revisions of the topic.
|
|
225
|
+
*/
|
|
226
|
+
getConflictsForEntityInGroupWithUser(user: models.User, groupId: string, entityId: string): Promise<Array<models.Topic>>;
|
|
227
|
+
/**
|
|
228
|
+
* Like {@link declareConflictWinnerWithUser} but targets the entity of the group with the given id.
|
|
229
|
+
* @param user the current user.
|
|
230
|
+
* @param groupId the id of the group the topic belongs to.
|
|
231
|
+
* @param request the {@link models.ConflictResolutionRequest} carrying the (decrypted) winning revision and the conflicts to purge.
|
|
232
|
+
* @return the {@link models.ConflictResolutionResult} with the decrypted saved winner and the conflicts that are still unresolved.
|
|
233
|
+
*/
|
|
234
|
+
declareConflictWinnerInGroupWithUser(user: models.User, groupId: string, request: models.ConflictResolutionRequest<models.Topic>): Promise<models.ConflictResolutionResult<models.Topic>>;
|
|
204
235
|
}
|
|
@@ -20,6 +20,7 @@ var RequestedPermissionEnum = EntityShareRequest_1.EntityShareRequest.RequestedP
|
|
|
20
20
|
const utils_1 = require("./utils");
|
|
21
21
|
const Connection_1 = require("../icc-api/model/Connection");
|
|
22
22
|
const SecretIdUseOption_1 = require("./crypto/SecretIdUseOption");
|
|
23
|
+
const collection_utils_1 = require("./utils/collection-utils");
|
|
23
24
|
// noinspection JSUnusedGlobalSymbols
|
|
24
25
|
class IccTopicXApi extends icc_api_1.IccTopicApi {
|
|
25
26
|
constructor(host, headers, crypto, dataOwnerApi, authApi, autofillAuthor, authenticationProvider = new AuthenticationProvider_1.NoAuthenticationProvider(), encryptedKeys = ['description'], fetchImpl = typeof window !== 'undefined'
|
|
@@ -304,6 +305,63 @@ class IccTopicXApi extends icc_api_1.IccTopicApi {
|
|
|
304
305
|
createDelegationDeAnonymizationMetadata(entity, delegates) {
|
|
305
306
|
return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: utils_1.EntityWithDelegationTypeName.Topic }, delegates);
|
|
306
307
|
}
|
|
308
|
+
/**
|
|
309
|
+
* Like {@link getConflictsForEntity} but additionally decrypts the conflicting revisions for the given user.
|
|
310
|
+
* @param user the current user.
|
|
311
|
+
* @param entityId the id of the topic to retrieve the conflicts for.
|
|
312
|
+
* @return the decrypted conflicting revisions of the topic.
|
|
313
|
+
*/
|
|
314
|
+
getConflictsForEntityWithUser(user, entityId) {
|
|
315
|
+
return super.getConflictsForEntity(entityId).then((ts) => this.decrypt(ts));
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Like {@link declareConflictWinner} but encrypts the winning revision before sending it and decrypts the saved
|
|
319
|
+
* winner returned by the backend.
|
|
320
|
+
* @param user the current user.
|
|
321
|
+
* @param request the {@link models.ConflictResolutionRequest} carrying the (decrypted) winning revision and the conflicts to purge.
|
|
322
|
+
* @return the {@link models.ConflictResolutionResult} with the decrypted saved winner and the conflicts that are still unresolved.
|
|
323
|
+
*/
|
|
324
|
+
declareConflictWinnerWithUser(user, request) {
|
|
325
|
+
const _super = Object.create(null, {
|
|
326
|
+
declareConflictWinner: { get: () => super.declareConflictWinner }
|
|
327
|
+
});
|
|
328
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
329
|
+
const encrypted = (yield this.encrypt([(0, collection_utils_1.cloneDeep)(request.document)]))[0];
|
|
330
|
+
const result = yield _super.declareConflictWinner.call(this, Object.assign(Object.assign({}, request), { document: encrypted }));
|
|
331
|
+
if (result.document)
|
|
332
|
+
result.document = (yield this.decrypt([result.document]))[0];
|
|
333
|
+
return result;
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Like {@link getConflictsForEntityWithUser} but targets the entity of the group with the given id.
|
|
338
|
+
* @param user the current user.
|
|
339
|
+
* @param groupId the id of the group the topic belongs to.
|
|
340
|
+
* @param entityId the id of the topic to retrieve the conflicts for.
|
|
341
|
+
* @return the decrypted conflicting revisions of the topic.
|
|
342
|
+
*/
|
|
343
|
+
getConflictsForEntityInGroupWithUser(user, groupId, entityId) {
|
|
344
|
+
return super.getConflictsForEntityInGroup(groupId, entityId).then((ts) => this.decrypt(ts));
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Like {@link declareConflictWinnerWithUser} but targets the entity of the group with the given id.
|
|
348
|
+
* @param user the current user.
|
|
349
|
+
* @param groupId the id of the group the topic belongs to.
|
|
350
|
+
* @param request the {@link models.ConflictResolutionRequest} carrying the (decrypted) winning revision and the conflicts to purge.
|
|
351
|
+
* @return the {@link models.ConflictResolutionResult} with the decrypted saved winner and the conflicts that are still unresolved.
|
|
352
|
+
*/
|
|
353
|
+
declareConflictWinnerInGroupWithUser(user, groupId, request) {
|
|
354
|
+
const _super = Object.create(null, {
|
|
355
|
+
declareConflictWinnerInGroup: { get: () => super.declareConflictWinnerInGroup }
|
|
356
|
+
});
|
|
357
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
358
|
+
const encrypted = (yield this.encrypt([(0, collection_utils_1.cloneDeep)(request.document)]))[0];
|
|
359
|
+
const result = yield _super.declareConflictWinnerInGroup.call(this, groupId, Object.assign(Object.assign({}, request), { document: encrypted }));
|
|
360
|
+
if (result.document)
|
|
361
|
+
result.document = (yield this.decrypt([result.document]))[0];
|
|
362
|
+
return result;
|
|
363
|
+
});
|
|
364
|
+
}
|
|
307
365
|
}
|
|
308
366
|
exports.IccTopicXApi = IccTopicXApi;
|
|
309
367
|
//# sourceMappingURL=icc-topic-x-api.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icc-topic-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-topic-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAoD;AAGpD,kDAAiD;AAGjD,0EAAgG;AAChG,wEAAoE;AAGpE,qFAAiF;AAKjF,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACzD,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAC3E,mCAAmJ;AAEnJ,4DAAwE;AACxE,kEAA8D;AAE9D,qCAAqC;AACrC,MAAa,YAAa,SAAQ,qBAAW;IAG3C,YACE,IAAY,EACZ,OAAkC,EACjB,MAAqB,EACrB,YAA8B,EAC9B,OAAmB,EACnB,cAAuB,EACxC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,gBAA+B,CAAC,aAAa,CAAC,EAC9C,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IA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AC,EAAE,EAAE,EAAE,CAAC,IAAI,2BAAc,CAAC,EAAE,CAAC,CAAC,CAAA;QACxC,CAAC;KAAA;IAED,uCAAuC,CAAC,MAAa,EAAE,SAAmB;QACxE,OAAO,IAAI,CAAC,MAAM,CAAC,0BAA0B,CAAC,iCAAiC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,oCAA4B,CAAC,KAAK,EAAE,EAAE,SAAS,CAAC,CAAA;IAClJ,CAAC;CACF;AA/WD,oCA+WC","sourcesContent":["import { IccAuthApi, IccTopicApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as models from '../icc-api/model/models'\nimport { ListOfIds, MaintenanceTask, TimingInfo, Topic, TopicRole } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport { XHR } from '../icc-api/api/XHR'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { FilterChainTopic } from '../icc-api/model/FilterChainTopic'\nimport { PaginatedListTopic } from '../icc-api/model/PaginatedListTopic'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { EncryptedFieldsManifest, EntityWithDelegationTypeName, parseEncryptedFields, subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { AbstractFilter } from './filters/filters'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport { SecretIdUseOption } from './crypto/SecretIdUseOption'\n\n// noinspection JSUnusedGlobalSymbols\nexport class IccTopicXApi extends IccTopicApi implements EncryptedEntityXApi<models.Topic> {\n private readonly encryptedFields: EncryptedFieldsManifest\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private readonly crypto: IccCryptoXApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly authApi: IccAuthApi,\n private readonly autofillAuthor: boolean,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n encryptedKeys: Array<string> = ['description'],\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n\n this.encryptedFields = parseEncryptedFields(encryptedKeys, 'Topic.')\n }\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Topic))\n }\n\n /**\n * Creates a new instance of topic with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this topic refers to.\n * @param c initialised data for the topic. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify\n * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.\n * @param options optional parameters:\n * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the\n * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with\n * auto-delegations, in such case the access level specified here will be used.\n * - sfkOption: specifies which sfk of the owning entity to use.\n * - ignoreAutoDelegations: if true the data won't be shared with the autodelegations of the user, but only with additional delegates\n * - alternateRootDelegation: by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,\n * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.\n * @return a new instance of topic.\n */\n async newInstance(\n user: models.User,\n patient: models.Patient | null,\n c: Topic = {}, // TODO: Why this isn't Topic?\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n sfkOption?: SecretIdUseOption\n ignoreAutoDelegations?: boolean\n alternateRootDelegation?: string\n } = {}\n ) {\n if (!patient && options.sfkOption) throw new Error('preferredSfk can only be specified if patient is specified.')\n\n const topic = {\n ...(c ?? {}),\n id: c?.id ?? this.crypto.primitives.randomUuid(),\n _type: 'org.taktik.icure.entities.Topic',\n created: c?.created ?? new Date().getTime(),\n modified: c?.modified ?? new Date().getTime(),\n responsible: c?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: c?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: c?.codes ?? [],\n tags: c?.tags ?? [],\n }\n\n const extraDelegations = {\n ...(options.ignoreAutoDelegations == true ? {} : Object.fromEntries((user.autoDelegations?.all ?? []).map((d) => [d, AccessLevelEnum.WRITE]))),\n ...(options?.additionalDelegates ?? {}),\n }\n\n const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) throw new Error('Can only initialise entities as current data owner.')\n const sfk = patient\n ? await this.crypto.xapi.resolveSecretIdUseOptions(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n options.sfkOption ?? SecretIdUseOption.UseAnySharedWithParent\n )\n : undefined\n\n if (patient && !sfk) throw new Error(`Couldn't find any sfk of parent patient ${patient.id}`)\n\n return new models.Topic(\n await this.crypto.xapi\n .entityWithInitialisedEncryptedMetadata(\n topic,\n EntityWithDelegationTypeName.Topic,\n patient?.id,\n sfk,\n true,\n extraDelegations,\n options.alternateRootDelegation\n )\n .then((x) => x.updatedEntity)\n )\n }\n\n async decrypt(topics: Array<models.Topic>) {\n return (await this.crypto.xapi.tryDecryptEntities(topics, EntityWithDelegationTypeName.Topic, (x) => new models.Topic(x))).map(\n ({ entity }) => entity\n )\n }\n\n async encrypt(topics: Array<models.Topic>): Promise<Array<models.Topic>> {\n return this.crypto.xapi.tryEncryptEntities(\n topics,\n EntityWithDelegationTypeName.Topic,\n this.encryptedFields,\n true,\n false,\n (x) => new models.Topic(x)\n )\n }\n\n /**\n * Create and share a new topic with other participants.\n * @param body the topic to create.\n * @return the created topic.\n */\n override async createTopic(body: Topic): Promise<Topic> {\n const encryptedTopics = await this.encrypt([body])\n const createdTopic = await super.createTopic(encryptedTopics[0])\n const decryptedTopics = await this.decrypt([createdTopic])\n return decryptedTopics[0]\n }\n\n /**\n * @param topic a topic\n * @return the id of the patient that the topic refers to, retrieved from the encrypted metadata. Normally there should only be one element\n * in the returned array, but in case of entity merges there could be multiple values.\n */\n async decryptPatientIdOf(topic: models.Topic): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: topic, type: EntityWithDelegationTypeName.Topic }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given topic\n */\n async hasWriteAccess(topic: models.Topic): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: topic, type: EntityWithDelegationTypeName.Topic })\n }\n\n /**\n * Share an existing topic with other data owners, allowing them to access the non-encrypted data of the topic and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param delegateId the id of the data owner which will be granted access to the topic.\n * @param topic the topic to share.\n * @param options optional parameters to customize the sharing behaviour:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - sharePatientId: specifies if the id of the patient that this topic refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n topic: models.Topic,\n options: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.Topic> {\n return this.shareWithMany(topic, { [delegateId]: options })\n }\n\n /**\n * Share an existing topic with other data owners, allowing them to access the non-encrypted data of the topic and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param topic the topic to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * topic does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this topic refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n topic: models.Topic,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.Topic> {\n return (await this.tryShareWithMany(topic, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing topic with other data owners, allowing them to access the non-encrypted data of the topic and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param topic the topic to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * topic does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this topic refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n topic: models.Topic,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.Topic>> {\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(topic, EntityWithDelegationTypeName.Topic)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyTopic(entityWithEncryptionKey) : topic\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Topic,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: options.sharePatientId,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkShareTopics(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decrypt([e]).then((es) => es[0])))\n }\n\n getDataOwnersWithAccessTo(\n entity: models.Topic\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Topic })\n }\n\n getEncryptionKeysOf(entity: models.Topic): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Topic }, undefined)\n }\n\n /**\n * Filter and decrypt topics by the given filter.\n * @param body the filter to apply.\n * @param startDocumentId the document id to start from (inclusive).\n * @param limit the maximum number of topics to return in the page.\n * @param collectTiming add timing information to the response\n * @return a paginated list of topics.\n */\n override async filterTopicsBy(body: FilterChainTopic, startDocumentId?: string, limit?: number, collectTiming?: false): Promise<PaginatedListTopic>\n override async filterTopicsBy(body: FilterChainTopic, startDocumentId?: string, limit?: number, collectTiming?: true): Promise<PaginatedListTopic & TimingInfo>\n override async filterTopicsBy(body: FilterChainTopic, startDocumentId?: string, limit?: number, collectTiming: boolean = false): Promise<PaginatedListTopic> {\n const page = await super.filterTopicsBy(body, startDocumentId, limit, collectTiming as any)\n const decryptedTopics = await this.decrypt(page.rows ?? [])\n return {\n ...page,\n rows: decryptedTopics,\n }\n }\n\n /**\n * Obtain the topic with the given id and decrypt it.\n * @param id the id of the topic to retrieve.\n * @return the decrypted topic.\n */\n override async getTopic(id: string): Promise<Topic> {\n const topic = await super.getTopic(id)\n const decryptedTopics = await this.decrypt([topic])\n return decryptedTopics[0]\n }\n\n /**\n * Obtain the topics with the given ids and decrypt them.\n * @param body the ids of the topics to retrieve.\n * @return the decrypted topics.\n */\n override async getTopics(body: ListOfIds): Promise<Array<Topic>> {\n const topics = await super.getTopics(body)\n return await this.decrypt(topics)\n }\n\n /**\n * Update and encrypt the given topic.\n * @param body the topic to update.\n * @return the updated decrypted topic.\n */\n override async modifyTopic(body: Topic): Promise<Topic> {\n const encryptedTopics = await this.encrypt([body])\n const modifiedTopic = await super.modifyTopic(encryptedTopics[0])\n const decryptedTopics = await this.decrypt([modifiedTopic])\n return decryptedTopics[0]\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice\n * @param body data owner id of the data owner to which the participant should be added and the topic role of the participant.\n * @param topicId Id of the topic to which the participant should be added.\n */\n override async addParticipant(body: { dataOwnerId: string; topicRole: TopicRole }, topicId: string): Promise<Topic> {\n throw new Error('Cannot add participant to topic without sharing it first. You should use addParticipantWithTopic instead.')\n }\n\n /**\n * This method is similar to {@link addParticipant} but it also shares the topic with the data owner before adding the participant.\n * @param body data owner id of the data owner to which the participant should be added and the topic role of the participant.\n * @param topic the topic to share and to which the participant should be added.\n * @return the updated topic.\n */\n async addParticipantWithTopic(body: { dataOwnerId: string; topicRole: TopicRole }, topic: Topic): Promise<Topic> {\n const updatedTopic = await this.shareWith(body.dataOwnerId, topic, {\n requestedPermissions: RequestedPermissionEnum.FULL_WRITE,\n })\n\n return (await this.decrypt([await super.addParticipant(body, updatedTopic.id!)]))[0]\n }\n\n /**\n * Remove the participant with the given data owner id from the topic with the given id.\n * @param body data owner id of the participant to remove.\n * @param topicId Id of the topic from which the participant should be removed.\n * @return the updated decrypted topic.\n */\n async removeParticipant(body: { dataOwnerId: string }, topicId: string): Promise<Topic> {\n const updatedTopic = await super.removeParticipant(body, topicId)\n return (await this.decrypt([updatedTopic]))[0]\n }\n\n async subscribeToTopicEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<Topic> | undefined,\n eventFired: (message: Topic) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n return await subscribeToEntityEvents(\n this.host,\n this.authApi,\n EntityWithDelegationTypeName.Topic,\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted) => (await this.decrypt([encrypted]))[0]\n ).then((rs) => new ConnectionImpl(rs))\n }\n\n createDelegationDeAnonymizationMetadata(entity: Topic, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Topic }, delegates)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"icc-topic-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-topic-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAoD;AAGpD,kDAAiD;AAGjD,0EAAgG;AAChG,wEAAoE;AAGpE,qFAAiF;AAKjF,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACzD,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,u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BAAqB,4CAAM,OAAO,KAAE,QAAQ,EAAE,SAAS,IAAG,CAAA;YACrF,IAAI,MAAM,CAAC,QAAQ;gBAAE,MAAM,CAAC,QAAQ,GAAG,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YACjF,OAAO,MAAM,CAAA;QACf,CAAC;KAAA;IAED;;;;;;OAMG;IACH,oCAAoC,CAAC,IAAiB,EAAE,OAAe,EAAE,QAAgB;QACvF,OAAO,KAAK,CAAC,4BAA4B,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAA;IAC7F,CAAC;IAED;;;;;;OAMG;IACG,oCAAoC,CACxC,IAAiB,EACjB,OAAe,EACf,OAAuD;;;;;YAEvD,MAAM,SAAS,GAAG,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,CAAC,IAAA,4BAAS,EAAC,OAAO,CAAC,QAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YACzE,MAAM,MAAM,GAAG,MAAM,OAAM,4BAA4B,YAAC,OAAO,kCAAO,OAAO,KAAE,QAAQ,EAAE,SAAS,IAAG,CAAA;YACrG,IAAI,MAAM,CAAC,QAAQ;gBAAE,MAAM,CAAC,QAAQ,GAAG,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;YACjF,OAAO,MAAM,CAAA;QACf,CAAC;KAAA;CACF;AAjbD,oCAibC","sourcesContent":["import { IccAuthApi, IccTopicApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as models from '../icc-api/model/models'\nimport { ListOfIds, MaintenanceTask, TimingInfo, Topic, TopicRole } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport { XHR } from '../icc-api/api/XHR'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { FilterChainTopic } from '../icc-api/model/FilterChainTopic'\nimport { PaginatedListTopic } from '../icc-api/model/PaginatedListTopic'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { EncryptedFieldsManifest, EntityWithDelegationTypeName, parseEncryptedFields, subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { AbstractFilter } from './filters/filters'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport { SecretIdUseOption } from './crypto/SecretIdUseOption'\nimport { cloneDeep } from './utils/collection-utils'\n\n// noinspection JSUnusedGlobalSymbols\nexport class IccTopicXApi extends IccTopicApi implements EncryptedEntityXApi<models.Topic> {\n private readonly encryptedFields: EncryptedFieldsManifest\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private readonly crypto: IccCryptoXApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly authApi: IccAuthApi,\n private readonly autofillAuthor: boolean,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n encryptedKeys: Array<string> = ['description'],\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n\n this.encryptedFields = parseEncryptedFields(encryptedKeys, 'Topic.')\n }\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Topic))\n }\n\n /**\n * Creates a new instance of topic with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this topic refers to.\n * @param c initialised data for the topic. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify\n * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.\n * @param options optional parameters:\n * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the\n * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with\n * auto-delegations, in such case the access level specified here will be used.\n * - sfkOption: specifies which sfk of the owning entity to use.\n * - ignoreAutoDelegations: if true the data won't be shared with the autodelegations of the user, but only with additional delegates\n * - alternateRootDelegation: by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,\n * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.\n * @return a new instance of topic.\n */\n async newInstance(\n user: models.User,\n patient: models.Patient | null,\n c: Topic = {}, // TODO: Why this isn't Topic?\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n sfkOption?: SecretIdUseOption\n ignoreAutoDelegations?: boolean\n alternateRootDelegation?: string\n } = {}\n ) {\n if (!patient && options.sfkOption) throw new Error('preferredSfk can only be specified if patient is specified.')\n\n const topic = {\n ...(c ?? {}),\n id: c?.id ?? this.crypto.primitives.randomUuid(),\n _type: 'org.taktik.icure.entities.Topic',\n created: c?.created ?? new Date().getTime(),\n modified: c?.modified ?? new Date().getTime(),\n responsible: c?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: c?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: c?.codes ?? [],\n tags: c?.tags ?? [],\n }\n\n const extraDelegations = {\n ...(options.ignoreAutoDelegations == true ? {} : Object.fromEntries((user.autoDelegations?.all ?? []).map((d) => [d, AccessLevelEnum.WRITE]))),\n ...(options?.additionalDelegates ?? {}),\n }\n\n const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) throw new Error('Can only initialise entities as current data owner.')\n const sfk = patient\n ? await this.crypto.xapi.resolveSecretIdUseOptions(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n options.sfkOption ?? SecretIdUseOption.UseAnySharedWithParent\n )\n : undefined\n\n if (patient && !sfk) throw new Error(`Couldn't find any sfk of parent patient ${patient.id}`)\n\n return new models.Topic(\n await this.crypto.xapi\n .entityWithInitialisedEncryptedMetadata(\n topic,\n EntityWithDelegationTypeName.Topic,\n patient?.id,\n sfk,\n true,\n extraDelegations,\n options.alternateRootDelegation\n )\n .then((x) => x.updatedEntity)\n )\n }\n\n async decrypt(topics: Array<models.Topic>) {\n return (await this.crypto.xapi.tryDecryptEntities(topics, EntityWithDelegationTypeName.Topic, (x) => new models.Topic(x))).map(\n ({ entity }) => entity\n )\n }\n\n async encrypt(topics: Array<models.Topic>): Promise<Array<models.Topic>> {\n return this.crypto.xapi.tryEncryptEntities(\n topics,\n EntityWithDelegationTypeName.Topic,\n this.encryptedFields,\n true,\n false,\n (x) => new models.Topic(x)\n )\n }\n\n /**\n * Create and share a new topic with other participants.\n * @param body the topic to create.\n * @return the created topic.\n */\n override async createTopic(body: Topic): Promise<Topic> {\n const encryptedTopics = await this.encrypt([body])\n const createdTopic = await super.createTopic(encryptedTopics[0])\n const decryptedTopics = await this.decrypt([createdTopic])\n return decryptedTopics[0]\n }\n\n /**\n * @param topic a topic\n * @return the id of the patient that the topic refers to, retrieved from the encrypted metadata. Normally there should only be one element\n * in the returned array, but in case of entity merges there could be multiple values.\n */\n async decryptPatientIdOf(topic: models.Topic): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: topic, type: EntityWithDelegationTypeName.Topic }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given topic\n */\n async hasWriteAccess(topic: models.Topic): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: topic, type: EntityWithDelegationTypeName.Topic })\n }\n\n /**\n * Share an existing topic with other data owners, allowing them to access the non-encrypted data of the topic and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param delegateId the id of the data owner which will be granted access to the topic.\n * @param topic the topic to share.\n * @param options optional parameters to customize the sharing behaviour:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - sharePatientId: specifies if the id of the patient that this topic refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n topic: models.Topic,\n options: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.Topic> {\n return this.shareWithMany(topic, { [delegateId]: options })\n }\n\n /**\n * Share an existing topic with other data owners, allowing them to access the non-encrypted data of the topic and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param topic the topic to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * topic does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this topic refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n topic: models.Topic,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.Topic> {\n return (await this.tryShareWithMany(topic, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing topic with other data owners, allowing them to access the non-encrypted data of the topic and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param topic the topic to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * topic does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this topic refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n topic: models.Topic,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.Topic>> {\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(topic, EntityWithDelegationTypeName.Topic)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyTopic(entityWithEncryptionKey) : topic\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Topic,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: options.sharePatientId,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkShareTopics(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decrypt([e]).then((es) => es[0])))\n }\n\n getDataOwnersWithAccessTo(\n entity: models.Topic\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Topic })\n }\n\n getEncryptionKeysOf(entity: models.Topic): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Topic }, undefined)\n }\n\n /**\n * Filter and decrypt topics by the given filter.\n * @param body the filter to apply.\n * @param startDocumentId the document id to start from (inclusive).\n * @param limit the maximum number of topics to return in the page.\n * @param collectTiming add timing information to the response\n * @return a paginated list of topics.\n */\n override async filterTopicsBy(body: FilterChainTopic, startDocumentId?: string, limit?: number, collectTiming?: false): Promise<PaginatedListTopic>\n override async filterTopicsBy(\n body: FilterChainTopic,\n startDocumentId?: string,\n limit?: number,\n collectTiming?: true\n ): Promise<PaginatedListTopic & TimingInfo>\n override async filterTopicsBy(\n body: FilterChainTopic,\n startDocumentId?: string,\n limit?: number,\n collectTiming: boolean = false\n ): Promise<PaginatedListTopic> {\n const page = await super.filterTopicsBy(body, startDocumentId, limit, collectTiming as any)\n const decryptedTopics = await this.decrypt(page.rows ?? [])\n return {\n ...page,\n rows: decryptedTopics,\n }\n }\n\n /**\n * Obtain the topic with the given id and decrypt it.\n * @param id the id of the topic to retrieve.\n * @return the decrypted topic.\n */\n override async getTopic(id: string): Promise<Topic> {\n const topic = await super.getTopic(id)\n const decryptedTopics = await this.decrypt([topic])\n return decryptedTopics[0]\n }\n\n /**\n * Obtain the topics with the given ids and decrypt them.\n * @param body the ids of the topics to retrieve.\n * @return the decrypted topics.\n */\n override async getTopics(body: ListOfIds): Promise<Array<Topic>> {\n const topics = await super.getTopics(body)\n return await this.decrypt(topics)\n }\n\n /**\n * Update and encrypt the given topic.\n * @param body the topic to update.\n * @return the updated decrypted topic.\n */\n override async modifyTopic(body: Topic): Promise<Topic> {\n const encryptedTopics = await this.encrypt([body])\n const modifiedTopic = await super.modifyTopic(encryptedTopics[0])\n const decryptedTopics = await this.decrypt([modifiedTopic])\n return decryptedTopics[0]\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice\n * @param body data owner id of the data owner to which the participant should be added and the topic role of the participant.\n * @param topicId Id of the topic to which the participant should be added.\n */\n override async addParticipant(body: { dataOwnerId: string; topicRole: TopicRole }, topicId: string): Promise<Topic> {\n throw new Error('Cannot add participant to topic without sharing it first. You should use addParticipantWithTopic instead.')\n }\n\n /**\n * This method is similar to {@link addParticipant} but it also shares the topic with the data owner before adding the participant.\n * @param body data owner id of the data owner to which the participant should be added and the topic role of the participant.\n * @param topic the topic to share and to which the participant should be added.\n * @return the updated topic.\n */\n async addParticipantWithTopic(body: { dataOwnerId: string; topicRole: TopicRole }, topic: Topic): Promise<Topic> {\n const updatedTopic = await this.shareWith(body.dataOwnerId, topic, {\n requestedPermissions: RequestedPermissionEnum.FULL_WRITE,\n })\n\n return (await this.decrypt([await super.addParticipant(body, updatedTopic.id!)]))[0]\n }\n\n /**\n * Remove the participant with the given data owner id from the topic with the given id.\n * @param body data owner id of the participant to remove.\n * @param topicId Id of the topic from which the participant should be removed.\n * @return the updated decrypted topic.\n */\n async removeParticipant(body: { dataOwnerId: string }, topicId: string): Promise<Topic> {\n const updatedTopic = await super.removeParticipant(body, topicId)\n return (await this.decrypt([updatedTopic]))[0]\n }\n\n async subscribeToTopicEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<Topic> | undefined,\n eventFired: (message: Topic) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n return await subscribeToEntityEvents(\n this.host,\n this.authApi,\n EntityWithDelegationTypeName.Topic,\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted) => (await this.decrypt([encrypted]))[0]\n ).then((rs) => new ConnectionImpl(rs))\n }\n\n createDelegationDeAnonymizationMetadata(entity: Topic, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Topic }, delegates)\n }\n\n /**\n * Like {@link getConflictsForEntity} but additionally decrypts the conflicting revisions for the given user.\n * @param user the current user.\n * @param entityId the id of the topic to retrieve the conflicts for.\n * @return the decrypted conflicting revisions of the topic.\n */\n getConflictsForEntityWithUser(user: models.User, entityId: string): Promise<Array<models.Topic>> {\n return super.getConflictsForEntity(entityId).then((ts) => this.decrypt(ts))\n }\n\n /**\n * Like {@link declareConflictWinner} but encrypts the winning revision before sending it and decrypts the saved\n * winner returned by the backend.\n * @param user the current user.\n * @param request the {@link models.ConflictResolutionRequest} carrying the (decrypted) winning revision and the conflicts to purge.\n * @return the {@link models.ConflictResolutionResult} with the decrypted saved winner and the conflicts that are still unresolved.\n */\n async declareConflictWinnerWithUser(\n user: models.User,\n request: models.ConflictResolutionRequest<models.Topic>\n ): Promise<models.ConflictResolutionResult<models.Topic>> {\n const encrypted = (await this.encrypt([cloneDeep(request.document!)]))[0]\n const result = await super.declareConflictWinner({ ...request, document: encrypted })\n if (result.document) result.document = (await this.decrypt([result.document]))[0]\n return result\n }\n\n /**\n * Like {@link getConflictsForEntityWithUser} but targets the entity of the group with the given id.\n * @param user the current user.\n * @param groupId the id of the group the topic belongs to.\n * @param entityId the id of the topic to retrieve the conflicts for.\n * @return the decrypted conflicting revisions of the topic.\n */\n getConflictsForEntityInGroupWithUser(user: models.User, groupId: string, entityId: string): Promise<Array<models.Topic>> {\n return super.getConflictsForEntityInGroup(groupId, entityId).then((ts) => this.decrypt(ts))\n }\n\n /**\n * Like {@link declareConflictWinnerWithUser} but targets the entity of the group with the given id.\n * @param user the current user.\n * @param groupId the id of the group the topic belongs to.\n * @param request the {@link models.ConflictResolutionRequest} carrying the (decrypted) winning revision and the conflicts to purge.\n * @return the {@link models.ConflictResolutionResult} with the decrypted saved winner and the conflicts that are still unresolved.\n */\n async declareConflictWinnerInGroupWithUser(\n user: models.User,\n groupId: string,\n request: models.ConflictResolutionRequest<models.Topic>\n ): Promise<models.ConflictResolutionResult<models.Topic>> {\n const encrypted = (await this.encrypt([cloneDeep(request.document!)]))[0]\n const result = await super.declareConflictWinnerInGroup(groupId, { ...request, document: encrypted })\n if (result.document) result.document = (await this.decrypt([result.document]))[0]\n return result\n }\n}\n"]}
|
|
@@ -28,20 +28,26 @@ export declare function dateDecode(dateNumber: number | null | undefined): Date
|
|
|
28
28
|
export declare function timeDecode(timeNumber: number | null | undefined): Date | undefined;
|
|
29
29
|
/**
|
|
30
30
|
* Encodes a Date object into a backend date number (e.g., patient birth date).
|
|
31
|
-
*
|
|
31
|
+
*
|
|
32
|
+
* A Date is formatted as usual. A String or a Number is interpreted as a fuzzy date that is already
|
|
33
|
+
* encoded (yyyyMMdd or yyyyMMddHHmmss) or as an epoch expressed in milliseconds.
|
|
34
|
+
* @param date a Date object, or a fuzzy date / epoch as a String or Number
|
|
32
35
|
* @return a YYYYMMDD date number for the backend
|
|
33
36
|
* @see #dateDecode
|
|
34
37
|
* @see #timeEncode
|
|
35
38
|
*/
|
|
36
|
-
export declare function dateEncode(date?: Date | null | undefined): number | undefined;
|
|
39
|
+
export declare function dateEncode(date?: Date | Number | String | null | undefined): number | undefined;
|
|
37
40
|
/**
|
|
38
41
|
* Encodes a Date object into a backend time number (e.g., health element openingDate).
|
|
39
|
-
*
|
|
42
|
+
*
|
|
43
|
+
* A Date is formatted as usual. A String or a Number is interpreted as a fuzzy date that is already
|
|
44
|
+
* encoded (yyyyMMdd or yyyyMMddHHmmss) or as an epoch expressed in milliseconds.
|
|
45
|
+
* @param date a Date object, or a fuzzy date / epoch as a String or Number
|
|
40
46
|
* @return a YYYYMMDDHHmmss date number for the backend
|
|
41
47
|
* @see #timeDecode
|
|
42
48
|
* @see #dateEncode
|
|
43
49
|
*/
|
|
44
|
-
export declare function timeEncode(date: Date | null | undefined): number | undefined;
|
|
50
|
+
export declare function timeEncode(date: Date | Number | String | null | undefined): number | undefined;
|
|
45
51
|
/**
|
|
46
52
|
* Formats a value and a physical unit into text.
|
|
47
53
|
* @param value the numerical or string value to encode
|
|
@@ -150,7 +150,10 @@ function timeDecode(timeNumber) {
|
|
|
150
150
|
}
|
|
151
151
|
/**
|
|
152
152
|
* Encodes a Date object into a backend date number (e.g., patient birth date).
|
|
153
|
-
*
|
|
153
|
+
*
|
|
154
|
+
* A Date is formatted as usual. A String or a Number is interpreted as a fuzzy date that is already
|
|
155
|
+
* encoded (yyyyMMdd or yyyyMMddHHmmss) or as an epoch expressed in milliseconds.
|
|
156
|
+
* @param date a Date object, or a fuzzy date / epoch as a String or Number
|
|
154
157
|
* @return a YYYYMMDD date number for the backend
|
|
155
158
|
* @see #dateDecode
|
|
156
159
|
* @see #timeEncode
|
|
@@ -159,13 +162,33 @@ function dateEncode(date) {
|
|
|
159
162
|
if (date === null || date === undefined) {
|
|
160
163
|
return undefined;
|
|
161
164
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
+
if (typeof date === 'string' && date.trim() === '')
|
|
166
|
+
return undefined;
|
|
167
|
+
if (date instanceof Date) {
|
|
168
|
+
// date is null if the field is not set
|
|
169
|
+
return date ? Number((0, date_fns_1.format)(date, 'yyyyMMdd').padStart(8, '19700101')) : undefined;
|
|
170
|
+
}
|
|
171
|
+
// A String or a Number is a fuzzy date (yyyyMMdd, yyyyMMddHHmmss) or an epoch in milliseconds
|
|
172
|
+
const fuzzy = Number(date);
|
|
173
|
+
if (!fuzzy || isNaN(fuzzy))
|
|
174
|
+
return undefined;
|
|
175
|
+
if (fuzzy >= 18000101 && fuzzy < 25400000) {
|
|
176
|
+
// already a yyyyMMdd fuzzy date
|
|
177
|
+
return fuzzy;
|
|
178
|
+
}
|
|
179
|
+
if (fuzzy >= 18000101000000) {
|
|
180
|
+
// a yyyyMMddHHmmss fuzzy date: keep only the date part
|
|
181
|
+
return Math.floor(fuzzy / 1000000);
|
|
182
|
+
}
|
|
183
|
+
// an epoch expressed in milliseconds
|
|
184
|
+
return Number((0, date_fns_1.format)(new Date(fuzzy), 'yyyyMMdd'));
|
|
165
185
|
}
|
|
166
186
|
/**
|
|
167
187
|
* Encodes a Date object into a backend time number (e.g., health element openingDate).
|
|
168
|
-
*
|
|
188
|
+
*
|
|
189
|
+
* A Date is formatted as usual. A String or a Number is interpreted as a fuzzy date that is already
|
|
190
|
+
* encoded (yyyyMMdd or yyyyMMddHHmmss) or as an epoch expressed in milliseconds.
|
|
191
|
+
* @param date a Date object, or a fuzzy date / epoch as a String or Number
|
|
169
192
|
* @return a YYYYMMDDHHmmss date number for the backend
|
|
170
193
|
* @see #timeDecode
|
|
171
194
|
* @see #dateEncode
|
|
@@ -173,7 +196,25 @@ function dateEncode(date) {
|
|
|
173
196
|
function timeEncode(date) {
|
|
174
197
|
if (date === null || date === undefined)
|
|
175
198
|
return undefined;
|
|
176
|
-
|
|
199
|
+
if (typeof date === 'string' && date.trim() === '')
|
|
200
|
+
return undefined;
|
|
201
|
+
if (date instanceof Date) {
|
|
202
|
+
return date ? Number((0, date_fns_1.format)(date, 'yyyyMMddHHmmss')) : undefined;
|
|
203
|
+
}
|
|
204
|
+
// A String or a Number is a fuzzy date (yyyyMMdd, yyyyMMddHHmmss) or an epoch in milliseconds
|
|
205
|
+
const fuzzy = Number(date);
|
|
206
|
+
if (!fuzzy || isNaN(fuzzy))
|
|
207
|
+
return undefined;
|
|
208
|
+
if (fuzzy >= 18000101 && fuzzy < 25400000) {
|
|
209
|
+
// a yyyyMMdd fuzzy date: pad the time part with zeroes
|
|
210
|
+
return fuzzy * 1000000;
|
|
211
|
+
}
|
|
212
|
+
if (fuzzy >= 18000101000000) {
|
|
213
|
+
// already a yyyyMMddHHmmss fuzzy date
|
|
214
|
+
return fuzzy;
|
|
215
|
+
}
|
|
216
|
+
// an epoch expressed in milliseconds
|
|
217
|
+
return Number((0, date_fns_1.format)(new Date(fuzzy), 'yyyyMMddHHmmss'));
|
|
177
218
|
}
|
|
178
219
|
/**
|
|
179
220
|
* Formats a value and a physical unit into text.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatting-util.js","sourceRoot":"","sources":["../../../icc-x-api/utils/formatting-util.ts"],"names":[],"mappings":";;;AAgBA,kCAaC;AAED,oCAOC;AAED,gCAGC;AAED,kCAGC;AAED,sCAGC;AAED,gCAGC;AAED,oCAGC;AAuBD,8CAQC;AAUD,gCAeC;AASD,gCAGC;AASD,gCAKC;AASD,gCAGC;AAOD,oBAWC;AAOD,wBAGC;AAMD,sBAGC;AAMD,kCAMC;AAED,gCAGC;AAED,4CAIC;AAsED,kEAwDC;AAED,4BAqBC;AA9WD,yDAA2E;AAC3E,uCAAiE;AAEjE,6BAA6B;AAC7B,MAAM,eAAe,GAAG,IAAI,CAAA;AAEf,QAAA,WAAW,GAAG,IAAI,MAAM,CAAC,oCAAoC,CAAC,CAAA;AAC9D,QAAA,UAAU,GAAG,IAAI,MAAM,CAAC,4CAA4C,CAAC,CAAA;AACrE,QAAA,UAAU,GAAG,IAAI,MAAM,CAAC,oCAAoC,CAAC,CAAA;AAE1E,MAAM,QAAQ,GAAG;IACf,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,WAAW,C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AAS,CAAA;YAC7D,MAAM,aAAa,GAAG,2BAA2B,CAAC,MAAM,CAAC,CAAA;YACzD,IAAI,aAAa,KAAK,IAAI,IAAI,aAAa,KAAK,SAAS;gBAAE,OAAO,SAAS,CAAA;YAC3E,OAAO,IAAA,iBAAU,EAAC,MAAM,EAAE,aAAa,EAAE;gBACvC,4BAA4B,EAAE,IAAI;gBAClC,2BAA2B,EAAE,IAAI;aAClC,CAAC,CAAA;QACJ,CAAC;KACF,CAAA;AACH,CAAC","sourcesContent":["import { parseNumber, formatNumber, ParsedNumber } from 'libphonenumber-js'\nimport {format as formatDate, parse as parseDate} from 'date-fns'\n\n// TODO: move this to env.js?\nconst DEFAULT_COUNTRY = 'BE'\n\nexport const nihiiRegExp = new RegExp('^(\\\\d{1})(\\\\d{5})(\\\\d{2})(\\\\d{3})$')\nexport const ssinRegExp = new RegExp('^(\\\\d{2})(\\\\d{2})(\\\\d{2})(\\\\d{3})(\\\\d{2})$')\nexport const ibanRegExp = new RegExp('^(\\\\d{4})(\\\\d{4})(\\\\d{4})(\\\\d{4})$')\n\nconst patterns = {\n IBAN: (iban: string) => /^BE\\d{14}$/.test(iban) && isValidIBAN(iban),\n IBANBE: (iban: string) => /^BE\\d{14}$/.test(iban) && isValidIBAN(iban),\n}\n\n//http://ht5ifv.serprest.pt/extensions/tools/IBAN/\nexport function isValidIBAN(iban: string | null | undefined): boolean | undefined {\n if (iban === null || iban === undefined) return undefined\n //This function check if the checksum if correct\n iban = iban.replace(/^(.{4})(.*)$/, '$2$1') //Move the first 4 chars from left to the right\n const fun = (e: string) => (e.charCodeAt(0) - 'A'.charCodeAt(0) + 10).toString()\n iban = iban.replace(/[A-Z]/g, fun) //Convert A-Z to 10-25\n let $sum = 0\n let $ei = 1 //First exponent\n for (let $i = iban.length - 1; $i >= 0; $i--) {\n $sum += $ei * parseInt(iban.charAt($i), 10) //multiply the digit by it's exponent\n $ei = ($ei * 10) % 97 //compute next base 10 exponent in modulus 97\n }\n return $sum % 97 === 1\n}\n\nexport function ibanValidate(iban: string | null | undefined): boolean | undefined {\n if (iban === null || iban === undefined) return undefined\n if (iban.startsWith('BE')) {\n return patterns.IBANBE(iban)\n } else {\n return patterns.IBAN(iban)\n }\n}\n\nexport function ibanFormat(iban: string | null | undefined): string | undefined {\n if (iban === null || iban === undefined) return undefined\n return iban.replace(ibanRegExp, '$1 $2 $3 $4')\n}\n\nexport function nihiiFormat(nihii: string | null | undefined): string | undefined {\n if (nihii === null || nihii === undefined) return undefined\n return nihii.replace(nihiiRegExp, '$1 $2 $3 $4')\n}\n\nexport function nihiiValidate(nihii: string | null | undefined): boolean | undefined {\n if (nihii === null || nihii === undefined) return undefined\n return !!nihii.match(nihiiRegExp)\n}\n\nexport function ssinFormat(ssin: string | null | undefined): string | undefined {\n if (ssin === null || ssin === undefined) return undefined\n return ssin.replace(ssinRegExp, '$1 $2 $3 $4 $5')\n}\n\nexport function ssinValidate(ssin: string | null | undefined): boolean | undefined {\n if (ssin === null || ssin === undefined) return undefined\n return !!ssin.match(ssinRegExp)\n}\n\n/* Alternate lib free version\nexport function phoneNumberValidate(phoneNumber: string): boolean {\n return (\n !!phoneNumber.match(/(?:\\+|00)([1-9][0-9]{1-2})([- /.]*([0-9]+))+/) ||\n !!phoneNumber.match(/(0[1-9][0-9]*)([- /.]*([0-9]+))+/)\n )\n}\n\nexport function phoneNumberFormat(phoneNumber: string): string {\n let match = phoneNumber.match(/(?:\\+|00)([1-9][0-9]{1-2})([- /.]*([0-9]+))+/)\n if (match) {\n return `+${match[1]} ${match[2].replace(/[- /.]/g, \" \")}`.replace(/ /g, \" \")\n }\n match = phoneNumber.match(/0([1-9][0-9]*)([- /.]*([0-9]+))+/)\n if (match) {\n return `+32 ${match[1]} ${match[2].replace(/[- /.]/g, \" \")}`.replace(/ /g, \" \")\n }\n return phoneNumber\n}\n*/\n\nexport function phoneNumberFormat(phoneNumber: string | null | undefined): string | undefined {\n if (phoneNumber === null || phoneNumber === undefined) return undefined\n const parsedPhoneNumber = parseNumber(phoneNumber, DEFAULT_COUNTRY) as ParsedNumber\n if (Object.keys(parsedPhoneNumber).length === 0) {\n // The number is not valid, so we leave the input string as-is.\n return phoneNumber\n }\n return formatNumber(parsedPhoneNumber, 'INTERNATIONAL')\n}\n\n/**\n * Converts a backend date number (e.g., patient birth date) into a Date object.\n * @param dateNumber a YYYYMMDD date number from the backend\n * @return a Date object\n * @throws Error if it is impossible to create a date from the number, other if dateNumber is negative.\n * @see #dateEncode\n * @see #timeDecode\n */\nexport function dateDecode(dateNumber: number | null | undefined): Date | undefined {\n if (dateNumber === null || dateNumber === undefined) return undefined\n\n if (dateNumber < 0) {\n throw new Error(\"We don't decode negative dates. Please make sure you have valid data.\")\n }\n const dateNumberStr: string = dateNumber.toString().padStart(8, '19700101')\n if (dateNumberStr.length > 8) {\n if (dateNumberStr.endsWith('000000')) {\n return dateNumber ? parseDate(dateNumberStr.slice(0, 8), 'yyyyMMdd', new Date()) : undefined\n }\n\n throw Error(\"Decoded date is over year 9999. We can't format it properly.\")\n }\n return dateNumber ? parseDate(dateNumberStr, 'yyyyMMdd', new Date()) : undefined\n}\n\n/**\n * Converts a backend time number (e.g., health element openingDate) into a Date object.\n * @param timeNumber a YYYYMMDD date number from the backend\n * @return a Date object\n * @see #timeEncode\n * @see #dateDecode\n */\nexport function timeDecode(timeNumber: number | null | undefined): Date | undefined {\n if (timeNumber === null || timeNumber === undefined) return undefined\n return timeNumber ? parseDate(timeNumber.toString(), 'yyyyMMddHHmmss', new Date()) : undefined\n}\n\n/**\n * Encodes a Date object into a backend date number (e.g., patient birth date).\n * @param date a Date object\n * @return a YYYYMMDD date number for the backend\n * @see #dateDecode\n * @see #timeEncode\n */\nexport function dateEncode(date?: Date | null | undefined): number | undefined {\n if (date === null || date === undefined) { return undefined }\n const dateStr = formatDate(date, 'yyyyMMdd').padStart(8, '19700101')\n // date is null if the field is not set\n return date ? Number(dateStr) : undefined\n}\n\n/**\n * Encodes a Date object into a backend time number (e.g., health element openingDate).\n * @param date a Date object\n * @return a YYYYMMDDHHmmss date number for the backend\n * @see #timeDecode\n * @see #dateEncode\n */\nexport function timeEncode(date: Date | null | undefined): number | undefined {\n if (date === null || date === undefined) return undefined\n return date ? Number(formatDate(date, 'yyyyMMddHHmmss')) : undefined\n}\n\n/**\n * Formats a value and a physical unit into text.\n * @param value the numerical or string value to encode\n * @param unit the unit represented as a string (an empty string is also supported)\n */\nexport function unit(value: number | string | null | undefined, unit: string | null | undefined): string | undefined {\n if (value === null || value === undefined) return undefined\n unit = unit || ''\n let separator: string\n if (!unit || unit.startsWith('°')) {\n separator = ''\n } else {\n // including '%'\n separator = '\\xa0'\n }\n return value + separator + unit\n}\n\n/**\n * 0.1 + 0.2 = 0.30000000000000004. Use this function to be better at maths.\n * @param value number\n * @return the rounded number, two after the comma\n */\nexport function amount(value: number | null | undefined): number | undefined {\n if (value === null || value === undefined) return undefined\n return Number(value.toFixed(2))\n}\n\n/**\n * A simple formatter to keep the logic across the app.\n * Input: 2.1 ; Output: 2.10€\n */\nexport function money(value: number | null | undefined): string | undefined {\n if (value === null || value === undefined) return undefined\n return [value.toFixed(2), '€'].join('')\n}\n\n/**\n * Transform a dictionary to a url params.\n * From { key1: value1, key2: value2, ... } returns key1=value1&key2=value2&...=...\n */\nexport function toUrlParams(params: { [key: string]: string } | null | undefined): string | undefined {\n if (params === null || params === undefined) return undefined\n return Object.entries(params)\n .map(([key, value]) => (value ? key + '=' + value : undefined))\n .filter(Boolean)\n .join('&')\n}\n\nexport function personName(person: { firstName?: string; lastName?: string } | null | undefined): string | undefined {\n if (person === null || person === undefined) return undefined\n return `${person.firstName || ''} ${person.lastName || ''}`.trim()\n}\n\nexport function personNameAbbrev(person: { firstName?: string; lastName?: string } | null | undefined): string | undefined {\n if (person === null || person === undefined) return undefined\n const firstName = person.firstName ? person.firstName[0] + '.' : undefined\n return personName({...person, firstName})\n}\n\n// Moment.js → date-fns format token mapping. Listed longest-first so the\n// matcher consumes the longest valid moment token at each position.\nconst MOMENT_TO_DATE_FNS_TOKENS: ReadonlyArray<readonly [string, string]> = [\n // Year\n ['YYYY', 'yyyy'],\n ['YY', 'yy'],\n ['Y', 'y'],\n // Month\n ['MMMM', 'MMMM'],\n ['MMM', 'MMM'],\n ['Mo', 'Mo'],\n ['MM', 'MM'],\n ['M', 'M'],\n // Quarter\n ['Qo', 'Qo'],\n ['Q', 'Q'],\n // Day of year (moment DDD/DDDD/DDDo → date-fns D/DDD/Do, additional tokens)\n ['DDDDo', 'Do'],\n ['DDDD', 'DDD'],\n ['DDDo', 'Do'],\n ['DDD', 'D'],\n // Day of month\n ['Do', 'do'],\n ['DD', 'dd'],\n ['D', 'd'],\n // Day of week\n ['dddd', 'EEEE'],\n ['ddd', 'EEE'],\n ['dd', 'EEEEEE'],\n ['do', 'eo'],\n ['d', 'e'],\n ['E', 'i'],\n // Week of year\n ['ww', 'ww'],\n ['wo', 'wo'],\n ['w', 'w'],\n ['WW', 'II'],\n ['Wo', 'Io'],\n ['W', 'I'],\n // Hour\n ['HH', 'HH'],\n ['H', 'H'],\n ['hh', 'hh'],\n ['h', 'h'],\n ['kk', 'kk'],\n ['k', 'k'],\n // AM/PM\n ['A', 'a'],\n ['a', 'aaa'],\n // Minute\n ['mm', 'mm'],\n ['m', 'm'],\n // Second\n ['ss', 'ss'],\n ['s', 's'],\n // Fractional seconds\n ['SSSS', 'SSSS'],\n ['SSS', 'SSS'],\n ['SS', 'SS'],\n ['S', 'S'],\n // Timezone offset\n ['ZZ', 'xx'],\n ['Z', 'xxx'],\n // Unix timestamp\n ['X', 't'],\n ['x', 'T'],\n]\n\nexport function momentFormatToDateFnsFormat(format: string | null | undefined): string | undefined {\n if (format === null || format === undefined) return undefined\n const parts: string[] = []\n let literalBuffer = ''\n\n const flushLiteral = () => {\n if (literalBuffer.length > 0) {\n parts.push(\"'\" + literalBuffer.replace(/'/g, \"''\") + \"'\")\n literalBuffer = ''\n }\n }\n\n let i = 0\n while (i < format.length) {\n const c = format[i]\n\n // Moment bracketed literal: [text] → date-fns 'text'\n if (c === '[') {\n const end = format.indexOf(']', i)\n if (end === -1) {\n literalBuffer += format.substring(i + 1)\n i = format.length\n continue\n }\n literalBuffer += format.substring(i + 1, end)\n i = end + 1\n continue\n }\n\n // Match the longest moment token starting at the current position.\n let matched: readonly [string, string] | undefined\n for (const token of MOMENT_TO_DATE_FNS_TOKENS) {\n if (format.startsWith(token[0], i)) {\n matched = token\n break\n }\n }\n if (matched) {\n flushLiteral()\n parts.push(matched[1])\n i += matched[0].length\n continue\n }\n\n // Non-token character: alphabetic chars must be escaped as literals,\n // otherwise date-fns would interpret them as its own tokens.\n if (/[A-Za-z]/.test(c)) {\n literalBuffer += c\n } else {\n flushLiteral()\n parts.push(c)\n }\n i++\n }\n flushLiteral()\n return parts.join('')\n}\n\nexport function toMoment(epochOrLongCalendar: number | null | undefined): { format: (format: string | null | undefined) => string | undefined } | undefined {\n if (epochOrLongCalendar === null || epochOrLongCalendar === undefined) return undefined\n if (!epochOrLongCalendar && epochOrLongCalendar !== 0) {\n return undefined\n }\n const parsed = (epochOrLongCalendar >= 18000101 && epochOrLongCalendar < 25400000) ?\n parseDate('' + epochOrLongCalendar, 'yyyyMMdd', new Date()) :\n (epochOrLongCalendar >= 18000101000000) ?\n parseDate('' + epochOrLongCalendar, 'yyyyMMddHHmmss', new Date()) :\n new Date(epochOrLongCalendar)\n return {\n format: (format: string | null | undefined): string | undefined => {\n if (format === null || format === undefined) return undefined\n const dateFnsFormat = momentFormatToDateFnsFormat(format)\n if (dateFnsFormat === null || dateFnsFormat === undefined) return undefined\n return formatDate(parsed, dateFnsFormat, {\n useAdditionalDayOfYearTokens: true,\n useAdditionalWeekYearTokens: true,\n })\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"formatting-util.js","sourceRoot":"","sources":["../../../icc-x-api/utils/formatting-util.ts"],"names":[],"mappings":";;;AAgBA,kCAaC;AAED,oCAOC;AAED,gCAGC;AAED,kCAGC;AAED,sCAG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mB,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IACvF,IAAI,CAAC,mBAAmB,IAAI,mBAAmB,KAAK,CAAC,EAAE,CAAC;QACtD,OAAO,SAAS,CAAA;IAClB,CAAC;IACD,MAAM,MAAM,GAAG,CAAC,mBAAmB,IAAI,QAAQ,IAAI,mBAAmB,GAAG,QAAQ,CAAC,CAAC,CAAC;QAClF,IAAA,gBAAS,EAAC,EAAE,GAAG,mBAAmB,EAAE,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;QAC7D,CAAC,mBAAmB,IAAI,cAAc,CAAC,CAAC,CAAC;YACvC,IAAA,gBAAS,EAAC,EAAE,GAAG,mBAAmB,EAAE,gBAAgB,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC;YACnE,IAAI,IAAI,CAAC,mBAAmB,CAAC,CAAA;IACjC,OAAO;QACL,MAAM,EAAE,CAAC,MAAiC,EAAsB,EAAE;YAChE,IAAI,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,SAAS;gBAAE,OAAO,SAAS,CAAA;YAC7D,MAAM,aAAa,GAAG,2BAA2B,CAAC,MAAM,CAAC,CAAA;YACzD,IAAI,aAAa,KAAK,IAAI,IAAI,aAAa,KAAK,SAAS;gBAAE,OAAO,SAAS,CAAA;YAC3E,OAAO,IAAA,iBAAU,EAAC,MAAM,EAAE,aAAa,EAAE;gBACvC,4BAA4B,EAAE,IAAI;gBAClC,2BAA2B,EAAE,IAAI;aAClC,CAAC,CAAA;QACJ,CAAC;KACF,CAAA;AACH,CAAC","sourcesContent":["import { parseNumber, formatNumber, ParsedNumber } from 'libphonenumber-js'\nimport {format as formatDate, parse as parseDate} from 'date-fns'\n\n// TODO: move this to env.js?\nconst DEFAULT_COUNTRY = 'BE'\n\nexport const nihiiRegExp = new RegExp('^(\\\\d{1})(\\\\d{5})(\\\\d{2})(\\\\d{3})$')\nexport const ssinRegExp = new RegExp('^(\\\\d{2})(\\\\d{2})(\\\\d{2})(\\\\d{3})(\\\\d{2})$')\nexport const ibanRegExp = new RegExp('^(\\\\d{4})(\\\\d{4})(\\\\d{4})(\\\\d{4})$')\n\nconst patterns = {\n IBAN: (iban: string) => /^BE\\d{14}$/.test(iban) && isValidIBAN(iban),\n IBANBE: (iban: string) => /^BE\\d{14}$/.test(iban) && isValidIBAN(iban),\n}\n\n//http://ht5ifv.serprest.pt/extensions/tools/IBAN/\nexport function isValidIBAN(iban: string | null | undefined): boolean | undefined {\n if (iban === null || iban === undefined) return undefined\n //This function check if the checksum if correct\n iban = iban.replace(/^(.{4})(.*)$/, '$2$1') //Move the first 4 chars from left to the right\n const fun = (e: string) => (e.charCodeAt(0) - 'A'.charCodeAt(0) + 10).toString()\n iban = iban.replace(/[A-Z]/g, fun) //Convert A-Z to 10-25\n let $sum = 0\n let $ei = 1 //First exponent\n for (let $i = iban.length - 1; $i >= 0; $i--) {\n $sum += $ei * parseInt(iban.charAt($i), 10) //multiply the digit by it's exponent\n $ei = ($ei * 10) % 97 //compute next base 10 exponent in modulus 97\n }\n return $sum % 97 === 1\n}\n\nexport function ibanValidate(iban: string | null | undefined): boolean | undefined {\n if (iban === null || iban === undefined) return undefined\n if (iban.startsWith('BE')) {\n return patterns.IBANBE(iban)\n } else {\n return patterns.IBAN(iban)\n }\n}\n\nexport function ibanFormat(iban: string | null | undefined): string | undefined {\n if (iban === null || iban === undefined) return undefined\n return iban.replace(ibanRegExp, '$1 $2 $3 $4')\n}\n\nexport function nihiiFormat(nihii: string | null | undefined): string | undefined {\n if (nihii === null || nihii === undefined) return undefined\n return nihii.replace(nihiiRegExp, '$1 $2 $3 $4')\n}\n\nexport function nihiiValidate(nihii: string | null | undefined): boolean | undefined {\n if (nihii === null || nihii === undefined) return undefined\n return !!nihii.match(nihiiRegExp)\n}\n\nexport function ssinFormat(ssin: string | null | undefined): string | undefined {\n if (ssin === null || ssin === undefined) return undefined\n return ssin.replace(ssinRegExp, '$1 $2 $3 $4 $5')\n}\n\nexport function ssinValidate(ssin: string | null | undefined): boolean | undefined {\n if (ssin === null || ssin === undefined) return undefined\n return !!ssin.match(ssinRegExp)\n}\n\n/* Alternate lib free version\nexport function phoneNumberValidate(phoneNumber: string): boolean {\n return (\n !!phoneNumber.match(/(?:\\+|00)([1-9][0-9]{1-2})([- /.]*([0-9]+))+/) ||\n !!phoneNumber.match(/(0[1-9][0-9]*)([- /.]*([0-9]+))+/)\n )\n}\n\nexport function phoneNumberFormat(phoneNumber: string): string {\n let match = phoneNumber.match(/(?:\\+|00)([1-9][0-9]{1-2})([- /.]*([0-9]+))+/)\n if (match) {\n return `+${match[1]} ${match[2].replace(/[- /.]/g, \" \")}`.replace(/ /g, \" \")\n }\n match = phoneNumber.match(/0([1-9][0-9]*)([- /.]*([0-9]+))+/)\n if (match) {\n return `+32 ${match[1]} ${match[2].replace(/[- /.]/g, \" \")}`.replace(/ /g, \" \")\n }\n return phoneNumber\n}\n*/\n\nexport function phoneNumberFormat(phoneNumber: string | null | undefined): string | undefined {\n if (phoneNumber === null || phoneNumber === undefined) return undefined\n const parsedPhoneNumber = parseNumber(phoneNumber, DEFAULT_COUNTRY) as ParsedNumber\n if (Object.keys(parsedPhoneNumber).length === 0) {\n // The number is not valid, so we leave the input string as-is.\n return phoneNumber\n }\n return formatNumber(parsedPhoneNumber, 'INTERNATIONAL')\n}\n\n/**\n * Converts a backend date number (e.g., patient birth date) into a Date object.\n * @param dateNumber a YYYYMMDD date number from the backend\n * @return a Date object\n * @throws Error if it is impossible to create a date from the number, other if dateNumber is negative.\n * @see #dateEncode\n * @see #timeDecode\n */\nexport function dateDecode(dateNumber: number | null | undefined): Date | undefined {\n if (dateNumber === null || dateNumber === undefined) return undefined\n\n if (dateNumber < 0) {\n throw new Error(\"We don't decode negative dates. Please make sure you have valid data.\")\n }\n const dateNumberStr: string = dateNumber.toString().padStart(8, '19700101')\n if (dateNumberStr.length > 8) {\n if (dateNumberStr.endsWith('000000')) {\n return dateNumber ? parseDate(dateNumberStr.slice(0, 8), 'yyyyMMdd', new Date()) : undefined\n }\n\n throw Error(\"Decoded date is over year 9999. We can't format it properly.\")\n }\n return dateNumber ? parseDate(dateNumberStr, 'yyyyMMdd', new Date()) : undefined\n}\n\n/**\n * Converts a backend time number (e.g., health element openingDate) into a Date object.\n * @param timeNumber a YYYYMMDD date number from the backend\n * @return a Date object\n * @see #timeEncode\n * @see #dateDecode\n */\nexport function timeDecode(timeNumber: number | null | undefined): Date | undefined {\n if (timeNumber === null || timeNumber === undefined) return undefined\n return timeNumber ? parseDate(timeNumber.toString(), 'yyyyMMddHHmmss', new Date()) : undefined\n}\n\n/**\n * Encodes a Date object into a backend date number (e.g., patient birth date).\n *\n * A Date is formatted as usual. A String or a Number is interpreted as a fuzzy date that is already\n * encoded (yyyyMMdd or yyyyMMddHHmmss) or as an epoch expressed in milliseconds.\n * @param date a Date object, or a fuzzy date / epoch as a String or Number\n * @return a YYYYMMDD date number for the backend\n * @see #dateDecode\n * @see #timeEncode\n */\nexport function dateEncode(date?: Date | Number | String | null | undefined): number | undefined {\n if (date === null || date === undefined) { return undefined }\n if (typeof date === 'string' && date.trim() === '') return undefined\n if (date instanceof Date) {\n // date is null if the field is not set\n return date ? Number(formatDate(date, 'yyyyMMdd').padStart(8, '19700101')) : undefined\n }\n // A String or a Number is a fuzzy date (yyyyMMdd, yyyyMMddHHmmss) or an epoch in milliseconds\n const fuzzy = Number(date)\n if (!fuzzy || isNaN(fuzzy)) return undefined\n if (fuzzy >= 18000101 && fuzzy < 25400000) {\n // already a yyyyMMdd fuzzy date\n return fuzzy\n }\n if (fuzzy >= 18000101000000) {\n // a yyyyMMddHHmmss fuzzy date: keep only the date part\n return Math.floor(fuzzy / 1000000)\n }\n // an epoch expressed in milliseconds\n return Number(formatDate(new Date(fuzzy), 'yyyyMMdd'))\n}\n\n/**\n * Encodes a Date object into a backend time number (e.g., health element openingDate).\n *\n * A Date is formatted as usual. A String or a Number is interpreted as a fuzzy date that is already\n * encoded (yyyyMMdd or yyyyMMddHHmmss) or as an epoch expressed in milliseconds.\n * @param date a Date object, or a fuzzy date / epoch as a String or Number\n * @return a YYYYMMDDHHmmss date number for the backend\n * @see #timeDecode\n * @see #dateEncode\n */\nexport function timeEncode(date: Date | Number | String | null | undefined): number | undefined {\n if (date === null || date === undefined) return undefined\n if (typeof date === 'string' && date.trim() === '') return undefined\n if (date instanceof Date) {\n return date ? Number(formatDate(date, 'yyyyMMddHHmmss')) : undefined\n }\n // A String or a Number is a fuzzy date (yyyyMMdd, yyyyMMddHHmmss) or an epoch in milliseconds\n const fuzzy = Number(date)\n if (!fuzzy || isNaN(fuzzy)) return undefined\n if (fuzzy >= 18000101 && fuzzy < 25400000) {\n // a yyyyMMdd fuzzy date: pad the time part with zeroes\n return fuzzy * 1000000\n }\n if (fuzzy >= 18000101000000) {\n // already a yyyyMMddHHmmss fuzzy date\n return fuzzy\n }\n // an epoch expressed in milliseconds\n return Number(formatDate(new Date(fuzzy), 'yyyyMMddHHmmss'))\n}\n\n/**\n * Formats a value and a physical unit into text.\n * @param value the numerical or string value to encode\n * @param unit the unit represented as a string (an empty string is also supported)\n */\nexport function unit(value: number | string | null | undefined, unit: string | null | undefined): string | undefined {\n if (value === null || value === undefined) return undefined\n unit = unit || ''\n let separator: string\n if (!unit || unit.startsWith('°')) {\n separator = ''\n } else {\n // including '%'\n separator = '\\xa0'\n }\n return value + separator + unit\n}\n\n/**\n * 0.1 + 0.2 = 0.30000000000000004. Use this function to be better at maths.\n * @param value number\n * @return the rounded number, two after the comma\n */\nexport function amount(value: number | null | undefined): number | undefined {\n if (value === null || value === undefined) return undefined\n return Number(value.toFixed(2))\n}\n\n/**\n * A simple formatter to keep the logic across the app.\n * Input: 2.1 ; Output: 2.10€\n */\nexport function money(value: number | null | undefined): string | undefined {\n if (value === null || value === undefined) return undefined\n return [value.toFixed(2), '€'].join('')\n}\n\n/**\n * Transform a dictionary to a url params.\n * From { key1: value1, key2: value2, ... } returns key1=value1&key2=value2&...=...\n */\nexport function toUrlParams(params: { [key: string]: string } | null | undefined): string | undefined {\n if (params === null || params === undefined) return undefined\n return Object.entries(params)\n .map(([key, value]) => (value ? key + '=' + value : undefined))\n .filter(Boolean)\n .join('&')\n}\n\nexport function personName(person: { firstName?: string; lastName?: string } | null | undefined): string | undefined {\n if (person === null || person === undefined) return undefined\n return `${person.firstName || ''} ${person.lastName || ''}`.trim()\n}\n\nexport function personNameAbbrev(person: { firstName?: string; lastName?: string } | null | undefined): string | undefined {\n if (person === null || person === undefined) return undefined\n const firstName = person.firstName ? person.firstName[0] + '.' : undefined\n return personName({...person, firstName})\n}\n\n// Moment.js → date-fns format token mapping. Listed longest-first so the\n// matcher consumes the longest valid moment token at each position.\nconst MOMENT_TO_DATE_FNS_TOKENS: ReadonlyArray<readonly [string, string]> = [\n // Year\n ['YYYY', 'yyyy'],\n ['YY', 'yy'],\n ['Y', 'y'],\n // Month\n ['MMMM', 'MMMM'],\n ['MMM', 'MMM'],\n ['Mo', 'Mo'],\n ['MM', 'MM'],\n ['M', 'M'],\n // Quarter\n ['Qo', 'Qo'],\n ['Q', 'Q'],\n // Day of year (moment DDD/DDDD/DDDo → date-fns D/DDD/Do, additional tokens)\n ['DDDDo', 'Do'],\n ['DDDD', 'DDD'],\n ['DDDo', 'Do'],\n ['DDD', 'D'],\n // Day of month\n ['Do', 'do'],\n ['DD', 'dd'],\n ['D', 'd'],\n // Day of week\n ['dddd', 'EEEE'],\n ['ddd', 'EEE'],\n ['dd', 'EEEEEE'],\n ['do', 'eo'],\n ['d', 'e'],\n ['E', 'i'],\n // Week of year\n ['ww', 'ww'],\n ['wo', 'wo'],\n ['w', 'w'],\n ['WW', 'II'],\n ['Wo', 'Io'],\n ['W', 'I'],\n // Hour\n ['HH', 'HH'],\n ['H', 'H'],\n ['hh', 'hh'],\n ['h', 'h'],\n ['kk', 'kk'],\n ['k', 'k'],\n // AM/PM\n ['A', 'a'],\n ['a', 'aaa'],\n // Minute\n ['mm', 'mm'],\n ['m', 'm'],\n // Second\n ['ss', 'ss'],\n ['s', 's'],\n // Fractional seconds\n ['SSSS', 'SSSS'],\n ['SSS', 'SSS'],\n ['SS', 'SS'],\n ['S', 'S'],\n // Timezone offset\n ['ZZ', 'xx'],\n ['Z', 'xxx'],\n // Unix timestamp\n ['X', 't'],\n ['x', 'T'],\n]\n\nexport function momentFormatToDateFnsFormat(format: string | null | undefined): string | undefined {\n if (format === null || format === undefined) return undefined\n const parts: string[] = []\n let literalBuffer = ''\n\n const flushLiteral = () => {\n if (literalBuffer.length > 0) {\n parts.push(\"'\" + literalBuffer.replace(/'/g, \"''\") + \"'\")\n literalBuffer = ''\n }\n }\n\n let i = 0\n while (i < format.length) {\n const c = format[i]\n\n // Moment bracketed literal: [text] → date-fns 'text'\n if (c === '[') {\n const end = format.indexOf(']', i)\n if (end === -1) {\n literalBuffer += format.substring(i + 1)\n i = format.length\n continue\n }\n literalBuffer += format.substring(i + 1, end)\n i = end + 1\n continue\n }\n\n // Match the longest moment token starting at the current position.\n let matched: readonly [string, string] | undefined\n for (const token of MOMENT_TO_DATE_FNS_TOKENS) {\n if (format.startsWith(token[0], i)) {\n matched = token\n break\n }\n }\n if (matched) {\n flushLiteral()\n parts.push(matched[1])\n i += matched[0].length\n continue\n }\n\n // Non-token character: alphabetic chars must be escaped as literals,\n // otherwise date-fns would interpret them as its own tokens.\n if (/[A-Za-z]/.test(c)) {\n literalBuffer += c\n } else {\n flushLiteral()\n parts.push(c)\n }\n i++\n }\n flushLiteral()\n return parts.join('')\n}\n\nexport function toMoment(epochOrLongCalendar: number | null | undefined): { format: (format: string | null | undefined) => string | undefined } | undefined {\n if (epochOrLongCalendar === null || epochOrLongCalendar === undefined) return undefined\n if (!epochOrLongCalendar && epochOrLongCalendar !== 0) {\n return undefined\n }\n const parsed = (epochOrLongCalendar >= 18000101 && epochOrLongCalendar < 25400000) ?\n parseDate('' + epochOrLongCalendar, 'yyyyMMdd', new Date()) :\n (epochOrLongCalendar >= 18000101000000) ?\n parseDate('' + epochOrLongCalendar, 'yyyyMMddHHmmss', new Date()) :\n new Date(epochOrLongCalendar)\n return {\n format: (format: string | null | undefined): string | undefined => {\n if (format === null || format === undefined) return undefined\n const dateFnsFormat = momentFormatToDateFnsFormat(format)\n if (dateFnsFormat === null || dateFnsFormat === undefined) return undefined\n return formatDate(parsed, dateFnsFormat, {\n useAdditionalDayOfYearTokens: true,\n useAdditionalWeekYearTokens: true,\n })\n }\n }\n}\n"]}
|