@openforis/arena-core 2.3.34 → 2.3.36
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/dist/esm/expression/javascript/evaluator.js +1 -1
- package/dist/esm/expression/javascript/evaluator.js.map +1 -1
- package/dist/esm/job/JobBase.js +20 -2
- package/dist/esm/job/JobBase.js.map +1 -1
- package/dist/esm/record/_records/nodeDefSelfReferences.js +57 -0
- package/dist/esm/record/_records/nodeDefSelfReferences.js.map +1 -0
- package/dist/esm/record/_records/recordGetters.js +8 -4
- package/dist/esm/record/_records/recordGetters.js.map +1 -1
- package/dist/expression/javascript/evaluator.d.ts +1 -0
- package/dist/expression/javascript/evaluator.js +3 -2
- package/dist/expression/javascript/evaluator.js.map +1 -1
- package/dist/job/JobBase.d.ts +8 -1
- package/dist/job/JobBase.js +20 -2
- package/dist/job/JobBase.js.map +1 -1
- package/dist/record/_records/nodeDefSelfReferences.d.ts +8 -0
- package/dist/record/_records/nodeDefSelfReferences.js +60 -0
- package/dist/record/_records/nodeDefSelfReferences.js.map +1 -0
- package/dist/record/_records/recordGetters.js +8 -4
- package/dist/record/_records/recordGetters.js.map +1 -1
- package/package.json +1 -1
|
@@ -40,7 +40,7 @@ const defaultEvaluators = {
|
|
|
40
40
|
const PARSED_EXPRESSIONS_CACHE_MAX_SIZE = 1000;
|
|
41
41
|
const parsedExpressionsCache = new Map();
|
|
42
42
|
const expressionParser = new JavascriptExpressionParser();
|
|
43
|
-
const parseExpression = (expression) => {
|
|
43
|
+
export const parseExpression = (expression) => {
|
|
44
44
|
let expressionNode = parsedExpressionsCache.get(expression);
|
|
45
45
|
if (!expressionNode) {
|
|
46
46
|
expressionNode = expressionParser.parse(expression);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"evaluator.js","sourceRoot":"","sources":["../../../../src/expression/javascript/evaluator.ts"],"names":[],"mappings":";;;;;;;;;AAGA,OAAO,EAAsD,kBAAkB,EAAE,MAAM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C,CAAA;QACrF,CAAC;QACD,sBAAsB,CAAC,GAAG,CAAC,UAAU,EAAE,cAAc,CAAC,CAAA;IACxD,CAAC;IACD,OAAO,cAAc,CAAA;AACvB,CAAC,CAAA;AAED,MAAM,OAAO,6BAA6B;IAIxC,YAAY,YAAoC,EAAE,EAAE,aAA4B,EAAE;QAChF,IAAI,CAAC,UAAU,mCAAQ,iBAAiB,GAAK,UAAU,CAAE,CAAA;QACzD,IAAI,CAAC,SAAS,mCAAQ,gBAAgB,GAAK,SAAS,CAAE,CAAA;IACxD,CAAC;IAEK,QAAQ,CAAC,UAAkB,EAAE,OAAW;;YAC5C,OAAO,IAAI,CAAC,YAAY,CAAC,eAAe,CAAC,UAAU,CAAC,EAAE,OAAO,aAAP,OAAO,cAAP,OAAO,GAAK,EAAQ,CAAC,CAAA;QAC7E,CAAC;KAAA;IAEK,YAAY,CAAC,cAAkD,EAAE,OAAU;;YAC/E,MAAM,EAAE,IAAI,EAAE,GAAG,cAAc,CAAA;YAE/B,MAAM,aAAa,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;YAC3C,IAAI,CAAC,aAAa,EAAE,CAAC;gBACnB,MAAM,IAAI,WAAW,CAAC,oCAAoC,EAAE,EAAE,IAAI,EAAE,CAAC,CAAA;YACvE,CAAC;YACD,OAAO,IAAI,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAA;QAClE,CAAC;KAAA;CACF","sourcesContent":["import { ExpressionContext } from '../context'\nimport { ExpressionEvaluator } from '../evaluator'\nimport { ExpressionFunctions } from '../function'\nimport { ExpressionNode, ExpressionNodeEvaluatorConstructor, ExpressionNodeType } from '../node'\nimport { SystemError } from '../../error'\n\nimport { functionsDefault } from './functionsDefault'\nimport { ArrayEvaluator } from './node/array'\nimport { BinaryEvaluator } from './node/binary'\nimport { CallEvaluator } from './node/call'\nimport { CompoundEvaluator } from './node/compound'\nimport { ConditionalEvaluator } from './node/conditional'\nimport { IdentifierEvaluator } from './node/identifier'\nimport { LiteralEvaluator } from './node/literal'\nimport { MemberEvaluator } from './node/member'\nimport { SequenceEvaluator } from './node/sequence'\nimport { ThisEvaluator } from './node/this'\nimport { UnaryEvaluator } from './node/unary'\nimport { JavascriptExpressionParser } from './parser/parser'\n\ntype Evaluators<C extends ExpressionContext> = {\n [nodeType in ExpressionNodeType]?: ExpressionNodeEvaluatorConstructor<C, ExpressionNode<ExpressionNodeType>>\n}\n\nconst defaultEvaluators = {\n [ExpressionNodeType.Array]: ArrayEvaluator,\n [ExpressionNodeType.Binary]: BinaryEvaluator,\n [ExpressionNodeType.Call]: CallEvaluator,\n [ExpressionNodeType.Compound]: CompoundEvaluator,\n [ExpressionNodeType.Conditional]: ConditionalEvaluator,\n [ExpressionNodeType.Identifier]: IdentifierEvaluator,\n [ExpressionNodeType.Literal]: LiteralEvaluator,\n [ExpressionNodeType.Member]: MemberEvaluator,\n [ExpressionNodeType.Sequence]: SequenceEvaluator,\n [ExpressionNodeType.This]: ThisEvaluator,\n [ExpressionNodeType.Unary]: UnaryEvaluator,\n}\n\n// Parsed expressions cache: the same expressions are evaluated many times (e.g. for every node during a record update).\n// The cached expression nodes are shared, so evaluators must never modify them.\nconst PARSED_EXPRESSIONS_CACHE_MAX_SIZE = 1000\nconst parsedExpressionsCache = new Map<string, ExpressionNode<ExpressionNodeType>>()\nconst expressionParser = new JavascriptExpressionParser()\n\nexport const parseExpression = (expression: string): ExpressionNode<ExpressionNodeType> => {\n let expressionNode = parsedExpressionsCache.get(expression)\n if (!expressionNode) {\n expressionNode = expressionParser.parse(expression)\n if (parsedExpressionsCache.size >= PARSED_EXPRESSIONS_CACHE_MAX_SIZE) {\n // evict the oldest entry (Map keeps insertion order)\n const oldestExpression = parsedExpressionsCache.keys().next().value\n if (oldestExpression !== undefined) parsedExpressionsCache.delete(oldestExpression)\n }\n parsedExpressionsCache.set(expression, expressionNode)\n }\n return expressionNode\n}\n\nexport class JavascriptExpressionEvaluator<C extends ExpressionContext> implements ExpressionEvaluator<C> {\n functions: ExpressionFunctions<C>\n evaluators: Evaluators<C>\n\n constructor(functions: ExpressionFunctions<C> = {}, evaluators: Evaluators<C> = {}) {\n this.evaluators = { ...defaultEvaluators, ...evaluators }\n this.functions = { ...functionsDefault, ...functions }\n }\n\n async evaluate(expression: string, context?: C): Promise<any> {\n return this.evaluateNode(parseExpression(expression), context ?? ({} as C))\n }\n\n async evaluateNode(expressionNode: ExpressionNode<ExpressionNodeType>, context: C): Promise<any> {\n const { type } = expressionNode\n\n const NodeEvaluator = this.evaluators[type]\n if (!NodeEvaluator) {\n throw new SystemError('expression.unsupportedFunctionType', { type })\n }\n return new NodeEvaluator(this, context).evaluate(expressionNode)\n }\n}\n"]}
|
package/dist/esm/job/JobBase.js
CHANGED
|
@@ -100,6 +100,7 @@ export class JobBase {
|
|
|
100
100
|
/**
|
|
101
101
|
* Registers the listener notified of job events (status changes and progress).
|
|
102
102
|
* Only one listener can be registered at a time; registering a new one replaces the previous one.
|
|
103
|
+
* Errors thrown (or rejections returned) by the listener are logged and do not affect the job execution.
|
|
103
104
|
*/
|
|
104
105
|
onEvent(listener) {
|
|
105
106
|
this.eventListener = listener;
|
|
@@ -191,7 +192,8 @@ export class JobBase {
|
|
|
191
192
|
}
|
|
192
193
|
}
|
|
193
194
|
catch (error) {
|
|
194
|
-
|
|
195
|
+
// a job can fail while still pending (e.g. the transaction cannot be opened, or onStart fails)
|
|
196
|
+
if (!this.cancelRequested && !this.isFailed() && !this.isCanceled()) {
|
|
195
197
|
this.logError((_a = error.stack) !== null && _a !== void 0 ? _a : error);
|
|
196
198
|
const { key, params } = this.getErrorInfo(error);
|
|
197
199
|
this.addError({ error: { valid: false, errors: [{ key, params }] } });
|
|
@@ -515,9 +517,25 @@ export class JobBase {
|
|
|
515
517
|
}
|
|
516
518
|
this.progressThrottleLastRunTime = 0;
|
|
517
519
|
}
|
|
520
|
+
/**
|
|
521
|
+
* Notifies the event to the registered listener.
|
|
522
|
+
* Listener errors are only logged: they would otherwise fail the job or, when thrown inside the progress
|
|
523
|
+
* throttle timeout, crash the process.
|
|
524
|
+
*/
|
|
518
525
|
notifyEvent(event) {
|
|
526
|
+
const listener = this.eventListener;
|
|
527
|
+
if (!listener)
|
|
528
|
+
return;
|
|
529
|
+
try {
|
|
530
|
+
Promise.resolve(listener(event)).catch((error) => this.logListenerError(error));
|
|
531
|
+
}
|
|
532
|
+
catch (error) {
|
|
533
|
+
this.logListenerError(error);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
logListenerError(error) {
|
|
519
537
|
var _a;
|
|
520
|
-
(_a =
|
|
538
|
+
this.logError(`error in job event listener: ${(_a = error === null || error === void 0 ? void 0 : error.stack) !== null && _a !== void 0 ? _a : error}`);
|
|
521
539
|
}
|
|
522
540
|
}
|
|
523
541
|
JobBase.keysContext = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JobBase.js","sourceRoot":"","sources":["../../../src/job/JobBase.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAEtC,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAA;AAIhC,OAAO,EAAY,YAAY,EAAE,MAAM,YAAY,CAAA;AAEnD,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AAOpC,MAAM,qCAAqC,GAAG,IAAI,CAAA;AAElD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,OAAgB,OAAO;IAiC3B,YAAmB,OAAU,EAAE,YAA+B,EAAE;;QAxBhE,WAAM,GAAc,SAAS,CAAC,OAAO,CAAA;QAIrC,WAAM,GAAkB,SAAS,CAAA;QACjC,WAAM,GAAwB,EAAE,CAAA;QAMtB,yBAAoB,GAAG,CAAC,CAAC,CAAA;QAE3B,eAAU,GAAG,CAAC,CAAA;QACd,kBAAa,GAA4C,SAAS,CAAA;QAClE,8BAAyB,GAA8C,SAAS,CAA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EAAE,IAAI,CAAC,KAAK;gBACjB,SAAS,EAAE,IAAI,CAAC,SAAS;aAC1B,CAAC,CAAA;QACJ,CAAC,CAAA;QAED,IAAI,IAAI,CAAC,yBAAyB;YAAE,OAAM;QAE1C,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,2BAA2B,CAAA;QAC7D,IAAI,CAAC,IAAI,CAAC,2BAA2B,IAAI,OAAO,IAAI,qCAAqC,EAAE,CAAC;YAC1F,GAAG,EAAE,CAAA;QACP,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,yBAAyB,GAAG,UAAU,CAAC,GAAG,EAAE,qCAAqC,GAAG,OAAO,CAAC,CAAA;QACnG,CAAC;IACH,CAAC;IAED;;OAEG;IACK,oBAAoB;QAC1B,IAAI,IAAI,CAAC,yBAAyB,EAAE,CAAC;YACnC,YAAY,CAAC,IAAI,CAAC,yBAAyB,CAAC,CAAA;YAC5C,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAA;QAC5C,CAAC;QACD,IAAI,CAAC,2BAA2B,GAAG,CAAC,CAAA;IACtC,CAAC;IAEO,WAAW,CAAC,KAAe;;QACjC,MAAA,IAAI,CAAC,aAAa,qDAAG,KAAK,CAAC,CAAA;IAC7B,CAAC;;AA5hBe,mBAAW,GAAG;IAC5B,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;IAChB,IAAI,EAAE,MAAM;CACb,AAJ0B,CAI1B","sourcesContent":["import { Dictionary } from '../common'\nimport { SystemError } from '../error'\nimport { Logger } from '../logger'\nimport { UUIDs } from '../utils'\n\nimport { Job } from './job'\nimport { JobContext } from './jobContext'\nimport { JobEvent, JobEventType } from './jobEvent'\nimport { JobSerialized } from './jobSerialized'\nimport { JobStatus } from './status'\n\nexport interface JobConstructor {\n new <C extends JobContext, R>(context: C, innerJobs?: JobBase<any>[]): JobBase<C, R>\n readonly prototype: JobBase<any, any>\n}\n\nconst PROGRESS_NOTIFICATION_THROTTLE_MILLIS = 1000\n\n/**\n * Asynchronous task handler.\n *\n * Status workflow:\n * - pending\n * - running\n * - (end)\n * -- succeeded\n * -- failed\n * -- canceled\n *\n * Methods that can be overwritten by subclasses:\n * - shouldExecute (in tx)\n * - onStart (in tx)\n * - execute (in tx)\n * - beforeSuccess (in tx)\n * - generateResult (in tx)\n * - beforeEnd (in tx)\n * - onEnd (out of tx)\n * - getErrorInfo\n */\nexport abstract class JobBase<C extends JobContext, R = undefined> implements Job<R> {\n static readonly keysContext = {\n surveyId: 'surveyId',\n survey: 'survey',\n user: 'user',\n }\n\n readonly uuid: string\n readonly type: string\n status: JobStatus = JobStatus.pending\n startTime?: Date\n endTime?: Date\n total: number\n result: R | undefined = undefined\n errors: Record<string, any> = {}\n canceledByAdmin?: boolean\n\n protected logger: Logger\n protected context: C\n protected innerJobs: JobBase<C, any>[]\n protected currentInnerJobIndex = -1\n\n private _processed = 0\n private eventListener: ((event: JobEvent) => void) | undefined = undefined\n private progressThrottleTimeoutId: ReturnType<typeof setTimeout> | undefined = undefined\n private progressThrottleLastRunTime = 0\n private _stopOnInnerJobFailure = true\n // set as soon as cancel() is called (the canceled status is set only after beforeEnd has run)\n private cancelRequested = false\n private beforeEndCalled = false\n // inner job events are handled in sequence; executeJobs waits for them before going on\n private innerJobEventsQueue: Promise<void> = Promise.resolve()\n\n public constructor(context: C, innerJobs: JobBase<C, any>[] = []) {\n this.context = { ...context }\n this.innerJobs = innerJobs\n\n this.uuid = UUIDs.v4()\n this.type = this.context.type ?? this.constructor.name\n this.total = innerJobs.length > 0 ? innerJobs.length : 1\n\n // Created last, so that createLogger() overrides can safely build the logger name out of\n // the job identity (e.g. arena's `Job <ClassName> (<uuid>)` log correlation id).\n this.logger = this.createLogger()\n }\n\n get processed(): number {\n return this._processed\n }\n\n set processed(value: number) {\n this._processed = value\n this.notifyProgress()\n }\n\n get stopOnInnerJobFailure(): boolean {\n return this._stopOnInnerJobFailure\n }\n\n set stopOnInnerJobFailure(value: boolean) {\n this._stopOnInnerJobFailure = value\n }\n\n protected get surveyId(): number | null {\n return this.getContextProp(JobBase.keysContext.surveyId)\n }\n\n protected get user(): any {\n return this.getContextProp(JobBase.keysContext.user)\n }\n\n protected get userUuid(): string | undefined {\n return this.user?.uuid\n }\n\n protected get contextSurvey(): any {\n return this.getContextProp(JobBase.keysContext.survey)\n }\n\n protected getContextProp<T = any>(prop: string, defaultValue: T | null = null): T | null {\n const value = (this.context as any)[prop]\n return value ?? defaultValue\n }\n\n protected setContext(context: Partial<C>): void {\n Object.assign(this.context, context)\n }\n\n protected deleteContextProps(...propNames: string[]): void {\n propNames.forEach((propName) => {\n delete (this.context as any)[propName]\n })\n }\n\n /**\n * Registers the listener notified of job events (status changes and progress).\n * Only one listener can be registered at a time; registering a new one replaces the previous one.\n */\n onEvent(listener: (event: JobEvent) => void): this {\n this.eventListener = listener\n return this\n }\n\n isPending(): boolean {\n return this.status === JobStatus.pending\n }\n\n isRunning(): boolean {\n return this.status === JobStatus.running\n }\n\n isSucceeded(): boolean {\n return this.status === JobStatus.succeeded\n }\n\n isFailed(): boolean {\n return this.status === JobStatus.failed\n }\n\n isCanceled(): boolean {\n return this.status === JobStatus.canceled\n }\n\n isEnded(): boolean {\n return [JobStatus.succeeded, JobStatus.failed, JobStatus.canceled].includes(this.status)\n }\n\n hasErrors(): boolean {\n return Object.keys(this.errors).length > 0\n }\n\n protected getCurrentInnerJob(): JobBase<C, any> | undefined {\n return this.innerJobs[this.currentInnerJobIndex]\n }\n\n protected combineInnerJobsResults(): Record<string, any> {\n const results: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(results, innerJob.result ?? {}))\n return results\n }\n\n protected combineInnerJobsErrors(): Record<string, any> {\n const errors: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(errors, innerJob.errors ?? {}))\n return errors\n }\n\n async cancel(options: { canceledByAdmin?: boolean } = {}): Promise<void> {\n const { canceledByAdmin = false } = options\n if (this.isEnded()) return\n\n this.cancelRequested = true\n\n const currentInnerJob = this.getCurrentInnerJob()\n if (currentInnerJob?.isRunning()) {\n // the parent job status will be set to canceled when handling the canceled event of the inner job\n await currentInnerJob.cancel({ canceledByAdmin })\n return\n }\n // no inner job running (job without inner jobs, or between two inner jobs)\n this.canceledByAdmin = canceledByAdmin\n // release the resources (temp files/directories, streams) allocated before the cancellation\n await this.runBeforeEnd()\n await this.setStatus(JobStatus.canceled)\n }\n\n private isCancelRequestedOrNotRunning(): boolean {\n return this.cancelRequested || !this.isRunning()\n }\n\n /**\n * Runs beforeEnd only once (it can be called by cancel() and when the job execution ends).\n */\n private async runBeforeEnd(): Promise<void> {\n if (this.beforeEndCalled) return\n this.beforeEndCalled = true\n await this.beforeEnd()\n }\n\n async start(client: any = null): Promise<void> {\n this.logDebug('start')\n\n try {\n if (client) {\n await client.tx(async (tx: any) => {\n this.context.tx = tx\n await this.executeInTransaction()\n })\n } else {\n await this.executeInTransaction()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.setStatus(JobStatus.succeeded)\n }\n } catch (error: any) {\n if (!this.cancelRequested && !this.isFailed() && (this.isRunning() || this.isSucceeded())) {\n this.logError(error.stack ?? error)\n const { key, params } = this.getErrorInfo(error)\n this.addError({ error: { valid: false, errors: [{ key, params }] } })\n await this.setStatus(JobStatus.failed)\n }\n } finally {\n this.context.tx = undefined\n }\n }\n\n private async executeInTransaction(): Promise<void> {\n try {\n await this.onStart()\n\n const shouldExecute = await this.shouldExecute()\n if (shouldExecute) {\n if (this.innerJobs.length > 0) {\n await this.executeJobs()\n } else {\n await this.execute()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.beforeSuccess()\n }\n }\n } finally {\n // runs only if not already run by cancel()\n await this.runBeforeEnd()\n this.context.tx = undefined\n }\n\n if (this.isCancelRequestedOrNotRunning()) {\n this.throwError('jobCanceledOrErrorsFound')\n }\n }\n\n /**\n * Generates a plain JSON-serializable representation of the job, including its inner jobs.\n */\n toJSON(): JobSerialized<R> {\n const { errors, processed, result, status, total, type, userUuid, uuid } = this\n\n return {\n uuid,\n type,\n userUuid,\n surveyId: this.surveyId,\n innerJobs: this.innerJobs.map((job) => job.toJSON()),\n currentInnerJobIndex: this.currentInnerJobIndex,\n\n status,\n pending: this.isPending(),\n running: this.isRunning(),\n succeeded: this.isSucceeded(),\n canceled: this.isCanceled(),\n failed: this.isFailed(),\n ended: this.isEnded(),\n\n total,\n processed,\n progressPercent: this.calculateProgressPercent(),\n elapsedMillis: this.calculateElapsedMillis(),\n\n errors: this.isFailed() ? errors : undefined,\n result: this.isSucceeded() ? result : undefined,\n }\n }\n\n private async executeJobs(): Promise<void> {\n this.logDebug(`- ${this.total} inner jobs found`)\n\n for (let i = 0; i < this.innerJobs.length; i++) {\n this.logDebug(`- executing inner job ${i + 1}`)\n this.currentInnerJobIndex = i\n const currentInnerJob = this.innerJobs[i]\n if (currentInnerJob.context) {\n Object.assign(this.context, currentInnerJob.context)\n }\n currentInnerJob.context = this.context\n currentInnerJob.onEvent((event) => {\n // handle the inner job events in sequence; errors are logged (they would be unhandled rejections otherwise)\n this.innerJobEventsQueue = this.innerJobEventsQueue\n .then(() => this.onInnerJobEvent(event))\n .catch((error) => this.logError(error?.stack ?? error))\n })\n\n // The inner job shares this very context object, and its own start()/executeInTransaction()\n // clear `context.tx` when they terminate: without saving and restoring it here, the first\n // inner job would wipe the parent's transaction handle, leaving every following inner job\n // (and the parent's own beforeSuccess()/beforeEnd()) running outside of the transaction.\n // start() never throws (it swallows/records errors internally), so a plain restore is enough.\n const parentTx = this.context.tx\n await currentInnerJob.start(parentTx)\n this.context.tx = parentTx\n // the inner job events (e.g. canceled, failed) update the status of this job\n await this.innerJobEventsQueue\n\n if (this.cancelRequested || this.isCanceled() || currentInnerJob.isCanceled()) {\n break\n }\n if (currentInnerJob.isSucceeded()) {\n this.incrementProcessedItems()\n } else if (this.stopOnInnerJobFailure) {\n break\n }\n }\n\n this.logDebug(`- ${this.processed} inner jobs processed successfully`)\n }\n\n /**\n * Runs the job's own work when it has no inner jobs. Default implementation is a no-op, so\n * subclasses that only supply inner jobs (and never override this) don't need to. It also means\n * a subclass can safely call `super.execute()` defensively without knowing whether any ancestor\n * overrides it - if this were `abstract` instead, TypeScript would compile away any runtime\n * property for it entirely, so `super.execute()` would throw the moment no ancestor overrides it\n * (confirmed in production: a subclass whose immediate parent didn't override `execute()` crashed\n * with \"(intermediate value).execute is not a function\" the instant it called `super.execute()`).\n */\n protected async execute(): Promise<void> {\n // to be extended by subclasses\n }\n\n /**\n * Determines whether the job should actually run.\n * When it returns false, \"execute\" (or the inner jobs) will be skipped, but the job will still succeed.\n */\n protected shouldExecute(): Promise<boolean> {\n return Promise.resolve(true)\n }\n\n protected incrementProcessedItems(incrementBy = 1): void {\n this.processed += incrementBy\n }\n\n protected async setStatus(status: JobStatus): Promise<void> {\n this.logDebug(`set status: ${status}`)\n this.status = status\n\n const event: JobEvent = { type: JobEventType.statusChange, status, total: this.total, processed: this.processed }\n if (status === JobStatus.failed) {\n event.errors = this.errors\n }\n\n if (this.isEnded()) {\n this.logDebug('onEnd...')\n await this.onEnd()\n this.logDebug(`onEnd run. Job completed in ${this.elapsedTimePrettyFormat}`)\n }\n\n this.notifyEvent(event)\n }\n\n /**\n * Inner job event handler.\n */\n protected async onInnerJobEvent(event: JobEvent): Promise<void> {\n const { status } = event\n if (status === JobStatus.canceled) {\n this.canceledByAdmin = this.getCurrentInnerJob()?.canceledByAdmin ?? false\n return this.setStatus(status)\n }\n if (status === JobStatus.failed) {\n // report the errors of the failed inner job in the failed event (and in the errors) of this job\n Object.assign(this.errors, this.getCurrentInnerJob()?.errors ?? {})\n return this.setStatus(status)\n }\n if (status === JobStatus.running) {\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n return\n }\n this.logDebug(`Unknown inner job status: ${status}`)\n }\n\n /**\n * Called when the job just has been started.\n */\n protected async onStart(): Promise<void> {\n this.startTime = new Date()\n await this.setStatus(JobStatus.running)\n }\n\n /**\n * Called before beforeEnd only if the status will change to 'success'.\n * Default implementation stores the value returned by generateResult() via setResult().\n * It runs INSIDE the current db transaction.\n */\n protected async beforeSuccess(): Promise<void> {\n this.setResult(await this.generateResult())\n }\n\n /**\n * Computes the value beforeSuccess() will store as this job's result.\n * Default implementation returns whatever is already in `this.result`\n * (e.g. accumulated via earlier setResult() calls during execute()).\n */\n protected generateResult(): Promise<R | undefined> {\n return Promise.resolve(this.result)\n }\n\n /**\n * Updates this job's result. When both the current and incoming values are plain objects,\n * they are merged (Object.assign); otherwise the incoming value replaces the current one.\n * This keeps it safe for subclasses whose result is a primitive (e.g. a plain number) as\n * well as ones that build an object result incrementally across multiple setResult() calls.\n */\n protected setResult(result: R | undefined): void {\n if (result && typeof result === 'object' && this.result && typeof this.result === 'object') {\n Object.assign(this.result, result)\n } else {\n this.result = result\n }\n }\n\n /**\n * Called before onEnd. Useful for flushing resources used by the job before it terminates completely.\n * It runs INSIDE the current db transaction.\n */\n protected beforeEnd(): Promise<void> {\n this.logDebug('Cleanup')\n return Promise.resolve()\n }\n\n /**\n * Called when the job status changes to success, failed or canceled\n * (it runs OUTSIDE of the current db transaction)\n */\n protected onEnd(): Promise<void> {\n this.endTime = new Date()\n this.cancelNotifyProgress()\n return Promise.resolve()\n }\n\n protected addError(error: any, errorKey?: string): void {\n const key = errorKey ?? String(this.processed + 1)\n this.errors[key] = error\n }\n\n protected throwError(errorKey: string, params?: Dictionary<any>): void {\n // SystemError: getErrorInfo will report the translatable key instead of a generic error\n throw new SystemError(errorKey, params)\n }\n\n protected getErrorInfo(error: any): { key: string; params: Record<string, any> } {\n if (error instanceof SystemError) {\n return { key: `appErrors:${error.key}`, params: error.params }\n }\n return { key: 'appErrors:generic', params: { text: error.toString() } }\n }\n\n protected abstract createLogger(): Logger\n\n protected logDebug(...msgs: any[]): void {\n this.logger.debug(...msgs)\n }\n\n protected logInfo(...msgs: any[]): void {\n this.logger.info(...msgs)\n }\n\n protected logWarn(...msgs: any[]): void {\n this.logger.warn(...msgs)\n }\n\n protected logError(...msgs: any[]): void {\n this.logger.error(...msgs)\n }\n\n private get elapsedTimePrettyFormat(): string {\n const elapsedTime = this.calculateElapsedMillis()\n const elapsedMins = Math.floor(elapsedTime / 1000 / 60)\n const elapsedSeconds = String(Math.floor(elapsedTime / 1000) % 60).padStart(2, '0')\n const elapsedMillis = String(elapsedTime % 1000).padStart(3, '0')\n return `${elapsedMins}:${elapsedSeconds}.${elapsedMillis}`\n }\n\n private calculatePartialProgress(): number {\n if (this.isSucceeded()) return 100\n if (this.total > 0) return Math.floor((100 * this.processed) / this.total)\n return 0\n }\n\n private calculateProgressPercent(): number {\n const partialProgress = this.calculatePartialProgress()\n const currentInnerJob = this.getCurrentInnerJob()\n if (\n !currentInnerJob ||\n this.currentInnerJobIndex < 0 ||\n partialProgress === 100 ||\n this.processed > this.currentInnerJobIndex\n ) {\n return partialProgress\n }\n return partialProgress + Math.floor(currentInnerJob.calculateProgressPercent() / this.total)\n }\n\n private calculateElapsedMillis(): number {\n if (!this.startTime) return 0\n return (this.endTime ?? new Date()).getTime() - this.startTime.getTime()\n }\n\n /**\n * Notifies a progress event to the registered listener, throttled so that fast-changing\n * progress does not flood consumers (e.g. web socket clients).\n */\n private notifyProgress(): void {\n const run = (): void => {\n this.progressThrottleTimeoutId = undefined\n this.progressThrottleLastRunTime = Date.now()\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n }\n\n if (this.progressThrottleTimeoutId) return\n\n const elapsed = Date.now() - this.progressThrottleLastRunTime\n if (!this.progressThrottleLastRunTime || elapsed >= PROGRESS_NOTIFICATION_THROTTLE_MILLIS) {\n run()\n } else {\n this.progressThrottleTimeoutId = setTimeout(run, PROGRESS_NOTIFICATION_THROTTLE_MILLIS - elapsed)\n }\n }\n\n /**\n * Cancels any pending throttled progress notification and resets the throttle state.\n */\n private cancelNotifyProgress(): void {\n if (this.progressThrottleTimeoutId) {\n clearTimeout(this.progressThrottleTimeoutId)\n this.progressThrottleTimeoutId = undefined\n }\n this.progressThrottleLastRunTime = 0\n }\n\n private notifyEvent(event: JobEvent): void {\n this.eventListener?.(event)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"JobBase.js","sourceRoot":"","sources":["../../../src/job/JobBase.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AAEtC,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAA;AAIhC,OAAO,EAAY,YAAY,EAAE,MAAM,YAAY,CAAA;AAEnD,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AAOpC,MAAM,qCAAqC,GAAG,IAAI,CAAA;AAElD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,OAAgB,OAAO;IAiC3B,YAAmB,OAAU,EAAE,YAA+B,EAAE;;QAxBhE,WAAM,GAAc,SAAS,CAAC,OAAO,CAAA;QAIrC,WAAM,GAAkB,SAAS,CAAA;QACjC,WAAM,GAAwB,EAAE,CAAA;QAMtB,yBAAoB,GAAG,CAAC,CAAC,CAAA;QAE3B,eAAU,GAAG,CAAC,CAAA;QACd,kBAAa,GAA+C,SAAS,CAAA;QACrE,8BAAyB,GAA8C,SAAS,CAAA;QAChF,gCAA2B,GAAG,CAAC,CAAA;QAC/B,2BAAsB,GAAG,IAAI,CAAA;QACrC,8FAA8F;QACtF,oBAAe,GAAG,KAAK,CAAA;QACvB,oBAAe,GAAG,KAAK,CAAA;QAC/B,uFAAuF;QAC/E,wBAAmB,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAA;QAG5D,IAAI,CAAC,OAAO,qBAAQ,OAAO,CAAE,CAAA;QAC7B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAA;QAE1B,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,EAAE,EAAE,CAAA;QACtB,IAAI,CAAC,IAAI,GAAG,MAAA,IAAI,CAAC,OAAO,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,CAAC;IACH,CAAC;IAED;;OAEG;IACK,oBAAoB;QAC1B,IAAI,IAAI,CAAC,yBAAyB,EAAE,CAAC;YACnC,YAAY,CAAC,IAAI,CAAC,yBAAyB,CAAC,CAAA;YAC5C,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAA;QAC5C,CAAC;QACD,IAAI,CAAC,2BAA2B,GAAG,CAAC,CAAA;IACtC,CAAC;IAED;;;;OAIG;IACK,WAAW,CAAC,KAAe;QACjC,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAA;QACnC,IAAI,CAAC,QAAQ;YAAE,OAAM;QACrB,IAAI,CAAC;YACH,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAA;QACjF,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAA;QAC9B,CAAC;IACH,CAAC;IAEO,gBAAgB,CAAC,KAAU;;QACjC,IAAI,CAAC,QAAQ,CAAC,gCAAgC,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,KAAK,mCAAI,KAAK,EAAE,CAAC,CAAA;IACxE,CAAC;;AA7iBe,mBAAW,GAAG;IAC5B,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;IAChB,IAAI,EAAE,MAAM;CACb,AAJ0B,CAI1B","sourcesContent":["import { Dictionary } from '../common'\nimport { SystemError } from '../error'\nimport { Logger } from '../logger'\nimport { UUIDs } from '../utils'\n\nimport { Job } from './job'\nimport { JobContext } from './jobContext'\nimport { JobEvent, JobEventType } from './jobEvent'\nimport { JobSerialized } from './jobSerialized'\nimport { JobStatus } from './status'\n\nexport interface JobConstructor {\n new <C extends JobContext, R>(context: C, innerJobs?: JobBase<any>[]): JobBase<C, R>\n readonly prototype: JobBase<any, any>\n}\n\nconst PROGRESS_NOTIFICATION_THROTTLE_MILLIS = 1000\n\n/**\n * Asynchronous task handler.\n *\n * Status workflow:\n * - pending\n * - running\n * - (end)\n * -- succeeded\n * -- failed\n * -- canceled\n *\n * Methods that can be overwritten by subclasses:\n * - shouldExecute (in tx)\n * - onStart (in tx)\n * - execute (in tx)\n * - beforeSuccess (in tx)\n * - generateResult (in tx)\n * - beforeEnd (in tx)\n * - onEnd (out of tx)\n * - getErrorInfo\n */\nexport abstract class JobBase<C extends JobContext, R = undefined> implements Job<R> {\n static readonly keysContext = {\n surveyId: 'surveyId',\n survey: 'survey',\n user: 'user',\n }\n\n readonly uuid: string\n readonly type: string\n status: JobStatus = JobStatus.pending\n startTime?: Date\n endTime?: Date\n total: number\n result: R | undefined = undefined\n errors: Record<string, any> = {}\n canceledByAdmin?: boolean\n\n protected logger: Logger\n protected context: C\n protected innerJobs: JobBase<C, any>[]\n protected currentInnerJobIndex = -1\n\n private _processed = 0\n private eventListener: ((event: JobEvent) => unknown) | undefined = undefined\n private progressThrottleTimeoutId: ReturnType<typeof setTimeout> | undefined = undefined\n private progressThrottleLastRunTime = 0\n private _stopOnInnerJobFailure = true\n // set as soon as cancel() is called (the canceled status is set only after beforeEnd has run)\n private cancelRequested = false\n private beforeEndCalled = false\n // inner job events are handled in sequence; executeJobs waits for them before going on\n private innerJobEventsQueue: Promise<void> = Promise.resolve()\n\n public constructor(context: C, innerJobs: JobBase<C, any>[] = []) {\n this.context = { ...context }\n this.innerJobs = innerJobs\n\n this.uuid = UUIDs.v4()\n this.type = this.context.type ?? this.constructor.name\n this.total = innerJobs.length > 0 ? innerJobs.length : 1\n\n // Created last, so that createLogger() overrides can safely build the logger name out of\n // the job identity (e.g. arena's `Job <ClassName> (<uuid>)` log correlation id).\n this.logger = this.createLogger()\n }\n\n get processed(): number {\n return this._processed\n }\n\n set processed(value: number) {\n this._processed = value\n this.notifyProgress()\n }\n\n get stopOnInnerJobFailure(): boolean {\n return this._stopOnInnerJobFailure\n }\n\n set stopOnInnerJobFailure(value: boolean) {\n this._stopOnInnerJobFailure = value\n }\n\n protected get surveyId(): number | null {\n return this.getContextProp(JobBase.keysContext.surveyId)\n }\n\n protected get user(): any {\n return this.getContextProp(JobBase.keysContext.user)\n }\n\n protected get userUuid(): string | undefined {\n return this.user?.uuid\n }\n\n protected get contextSurvey(): any {\n return this.getContextProp(JobBase.keysContext.survey)\n }\n\n protected getContextProp<T = any>(prop: string, defaultValue: T | null = null): T | null {\n const value = (this.context as any)[prop]\n return value ?? defaultValue\n }\n\n protected setContext(context: Partial<C>): void {\n Object.assign(this.context, context)\n }\n\n protected deleteContextProps(...propNames: string[]): void {\n propNames.forEach((propName) => {\n delete (this.context as any)[propName]\n })\n }\n\n /**\n * Registers the listener notified of job events (status changes and progress).\n * Only one listener can be registered at a time; registering a new one replaces the previous one.\n * Errors thrown (or rejections returned) by the listener are logged and do not affect the job execution.\n */\n onEvent(listener: (event: JobEvent) => unknown): this {\n this.eventListener = listener\n return this\n }\n\n isPending(): boolean {\n return this.status === JobStatus.pending\n }\n\n isRunning(): boolean {\n return this.status === JobStatus.running\n }\n\n isSucceeded(): boolean {\n return this.status === JobStatus.succeeded\n }\n\n isFailed(): boolean {\n return this.status === JobStatus.failed\n }\n\n isCanceled(): boolean {\n return this.status === JobStatus.canceled\n }\n\n isEnded(): boolean {\n return [JobStatus.succeeded, JobStatus.failed, JobStatus.canceled].includes(this.status)\n }\n\n hasErrors(): boolean {\n return Object.keys(this.errors).length > 0\n }\n\n protected getCurrentInnerJob(): JobBase<C, any> | undefined {\n return this.innerJobs[this.currentInnerJobIndex]\n }\n\n protected combineInnerJobsResults(): Record<string, any> {\n const results: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(results, innerJob.result ?? {}))\n return results\n }\n\n protected combineInnerJobsErrors(): Record<string, any> {\n const errors: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(errors, innerJob.errors ?? {}))\n return errors\n }\n\n async cancel(options: { canceledByAdmin?: boolean } = {}): Promise<void> {\n const { canceledByAdmin = false } = options\n if (this.isEnded()) return\n\n this.cancelRequested = true\n\n const currentInnerJob = this.getCurrentInnerJob()\n if (currentInnerJob?.isRunning()) {\n // the parent job status will be set to canceled when handling the canceled event of the inner job\n await currentInnerJob.cancel({ canceledByAdmin })\n return\n }\n // no inner job running (job without inner jobs, or between two inner jobs)\n this.canceledByAdmin = canceledByAdmin\n // release the resources (temp files/directories, streams) allocated before the cancellation\n await this.runBeforeEnd()\n await this.setStatus(JobStatus.canceled)\n }\n\n private isCancelRequestedOrNotRunning(): boolean {\n return this.cancelRequested || !this.isRunning()\n }\n\n /**\n * Runs beforeEnd only once (it can be called by cancel() and when the job execution ends).\n */\n private async runBeforeEnd(): Promise<void> {\n if (this.beforeEndCalled) return\n this.beforeEndCalled = true\n await this.beforeEnd()\n }\n\n async start(client: any = null): Promise<void> {\n this.logDebug('start')\n\n try {\n if (client) {\n await client.tx(async (tx: any) => {\n this.context.tx = tx\n await this.executeInTransaction()\n })\n } else {\n await this.executeInTransaction()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.setStatus(JobStatus.succeeded)\n }\n } catch (error: any) {\n // a job can fail while still pending (e.g. the transaction cannot be opened, or onStart fails)\n if (!this.cancelRequested && !this.isFailed() && !this.isCanceled()) {\n this.logError(error.stack ?? error)\n const { key, params } = this.getErrorInfo(error)\n this.addError({ error: { valid: false, errors: [{ key, params }] } })\n await this.setStatus(JobStatus.failed)\n }\n } finally {\n this.context.tx = undefined\n }\n }\n\n private async executeInTransaction(): Promise<void> {\n try {\n await this.onStart()\n\n const shouldExecute = await this.shouldExecute()\n if (shouldExecute) {\n if (this.innerJobs.length > 0) {\n await this.executeJobs()\n } else {\n await this.execute()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.beforeSuccess()\n }\n }\n } finally {\n // runs only if not already run by cancel()\n await this.runBeforeEnd()\n this.context.tx = undefined\n }\n\n if (this.isCancelRequestedOrNotRunning()) {\n this.throwError('jobCanceledOrErrorsFound')\n }\n }\n\n /**\n * Generates a plain JSON-serializable representation of the job, including its inner jobs.\n */\n toJSON(): JobSerialized<R> {\n const { errors, processed, result, status, total, type, userUuid, uuid } = this\n\n return {\n uuid,\n type,\n userUuid,\n surveyId: this.surveyId,\n innerJobs: this.innerJobs.map((job) => job.toJSON()),\n currentInnerJobIndex: this.currentInnerJobIndex,\n\n status,\n pending: this.isPending(),\n running: this.isRunning(),\n succeeded: this.isSucceeded(),\n canceled: this.isCanceled(),\n failed: this.isFailed(),\n ended: this.isEnded(),\n\n total,\n processed,\n progressPercent: this.calculateProgressPercent(),\n elapsedMillis: this.calculateElapsedMillis(),\n\n errors: this.isFailed() ? errors : undefined,\n result: this.isSucceeded() ? result : undefined,\n }\n }\n\n private async executeJobs(): Promise<void> {\n this.logDebug(`- ${this.total} inner jobs found`)\n\n for (let i = 0; i < this.innerJobs.length; i++) {\n this.logDebug(`- executing inner job ${i + 1}`)\n this.currentInnerJobIndex = i\n const currentInnerJob = this.innerJobs[i]\n if (currentInnerJob.context) {\n Object.assign(this.context, currentInnerJob.context)\n }\n currentInnerJob.context = this.context\n currentInnerJob.onEvent((event) => {\n // handle the inner job events in sequence; errors are logged (they would be unhandled rejections otherwise)\n this.innerJobEventsQueue = this.innerJobEventsQueue\n .then(() => this.onInnerJobEvent(event))\n .catch((error) => this.logError(error?.stack ?? error))\n })\n\n // The inner job shares this very context object, and its own start()/executeInTransaction()\n // clear `context.tx` when they terminate: without saving and restoring it here, the first\n // inner job would wipe the parent's transaction handle, leaving every following inner job\n // (and the parent's own beforeSuccess()/beforeEnd()) running outside of the transaction.\n // start() never throws (it swallows/records errors internally), so a plain restore is enough.\n const parentTx = this.context.tx\n await currentInnerJob.start(parentTx)\n this.context.tx = parentTx\n // the inner job events (e.g. canceled, failed) update the status of this job\n await this.innerJobEventsQueue\n\n if (this.cancelRequested || this.isCanceled() || currentInnerJob.isCanceled()) {\n break\n }\n if (currentInnerJob.isSucceeded()) {\n this.incrementProcessedItems()\n } else if (this.stopOnInnerJobFailure) {\n break\n }\n }\n\n this.logDebug(`- ${this.processed} inner jobs processed successfully`)\n }\n\n /**\n * Runs the job's own work when it has no inner jobs. Default implementation is a no-op, so\n * subclasses that only supply inner jobs (and never override this) don't need to. It also means\n * a subclass can safely call `super.execute()` defensively without knowing whether any ancestor\n * overrides it - if this were `abstract` instead, TypeScript would compile away any runtime\n * property for it entirely, so `super.execute()` would throw the moment no ancestor overrides it\n * (confirmed in production: a subclass whose immediate parent didn't override `execute()` crashed\n * with \"(intermediate value).execute is not a function\" the instant it called `super.execute()`).\n */\n protected async execute(): Promise<void> {\n // to be extended by subclasses\n }\n\n /**\n * Determines whether the job should actually run.\n * When it returns false, \"execute\" (or the inner jobs) will be skipped, but the job will still succeed.\n */\n protected shouldExecute(): Promise<boolean> {\n return Promise.resolve(true)\n }\n\n protected incrementProcessedItems(incrementBy = 1): void {\n this.processed += incrementBy\n }\n\n protected async setStatus(status: JobStatus): Promise<void> {\n this.logDebug(`set status: ${status}`)\n this.status = status\n\n const event: JobEvent = { type: JobEventType.statusChange, status, total: this.total, processed: this.processed }\n if (status === JobStatus.failed) {\n event.errors = this.errors\n }\n\n if (this.isEnded()) {\n this.logDebug('onEnd...')\n await this.onEnd()\n this.logDebug(`onEnd run. Job completed in ${this.elapsedTimePrettyFormat}`)\n }\n\n this.notifyEvent(event)\n }\n\n /**\n * Inner job event handler.\n */\n protected async onInnerJobEvent(event: JobEvent): Promise<void> {\n const { status } = event\n if (status === JobStatus.canceled) {\n this.canceledByAdmin = this.getCurrentInnerJob()?.canceledByAdmin ?? false\n return this.setStatus(status)\n }\n if (status === JobStatus.failed) {\n // report the errors of the failed inner job in the failed event (and in the errors) of this job\n Object.assign(this.errors, this.getCurrentInnerJob()?.errors ?? {})\n return this.setStatus(status)\n }\n if (status === JobStatus.running) {\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n return\n }\n this.logDebug(`Unknown inner job status: ${status}`)\n }\n\n /**\n * Called when the job just has been started.\n */\n protected async onStart(): Promise<void> {\n this.startTime = new Date()\n await this.setStatus(JobStatus.running)\n }\n\n /**\n * Called before beforeEnd only if the status will change to 'success'.\n * Default implementation stores the value returned by generateResult() via setResult().\n * It runs INSIDE the current db transaction.\n */\n protected async beforeSuccess(): Promise<void> {\n this.setResult(await this.generateResult())\n }\n\n /**\n * Computes the value beforeSuccess() will store as this job's result.\n * Default implementation returns whatever is already in `this.result`\n * (e.g. accumulated via earlier setResult() calls during execute()).\n */\n protected generateResult(): Promise<R | undefined> {\n return Promise.resolve(this.result)\n }\n\n /**\n * Updates this job's result. When both the current and incoming values are plain objects,\n * they are merged (Object.assign); otherwise the incoming value replaces the current one.\n * This keeps it safe for subclasses whose result is a primitive (e.g. a plain number) as\n * well as ones that build an object result incrementally across multiple setResult() calls.\n */\n protected setResult(result: R | undefined): void {\n if (result && typeof result === 'object' && this.result && typeof this.result === 'object') {\n Object.assign(this.result, result)\n } else {\n this.result = result\n }\n }\n\n /**\n * Called before onEnd. Useful for flushing resources used by the job before it terminates completely.\n * It runs INSIDE the current db transaction.\n */\n protected beforeEnd(): Promise<void> {\n this.logDebug('Cleanup')\n return Promise.resolve()\n }\n\n /**\n * Called when the job status changes to success, failed or canceled\n * (it runs OUTSIDE of the current db transaction)\n */\n protected onEnd(): Promise<void> {\n this.endTime = new Date()\n this.cancelNotifyProgress()\n return Promise.resolve()\n }\n\n protected addError(error: any, errorKey?: string): void {\n const key = errorKey ?? String(this.processed + 1)\n this.errors[key] = error\n }\n\n protected throwError(errorKey: string, params?: Dictionary<any>): void {\n // SystemError: getErrorInfo will report the translatable key instead of a generic error\n throw new SystemError(errorKey, params)\n }\n\n protected getErrorInfo(error: any): { key: string; params: Record<string, any> } {\n if (error instanceof SystemError) {\n return { key: `appErrors:${error.key}`, params: error.params }\n }\n return { key: 'appErrors:generic', params: { text: error.toString() } }\n }\n\n protected abstract createLogger(): Logger\n\n protected logDebug(...msgs: any[]): void {\n this.logger.debug(...msgs)\n }\n\n protected logInfo(...msgs: any[]): void {\n this.logger.info(...msgs)\n }\n\n protected logWarn(...msgs: any[]): void {\n this.logger.warn(...msgs)\n }\n\n protected logError(...msgs: any[]): void {\n this.logger.error(...msgs)\n }\n\n private get elapsedTimePrettyFormat(): string {\n const elapsedTime = this.calculateElapsedMillis()\n const elapsedMins = Math.floor(elapsedTime / 1000 / 60)\n const elapsedSeconds = String(Math.floor(elapsedTime / 1000) % 60).padStart(2, '0')\n const elapsedMillis = String(elapsedTime % 1000).padStart(3, '0')\n return `${elapsedMins}:${elapsedSeconds}.${elapsedMillis}`\n }\n\n private calculatePartialProgress(): number {\n if (this.isSucceeded()) return 100\n if (this.total > 0) return Math.floor((100 * this.processed) / this.total)\n return 0\n }\n\n private calculateProgressPercent(): number {\n const partialProgress = this.calculatePartialProgress()\n const currentInnerJob = this.getCurrentInnerJob()\n if (\n !currentInnerJob ||\n this.currentInnerJobIndex < 0 ||\n partialProgress === 100 ||\n this.processed > this.currentInnerJobIndex\n ) {\n return partialProgress\n }\n return partialProgress + Math.floor(currentInnerJob.calculateProgressPercent() / this.total)\n }\n\n private calculateElapsedMillis(): number {\n if (!this.startTime) return 0\n return (this.endTime ?? new Date()).getTime() - this.startTime.getTime()\n }\n\n /**\n * Notifies a progress event to the registered listener, throttled so that fast-changing\n * progress does not flood consumers (e.g. web socket clients).\n */\n private notifyProgress(): void {\n const run = (): void => {\n this.progressThrottleTimeoutId = undefined\n this.progressThrottleLastRunTime = Date.now()\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n }\n\n if (this.progressThrottleTimeoutId) return\n\n const elapsed = Date.now() - this.progressThrottleLastRunTime\n if (!this.progressThrottleLastRunTime || elapsed >= PROGRESS_NOTIFICATION_THROTTLE_MILLIS) {\n run()\n } else {\n this.progressThrottleTimeoutId = setTimeout(run, PROGRESS_NOTIFICATION_THROTTLE_MILLIS - elapsed)\n }\n }\n\n /**\n * Cancels any pending throttled progress notification and resets the throttle state.\n */\n private cancelNotifyProgress(): void {\n if (this.progressThrottleTimeoutId) {\n clearTimeout(this.progressThrottleTimeoutId)\n this.progressThrottleTimeoutId = undefined\n }\n this.progressThrottleLastRunTime = 0\n }\n\n /**\n * Notifies the event to the registered listener.\n * Listener errors are only logged: they would otherwise fail the job or, when thrown inside the progress\n * throttle timeout, crash the process.\n */\n private notifyEvent(event: JobEvent): void {\n const listener = this.eventListener\n if (!listener) return\n try {\n Promise.resolve(listener(event)).catch((error) => this.logListenerError(error))\n } catch (error) {\n this.logListenerError(error)\n }\n }\n\n private logListenerError(error: any): void {\n this.logError(`error in job event listener: ${error?.stack ?? error}`)\n }\n}\n"]}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { ExpressionNodeType } from '../../expression';
|
|
2
|
+
import { parseExpression } from '../../expression/javascript/evaluator';
|
|
3
|
+
import { NodeDefs } from '../../nodeDef';
|
|
4
|
+
import { SurveyDependencyType } from '../../survey/survey';
|
|
5
|
+
/**
|
|
6
|
+
* True if the identifier is used as (or inside) the property of a member expression (e.g. "dbh" in
|
|
7
|
+
* "parent(tree).tree.dbh" or in "tree[dbh > 10]"): there it can refer to nodes outside the context entity.
|
|
8
|
+
*/
|
|
9
|
+
const isReferencedThroughMember = (params) => {
|
|
10
|
+
const { expressionNode, name, inMemberProperty } = params;
|
|
11
|
+
if (!expressionNode || typeof expressionNode !== 'object')
|
|
12
|
+
return false;
|
|
13
|
+
if (Array.isArray(expressionNode)) {
|
|
14
|
+
return expressionNode.some((item) => isReferencedThroughMember({ expressionNode: item, name, inMemberProperty }));
|
|
15
|
+
}
|
|
16
|
+
const { type } = expressionNode;
|
|
17
|
+
if (type === ExpressionNodeType.Identifier) {
|
|
18
|
+
return inMemberProperty && expressionNode.name === name;
|
|
19
|
+
}
|
|
20
|
+
if (type === ExpressionNodeType.Member) {
|
|
21
|
+
const { object, property } = expressionNode;
|
|
22
|
+
return (isReferencedThroughMember({ expressionNode: object, name, inMemberProperty }) ||
|
|
23
|
+
isReferencedThroughMember({ expressionNode: property, name, inMemberProperty: true }));
|
|
24
|
+
}
|
|
25
|
+
return Object.values(expressionNode).some((child) => isReferencedThroughMember({ expressionNode: child, name, inMemberProperty }));
|
|
26
|
+
};
|
|
27
|
+
const isExpressionSelfReferenceLocal = (params) => {
|
|
28
|
+
const { expression, name } = params;
|
|
29
|
+
if (!expression)
|
|
30
|
+
return true;
|
|
31
|
+
try {
|
|
32
|
+
return !isReferencedThroughMember({ expressionNode: parseExpression(expression), name, inMemberProperty: false });
|
|
33
|
+
}
|
|
34
|
+
catch (_a) {
|
|
35
|
+
// invalid expression: be conservative
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Returns true if the node def references itself in its expressions of the specified dependency type only
|
|
41
|
+
* as a plain identifier (e.g. "dbh > 0" in a validation of "dbh"): such a reference is resolved among the
|
|
42
|
+
* children of the node's parent entity, so only the node and its siblings depend on it, not every node with
|
|
43
|
+
* the same node def in the record.
|
|
44
|
+
*/
|
|
45
|
+
const isSelfReferenceLocal = (params) => {
|
|
46
|
+
const { nodeDef, dependencyType } = params;
|
|
47
|
+
// self references by plain identifier are allowed only in validation expressions (see dependencies.ts)
|
|
48
|
+
if (dependencyType !== SurveyDependencyType.validations)
|
|
49
|
+
return false;
|
|
50
|
+
const name = NodeDefs.getName(nodeDef);
|
|
51
|
+
return NodeDefs.getValidationsExpressions(nodeDef).every(({ expression, applyIf }) => isExpressionSelfReferenceLocal({ expression, name }) &&
|
|
52
|
+
isExpressionSelfReferenceLocal({ expression: applyIf, name }));
|
|
53
|
+
};
|
|
54
|
+
export const NodeDefSelfReferences = {
|
|
55
|
+
isSelfReferenceLocal,
|
|
56
|
+
};
|
|
57
|
+
//# sourceMappingURL=nodeDefSelfReferences.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version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AAoB;CACrB,CAAA","sourcesContent":["import { ExpressionNode, ExpressionNodeType, IdentifierExpression, MemberExpression } from '../../expression'\nimport { parseExpression } from '../../expression/javascript/evaluator'\nimport { NodeDef, NodeDefProps, NodeDefs, NodeDefType } from '../../nodeDef'\nimport { SurveyDependencyType } from '../../survey/survey'\n\n/**\n * True if the identifier is used as (or inside) the property of a member expression (e.g. \"dbh\" in\n * \"parent(tree).tree.dbh\" or in \"tree[dbh > 10]\"): there it can refer to nodes outside the context entity.\n */\nconst isReferencedThroughMember = (params: {\n expressionNode: unknown\n name: string\n inMemberProperty: boolean\n}): boolean => {\n const { expressionNode, name, inMemberProperty } = params\n if (!expressionNode || typeof expressionNode !== 'object') return false\n if (Array.isArray(expressionNode)) {\n return expressionNode.some((item) => isReferencedThroughMember({ expressionNode: item, name, inMemberProperty }))\n }\n const { type } = expressionNode as ExpressionNode<ExpressionNodeType>\n if (type === ExpressionNodeType.Identifier) {\n return inMemberProperty && (expressionNode as IdentifierExpression).name === name\n }\n if (type === ExpressionNodeType.Member) {\n const { object, property } = expressionNode as MemberExpression\n return (\n isReferencedThroughMember({ expressionNode: object, name, inMemberProperty }) ||\n isReferencedThroughMember({ expressionNode: property, name, inMemberProperty: true })\n )\n }\n return Object.values(expressionNode).some((child) =>\n isReferencedThroughMember({ expressionNode: child, name, inMemberProperty })\n )\n}\n\nconst isExpressionSelfReferenceLocal = (params: { expression: string | undefined; name: string }): boolean => {\n const { expression, name } = params\n if (!expression) return true\n try {\n return !isReferencedThroughMember({ expressionNode: parseExpression(expression), name, inMemberProperty: false })\n } catch {\n // invalid expression: be conservative\n return false\n }\n}\n\n/**\n * Returns true if the node def references itself in its expressions of the specified dependency type only\n * as a plain identifier (e.g. \"dbh > 0\" in a validation of \"dbh\"): such a reference is resolved among the\n * children of the node's parent entity, so only the node and its siblings depend on it, not every node with\n * the same node def in the record.\n */\nconst isSelfReferenceLocal = (params: {\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n dependencyType: SurveyDependencyType\n}): boolean => {\n const { nodeDef, dependencyType } = params\n // self references by plain identifier are allowed only in validation expressions (see dependencies.ts)\n if (dependencyType !== SurveyDependencyType.validations) return false\n const name = NodeDefs.getName(nodeDef)\n return NodeDefs.getValidationsExpressions(nodeDef).every(\n ({ expression, applyIf }) =>\n isExpressionSelfReferenceLocal({ expression, name }) &&\n isExpressionSelfReferenceLocal({ expression: applyIf, name })\n )\n}\n\nexport const NodeDefSelfReferences = {\n isSelfReferenceLocal,\n}\n"]}
|
|
@@ -8,6 +8,7 @@ import { Arrays, Queue } from '../../utils';
|
|
|
8
8
|
import { RECORD_STEP_DEFAULT } from '../record';
|
|
9
9
|
import { RecordStepAnalysisCode } from '../recordStep';
|
|
10
10
|
import { RecordNodesIndexReader } from './recordNodesIndexReader';
|
|
11
|
+
import { NodeDefSelfReferences } from './nodeDefSelfReferences';
|
|
11
12
|
export const getCycle = (record) => { var _a; return (_a = record.cycle) !== null && _a !== void 0 ? _a : defaultCycle; };
|
|
12
13
|
export const getNodes = (record) => { var _a; return (_a = record.nodes) !== null && _a !== void 0 ? _a : {}; };
|
|
13
14
|
export const getNodesArray = (record) => Object.values(getNodes(record));
|
|
@@ -203,12 +204,15 @@ export const findDescendantOrSelf = (node, predicate) => (record) => {
|
|
|
203
204
|
return found;
|
|
204
205
|
};
|
|
205
206
|
const getClosestAncestorNode = (params) => {
|
|
206
|
-
const { record, node, nodeDef, dependentDef } = params;
|
|
207
|
+
const { record, node, nodeDef, dependentDef, dependencyType } = params;
|
|
207
208
|
// 1a if dependent def is the same as node def, potentially all nodes with
|
|
208
209
|
// nodeDefUuid === dependentDef.uuid in record could be dependent of nodeDef;
|
|
209
|
-
// consider the root node as the closest ancestor node
|
|
210
|
+
// consider the root node as the closest ancestor node,
|
|
211
|
+
// unless the node def references itself only among the children of its parent entity (e.g. validation "dbh > 0")
|
|
210
212
|
if (nodeDef.uuid === dependentDef.uuid) {
|
|
211
|
-
return
|
|
213
|
+
return NodeDefSelfReferences.isSelfReferenceLocal({ nodeDef, dependencyType })
|
|
214
|
+
? getParent(node)(record)
|
|
215
|
+
: getRoot(record);
|
|
212
216
|
}
|
|
213
217
|
// 1 find common ancestor def
|
|
214
218
|
const commonAncestorDefUuid = Arrays.last(Arrays.intersection(nodeDef.meta.h, dependentDef.meta.h));
|
|
@@ -337,7 +341,7 @@ export const getDependentNodePointers = (params) => {
|
|
|
337
341
|
};
|
|
338
342
|
for (const dependentDef of dependentDefs) {
|
|
339
343
|
// 1 find common ancestor node
|
|
340
|
-
const commonAncestorNode = getClosestAncestorNode({ record, node, nodeDef, dependentDef });
|
|
344
|
+
const commonAncestorNode = getClosestAncestorNode({ record, node, nodeDef, dependentDef, dependencyType });
|
|
341
345
|
if (!commonAncestorNode)
|
|
342
346
|
continue;
|
|
343
347
|
const nodeDefDependentParent = Surveys.getNodeDefParent({ survey, nodeDef: dependentDef });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recordGetters.js","sourceRoot":"","sources":["../../../../src/record/_records/recordGetters.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,cAAc,EAAE,MAAM,cAAc,CAAA;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAqB,KAAK,EAAY,MAAM,YAAY,CAAA;AAC/D,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAA;AAClD,OAAO,EAAwD,QAAQ,EAAe,MAAM,eAAe,CAAA;AAC3G,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAEpD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAU,mBAAmB,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAA;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AAEjE,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,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,CACf,CAAC,MAAc,EAAW,EAAE,CAC1B,CAAC,CAAC,oBAAoB,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,KAAK,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAA;AAE/F,MAAM,CAAC,MAAM,WAAW,GACtB,CAAC,IAAU,EAAE,EAAE,CACf,CAAC,MAAc,EAAW,EAAE,CAC1B,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAA;AAErC,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,MAAc,EAAW,EAAE;IACjD,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;IAChC,OAAO,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;AACxD,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,MAAc,EAAU,EAAE,WAAC,OAAA,MAAA,MAAM,CAAC,IAAI,mCAAI,mBAAmB,CAAA,EAAA,CAAA;AAErF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,MAAc,EAAW,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,sBAAsB,CAAA","sourcesContent":["import { Dictionary, TraverseMethod } from '../../common'\nimport { SystemError } from '../../error'\nimport { Node, NodePointer, Nodes, NodesMap } from '../../node'\nimport { NodeValues } from '../../node/nodeValues'\nimport { NodeDef, NodeDefCode, NodeDefCodeProps, NodeDefProps, NodeDefs, NodeDefType } from '../../nodeDef'\nimport { defaultCycle, Surveys } from '../../survey'\nimport { Survey, SurveyDependencyType } from '../../survey/survey'\nimport { Arrays, Queue } from '../../utils'\nimport { Record, RECORD_STEP_DEFAULT } from '../record'\nimport { RecordStepAnalysisCode } from '../recordStep'\nimport { RecordNodesIndexReader } from './recordNodesIndexReader'\n\nexport const getCycle = (record: Record): string => record.cycle ?? defaultCycle\n\nexport const getNodes = (record: Record): Dictionary<Node> => record.nodes ?? {}\n\nexport const getNodesArray = (record: Record): Node[] => Object.values(getNodes(record))\n\nexport const getNodeByUuid =\n (uuid: string) =>\n (record: Record): Node | undefined =>\n record.nodes?.[uuid]\n\nexport const getNodesByUuids =\n (uuids: string[]) =>\n (record: Record): Node[] =>\n uuids.map((uuid: string) => getNodeByUuid(uuid)(record)) as Node[]\n\nexport const getRoot = (record: Record): Node | undefined => {\n const rootUuid = record._nodesIndex ? RecordNodesIndexReader.getNodeRootUuid(record._nodesIndex) : null\n if (rootUuid) {\n return getNodeByUuid(rootUuid)(record)\n }\n return getNodesArray(record).find((node) => !node.parentUuid)\n}\n\nexport const getChildren =\n (parentNode: Node, childDefUuid?: string) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const childrenUuids = childDefUuid\n ? RecordNodesIndexReader.getNodeUuidsByParentAndChildDef({\n parentNodeUuid: parentNode.uuid,\n childDefUuid,\n })(record._nodesIndex)\n : RecordNodesIndexReader.getNodeUuidsByParent(parentNode.uuid)(record._nodesIndex)\n return getNodesByUuids(childrenUuids)(record)\n }\n return getNodesArray(record).filter(\n (node) => node.parentUuid === parentNode.uuid && (!childDefUuid || node.nodeDefUuid == childDefUuid)\n )\n }\n\nexport const getChild =\n (parentNode: Node, childDefUuid: string) =>\n (record: Record): Node => {\n const children = getChildren(parentNode, childDefUuid)(record)\n const errorParams = { childDefUuid, parentNodeUuid: parentNode.uuid, recordUuid: record.uuid }\n if (children.length === 1) {\n return children[0]\n }\n if (children.length > 1) {\n throw new SystemError('systemError.record.multipleNodesFound', errorParams)\n }\n throw new SystemError('systemError.record.childNotFound', errorParams)\n }\n\nexport const getParent =\n (node: Node) =>\n (record: Record): Node | undefined =>\n node.parentUuid ? getNodeByUuid(node.parentUuid)(record) : undefined\n\nexport const getNodesByDefUuid =\n (nodeDefUuid: string) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeUuidsByDef(nodeDefUuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n return getNodesArray(record).filter((node) => node.nodeDefUuid === nodeDefUuid)\n }\n\nconst isNodeFlagTrue =\n (isChildFlagTrue: (parent: Node, nodeDefUuid: string) => boolean) =>\n (params: { record: Record; node: Node }): boolean => {\n const { record, node } = params\n const ancestorsAndSelf = getAncestorsAndSelf({ record, node })\n for (let i = 0; i < ancestorsAndSelf.length - 1; i++) {\n const child = ancestorsAndSelf[i]\n const parent = ancestorsAndSelf[i + 1]\n if (!isChildFlagTrue(parent, child.nodeDefUuid)) return false\n }\n return true\n }\n\nexport const isNodeApplicable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildApplicable(parent, nodeDefUuid))\nexport const isNodeEditable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildEditable(parent, nodeDefUuid))\nexport const isNodeVisible = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildVisible(parent, nodeDefUuid))\n\nexport const getDependentCodeAttributes =\n (node: Node) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeCodeDependentUuids(node.uuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n throw new SystemError('record.nodesIndexNotInitialized')\n }\n\nexport const getParentCodeAttribute =\n (params: { parentNode: Node; nodeDef: NodeDefCode }) =>\n (record: Record): Node | undefined => {\n const { parentNode, nodeDef } = params\n\n const parentCodeDefUuid = NodeDefs.getParentCodeDefUuid(nodeDef)\n if (!parentCodeDefUuid) return undefined\n\n const ancestors = getAncestorsAndSelf({ record, node: parentNode })\n for (const ancestor of ancestors) {\n const children = getChildren(ancestor, parentCodeDefUuid)(record)\n if (children.length === 1) {\n return children[0]\n }\n }\n return undefined\n }\n\n// ancestors\nexport const visitAncestorsAndSelf =\n (node: Node, visitor: (node: Node) => void, stopIfFn?: () => boolean) =>\n (record: Record): void => {\n let currentNode: Node | undefined = node\n while (currentNode) {\n visitor(currentNode)\n if (stopIfFn?.()) break\n currentNode = getParent(currentNode)(record)\n }\n }\n\nexport const findAncestor =\n (node: Node, predicate: (node: Node) => boolean) =>\n (record: Record): Node | undefined => {\n let result: Node | undefined = undefined\n visitAncestorsAndSelf(\n node,\n (visitedNode) => {\n if (predicate(visitedNode)) {\n result = visitedNode\n }\n },\n () => !!result\n )(record)\n return result\n }\n\nexport const getAncestor = (params: { record: Record; node: Node; ancestorDefUuid: string }): Node | undefined => {\n const { record, node, ancestorDefUuid } = params\n if (node.nodeDefUuid === ancestorDefUuid) return node\n\n let ancestor = getParent(node)(record)\n while (ancestor && ancestor.nodeDefUuid !== ancestorDefUuid) {\n ancestor = getParent(ancestor)(record)\n }\n return ancestor\n}\n\n/**\n * Returns the list of ancestors from the given node to the root entity\n */\nexport const getAncestorsAndSelf = (params: { record: Record; node: Node }): Array<Node> => {\n const { record, node } = params\n const ancestors: Array<Node> = []\n visitAncestorsAndSelf(node, (currentNode) => {\n ancestors.push(currentNode)\n })(record)\n return ancestors\n}\n\n// descendants\n\nexport const getDescendantsOrSelf = (params: {\n record: Record\n node: Node\n nodeDefDescendant: NodeDef<any>\n}): Node[] => {\n const { record, node, nodeDefDescendant } = params\n\n if (nodeDefDescendant.uuid === node.nodeDefUuid) return [node]\n\n const nodeDefDescendantFullHierarchy = [...nodeDefDescendant.meta.h, nodeDefDescendant.uuid]\n\n // 1. get the descendant node defs uuids starting from node nodeDefUuid (not inclusive) down to the specified nodeDefDescendant uuid\n const descendantNodeDefUuids = nodeDefDescendantFullHierarchy.slice(\n nodeDefDescendantFullHierarchy.indexOf(node.nodeDefUuid) + 1\n )\n // 2. for every level in the hierarchy, find the children having the nodeDefUuid equal to the current one\n let currentAncestors = [node]\n let currentDescendants: Node[] = []\n for (const currentDescendantDefUuid of descendantNodeDefUuids) {\n for (const currentAncestor of currentAncestors) {\n currentDescendants.push(...getChildren(currentAncestor, currentDescendantDefUuid)(record))\n }\n currentAncestors = currentDescendants\n currentDescendants = []\n }\n return currentAncestors // currentAncestors is equal to the currentDescendants of the last level\n}\n\nexport const getDescendant = (params: { record: Record; node: Node; nodeDefDescendant: NodeDef<any> }): Node => {\n const { record, node, nodeDefDescendant } = params\n\n return getDescendantsOrSelf({ record, node, nodeDefDescendant })[0]\n}\n\nexport const isDescendantOf = (params: { node: Node; ancestor: Node }): boolean => {\n const { node, ancestor } = params\n return Nodes.getHierarchy(node).includes(ancestor.uuid)\n}\n\nexport const visitDescendantsAndSelf = (params: {\n record: Record\n node: Node\n visitor: (node: Node) => boolean | void\n traverseMethod?: TraverseMethod\n}): void => {\n const { record, node, visitor, traverseMethod = TraverseMethod.bfs } = params\n\n if (traverseMethod === TraverseMethod.bfs) {\n const queue = new Queue()\n\n queue.enqueue(node)\n\n while (!queue.isEmpty()) {\n const visitedNode = queue.dequeue()\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n queue.enqueueItems(children)\n }\n } else {\n const stack = []\n\n stack.push(node)\n\n while (stack.length > 0) {\n const visitedNode = stack.pop() as Node\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n\n // add children to stack in reverse order\n for (let index = children.length - 1; index >= 0; index--) {\n const child = children[index]\n stack.push(child)\n }\n }\n }\n}\n\nexport const findDescendantOrSelf =\n (node: Node, predicate: (node: Node) => boolean) =>\n (record: Record): Node | undefined => {\n let found = undefined\n\n visitDescendantsAndSelf({\n record,\n node,\n visitor: (currentNode) => {\n if (predicate(currentNode)) {\n found = currentNode\n return true\n }\n return false\n },\n })\n return found\n }\n\nconst getClosestAncestorNode = (params: {\n record: Record\n node: Node\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n dependentDef: NodeDef<NodeDefType, NodeDefProps>\n}): Node | undefined => {\n const { record, node, nodeDef, dependentDef } = params\n\n // 1a if dependent def is the same as node def, potentially all nodes with\n // nodeDefUuid === dependentDef.uuid in record could be dependent of nodeDef;\n // consider the root node as the closest ancestor node\n if (nodeDef.uuid === dependentDef.uuid) {\n return getRoot(record)\n }\n // 1 find common ancestor def\n const commonAncestorDefUuid = Arrays.last(Arrays.intersection(nodeDef.meta.h, dependentDef.meta.h))\n if (!commonAncestorDefUuid) return undefined\n\n // 2 get ancestor node with common parent def\n return getAncestor({ record, node, ancestorDefUuid: commonAncestorDefUuid })\n}\n\ntype EntityKeyNodesGetterParams = {\n survey: Survey\n cycle?: string\n record: Record\n entity: Node\n keyDefs?: NodeDef<NodeDefType, NodeDefProps>[]\n}\n\nexport const getEntityKeyNodesByDefUuid = (params: EntityKeyNodesGetterParams): NodesMap => {\n const { survey, cycle, record, entity, keyDefs } = params\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: entity.nodeDefUuid })\n const nodeDefKeys = keyDefs ?? Surveys.getNodeDefKeys({ survey, cycle, nodeDef })\n return nodeDefKeys.reduce((acc: NodesMap, nodeDefKey) => {\n const nodeKey = getDescendant({ record, node: entity, nodeDefDescendant: nodeDefKey })\n acc[nodeDefKey.uuid] = nodeKey\n return acc\n }, {})\n}\n\nexport const getEntityKeyNodes = (params: EntityKeyNodesGetterParams): Node[] =>\n Object.values(getEntityKeyNodesByDefUuid(params))\n\nexport const getEntityKeyValuesByDefUuid = (params: EntityKeyNodesGetterParams): Dictionary<any> => {\n const keyNodesByDefUuid = getEntityKeyNodesByDefUuid(params)\n return Object.entries(keyNodesByDefUuid).reduce((acc: Dictionary<any>, [uuid, keyNode]) => {\n acc[uuid] = keyNode?.value\n return acc\n }, {})\n}\n\nexport const getEntityKeyValues = (params: EntityKeyNodesGetterParams): any[] =>\n Object.values(getEntityKeyValuesByDefUuid(params))\n\nexport const getEntitySiblings = (params: { record: Record; entity: Node; includeSelf?: boolean }) => {\n const { record, entity, includeSelf = false } = params\n const parentEntity = getParent(entity)(record)\n if (!parentEntity) return []\n const siblingEntities = getChildren(parentEntity, entity.nodeDefUuid)(record)\n return includeSelf ? siblingEntities : siblingEntities.filter((sibling) => !Nodes.areEqual(sibling, entity))\n}\n\nexport const getAttributeSiblings = (params: {\n record: Record\n node: Node\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n}) => {\n const { record, node, nodeDef } = params\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return []\n const siblingParentEntities = getEntitySiblings({ record, entity: parentEntity })\n return siblingParentEntities.reduce((siblingsAcc: Node[], siblingEntity) => {\n siblingsAcc.push(...getChildren(siblingEntity, nodeDef.uuid)(record))\n return siblingsAcc\n }, [])\n}\n\nexport const getNodeIndex = (params: { record: Record; node: Node }) => {\n const { record, node } = params\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return 0 // root entity\n const siblings = getChildren(parentEntity, node.nodeDefUuid)(record)\n return siblings.indexOf(node)\n}\n\nexport const findEntityByKeyValues = (params: {\n survey: Survey\n cycle: string\n record: Record\n parentEntity: Node\n entityDefUuid: string\n keyValuesByDefUuid: Dictionary<any>\n}): Node | undefined => {\n const { survey, cycle, record, parentEntity, entityDefUuid, keyValuesByDefUuid } = params\n const entityDef = Surveys.getNodeDefByUuid({ survey, uuid: entityDefUuid })\n const siblingEntities = getChildren(parentEntity, entityDefUuid)(record)\n if (NodeDefs.isSingle(entityDef)) {\n return siblingEntities[0]\n }\n const keyDefs = Surveys.getNodeDefKeys({ survey, cycle, nodeDef: entityDef })\n\n return siblingEntities.find((siblingEntity) => {\n const siblingEntityKeyValuesByDefUuid = getEntityKeyValuesByDefUuid({\n survey,\n record,\n entity: siblingEntity,\n keyDefs,\n })\n return keyDefs.every((keyDef) => {\n const keyValue = siblingEntityKeyValuesByDefUuid[keyDef.uuid]\n const keyValueSearch = keyValuesByDefUuid[keyDef.uuid]\n return NodeValues.isValueEqual({\n survey,\n nodeDef: keyDef,\n value: keyValue,\n valueSearch: keyValueSearch,\n })\n })\n })\n}\n\nexport const findEntityWithSameKeysInAnotherRecord = (params: {\n survey: Survey\n cycle: string\n entityUuid: string\n record: Record\n recordOther: Record\n}): Node | undefined => {\n const { survey, cycle, entityUuid, record, recordOther } = params\n const entity = getNodeByUuid(entityUuid)(record)\n if (!entity) return undefined\n\n let otherRecordCurrentParentEntity = getRoot(recordOther)\n if (!otherRecordCurrentParentEntity) return undefined\n\n const entityAncestorsAndSelf = getAncestorsAndSelf({\n record,\n node: entity,\n })\n const ancestorDefUuidsAndKeys = entityAncestorsAndSelf.map((ancestor) => ({\n entityDefUuid: ancestor.nodeDefUuid,\n keyValuesByDefUuid: getEntityKeyValuesByDefUuid({\n survey,\n record,\n entity: ancestor,\n }),\n }))\n\n const ancestorDefUuidsAndKeysToVisit = [...ancestorDefUuidsAndKeys].reverse()\n\n for (let index = 1; otherRecordCurrentParentEntity && index < ancestorDefUuidsAndKeysToVisit.length; index++) {\n const { entityDefUuid, keyValuesByDefUuid } = ancestorDefUuidsAndKeysToVisit[index]\n otherRecordCurrentParentEntity = findEntityByKeyValues({\n survey,\n cycle,\n record: recordOther,\n parentEntity: otherRecordCurrentParentEntity,\n entityDefUuid,\n keyValuesByDefUuid,\n })\n }\n return otherRecordCurrentParentEntity\n}\n\nexport const getDependentNodePointers = (params: {\n survey: Survey\n record: Record\n node: Node\n dependencyType: SurveyDependencyType\n includeSelf?: boolean\n filterFn?: (nodePointer: NodePointer) => boolean\n}) => {\n const { survey, record, node, dependencyType, includeSelf = false, filterFn = null } = params\n const nodeDefUuid = node.nodeDefUuid\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: nodeDefUuid })\n const dependentDefs = Surveys.getNodeDefDependents({ survey, nodeDefUuid, dependencyType })\n const nodePointers: Array<NodePointer> = []\n\n const addToNodePointers = (nodePointer: NodePointer): void => {\n if (filterFn === null || filterFn(nodePointer)) {\n nodePointers.push(nodePointer)\n }\n }\n\n for (const dependentDef of dependentDefs) {\n // 1 find common ancestor node\n const commonAncestorNode = getClosestAncestorNode({ record, node, nodeDef, dependentDef })\n if (!commonAncestorNode) continue\n\n const nodeDefDependentParent = Surveys.getNodeDefParent({ survey, nodeDef: dependentDef })\n if (!nodeDefDependentParent) throw new SystemError('record.nodes.dependents.dependencyOnRootFound')\n\n // 2 find descendant nodes of common parent node with nodeDefUuid = dependentDef uuid\n const dependentContextNodes = getDescendantsOrSelf({\n record,\n node: commonAncestorNode,\n nodeDefDescendant: nodeDefDependentParent,\n })\n\n for (const dependentContextNode of dependentContextNodes) {\n addToNodePointers({\n nodeCtx: dependentContextNode,\n nodeDef: dependentDef,\n })\n }\n }\n if (includeSelf) {\n const parentNode = getParent(node)(record)\n if (parentNode) {\n addToNodePointers({\n nodeCtx: parentNode,\n nodeDef,\n })\n }\n }\n\n return nodePointers\n}\n\nexport const getAncestorCodePath = (params: {\n survey: Survey\n record: Record\n parentNode: Node\n nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>\n}): string[] => {\n const { record, parentNode, nodeDef, survey } = params\n\n const getCodeAttributeItemCode = (codeAttribute: Node | undefined): string => {\n const codeItemUuid = codeAttribute ? NodeValues.getItemUuid(codeAttribute) : undefined\n if (!codeItemUuid) return ''\n const item = Surveys.getCategoryItemByUuid({ survey, itemUuid: codeItemUuid })\n return item?.props.code ?? ''\n }\n\n const codePaths = []\n let currentParentCodeAttribute = getParentCodeAttribute({ parentNode, nodeDef })(record)\n\n while (currentParentCodeAttribute) {\n const ancestorItemCode = getCodeAttributeItemCode(currentParentCodeAttribute)\n codePaths.unshift(ancestorItemCode)\n const ancestorCodeDef = Surveys.getNodeDefByUuid({\n survey,\n uuid: currentParentCodeAttribute.nodeDefUuid,\n }) as NodeDefCode\n currentParentCodeAttribute = getParentCodeAttribute({ parentNode, nodeDef: ancestorCodeDef })(record)\n }\n return codePaths\n}\n\nexport const getCategoryItemUuid = (params: {\n survey: Survey\n nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>\n record: Record\n parentNode: Node\n code: string\n}): string | undefined => {\n const { survey, nodeDef, record, parentNode, code } = params\n const categoryUuid = nodeDef.props.categoryUuid\n\n const codePaths = [...getAncestorCodePath({ survey, record, parentNode, nodeDef }), code]\n\n const item = Surveys.getCategoryItemByCodePaths({ survey, categoryUuid, codePaths })\n\n return item?.uuid\n}\n\nexport const isNodeFilledByUser =\n (node: Node) =>\n (record: Record): boolean =>\n !!findDescendantOrSelf(node, (visitedNode) => Nodes.hasUserInputValue(visitedNode))(record)\n\nexport const isNodeEmpty =\n (node: Node) =>\n (record: Record): boolean =>\n !isNodeFilledByUser(node)(record)\n\nexport const isEmpty = (record: Record): boolean => {\n const rootNode = getRoot(record)\n return rootNode ? isNodeEmpty(rootNode)(record) : true\n}\n\nexport const getStep = (record: Record): string => record.step ?? RECORD_STEP_DEFAULT\n\nexport const isInAnalysisStep = (record: Record): boolean => getStep(record) === RecordStepAnalysisCode\n"]}
|
|
1
|
+
{"version":3,"file":"recordGetters.js","sourceRoot":"","sources":["../../../../src/record/_records/recordGetters.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,cAAc,EAAE,MAAM,cAAc,CAAA;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAqB,KAAK,EAAY,MAAM,YAAY,CAAA;AAC/D,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAA;AAClD,OAAO,EAAwD,QAAQ,EAAe,MAAM,eAAe,CAAA;AAC3G,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAEpD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAU,mBAAmB,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAA;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAA;AAE/D,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAU,EAAE,WAAC,OAAA,MAAA,MAAM,CAAC,KAAK,m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I,aAAJ,IAAI,uBAAJ,IAAI,CAAE,IAAI,CAAA;AACnB,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,kBAAkB,GAC7B,CAAC,IAAU,EAAE,EAAE,CACf,CAAC,MAAc,EAAW,EAAE,CAC1B,CAAC,CAAC,oBAAoB,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,KAAK,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAA;AAE/F,MAAM,CAAC,MAAM,WAAW,GACtB,CAAC,IAAU,EAAE,EAAE,CACf,CAAC,MAAc,EAAW,EAAE,CAC1B,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAA;AAErC,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,MAAc,EAAW,EAAE;IACjD,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;IAChC,OAAO,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;AACxD,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,MAAc,EAAU,EAAE,WAAC,OAAA,MAAA,MAAM,CAAC,IAAI,mCAAI,mBAAmB,CAAA,EAAA,CAAA;AAErF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,MAAc,EAAW,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,sBAAsB,CAAA","sourcesContent":["import { Dictionary, TraverseMethod } from '../../common'\nimport { SystemError } from '../../error'\nimport { Node, NodePointer, Nodes, NodesMap } from '../../node'\nimport { NodeValues } from '../../node/nodeValues'\nimport { NodeDef, NodeDefCode, NodeDefCodeProps, NodeDefProps, NodeDefs, NodeDefType } from '../../nodeDef'\nimport { defaultCycle, Surveys } from '../../survey'\nimport { Survey, SurveyDependencyType } from '../../survey/survey'\nimport { Arrays, Queue } from '../../utils'\nimport { Record, RECORD_STEP_DEFAULT } from '../record'\nimport { RecordStepAnalysisCode } from '../recordStep'\nimport { RecordNodesIndexReader } from './recordNodesIndexReader'\nimport { NodeDefSelfReferences } from './nodeDefSelfReferences'\n\nexport const getCycle = (record: Record): string => record.cycle ?? defaultCycle\n\nexport const getNodes = (record: Record): Dictionary<Node> => record.nodes ?? {}\n\nexport const getNodesArray = (record: Record): Node[] => Object.values(getNodes(record))\n\nexport const getNodeByUuid =\n (uuid: string) =>\n (record: Record): Node | undefined =>\n record.nodes?.[uuid]\n\nexport const getNodesByUuids =\n (uuids: string[]) =>\n (record: Record): Node[] =>\n uuids.map((uuid: string) => getNodeByUuid(uuid)(record)) as Node[]\n\nexport const getRoot = (record: Record): Node | undefined => {\n const rootUuid = record._nodesIndex ? RecordNodesIndexReader.getNodeRootUuid(record._nodesIndex) : null\n if (rootUuid) {\n return getNodeByUuid(rootUuid)(record)\n }\n return getNodesArray(record).find((node) => !node.parentUuid)\n}\n\nexport const getChildren =\n (parentNode: Node, childDefUuid?: string) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const childrenUuids = childDefUuid\n ? RecordNodesIndexReader.getNodeUuidsByParentAndChildDef({\n parentNodeUuid: parentNode.uuid,\n childDefUuid,\n })(record._nodesIndex)\n : RecordNodesIndexReader.getNodeUuidsByParent(parentNode.uuid)(record._nodesIndex)\n return getNodesByUuids(childrenUuids)(record)\n }\n return getNodesArray(record).filter(\n (node) => node.parentUuid === parentNode.uuid && (!childDefUuid || node.nodeDefUuid == childDefUuid)\n )\n }\n\nexport const getChild =\n (parentNode: Node, childDefUuid: string) =>\n (record: Record): Node => {\n const children = getChildren(parentNode, childDefUuid)(record)\n const errorParams = { childDefUuid, parentNodeUuid: parentNode.uuid, recordUuid: record.uuid }\n if (children.length === 1) {\n return children[0]\n }\n if (children.length > 1) {\n throw new SystemError('systemError.record.multipleNodesFound', errorParams)\n }\n throw new SystemError('systemError.record.childNotFound', errorParams)\n }\n\nexport const getParent =\n (node: Node) =>\n (record: Record): Node | undefined =>\n node.parentUuid ? getNodeByUuid(node.parentUuid)(record) : undefined\n\nexport const getNodesByDefUuid =\n (nodeDefUuid: string) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeUuidsByDef(nodeDefUuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n return getNodesArray(record).filter((node) => node.nodeDefUuid === nodeDefUuid)\n }\n\nconst isNodeFlagTrue =\n (isChildFlagTrue: (parent: Node, nodeDefUuid: string) => boolean) =>\n (params: { record: Record; node: Node }): boolean => {\n const { record, node } = params\n const ancestorsAndSelf = getAncestorsAndSelf({ record, node })\n for (let i = 0; i < ancestorsAndSelf.length - 1; i++) {\n const child = ancestorsAndSelf[i]\n const parent = ancestorsAndSelf[i + 1]\n if (!isChildFlagTrue(parent, child.nodeDefUuid)) return false\n }\n return true\n }\n\nexport const isNodeApplicable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildApplicable(parent, nodeDefUuid))\nexport const isNodeEditable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildEditable(parent, nodeDefUuid))\nexport const isNodeVisible = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildVisible(parent, nodeDefUuid))\n\nexport const getDependentCodeAttributes =\n (node: Node) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeCodeDependentUuids(node.uuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n throw new SystemError('record.nodesIndexNotInitialized')\n }\n\nexport const getParentCodeAttribute =\n (params: { parentNode: Node; nodeDef: NodeDefCode }) =>\n (record: Record): Node | undefined => {\n const { parentNode, nodeDef } = params\n\n const parentCodeDefUuid = NodeDefs.getParentCodeDefUuid(nodeDef)\n if (!parentCodeDefUuid) return undefined\n\n const ancestors = getAncestorsAndSelf({ record, node: parentNode })\n for (const ancestor of ancestors) {\n const children = getChildren(ancestor, parentCodeDefUuid)(record)\n if (children.length === 1) {\n return children[0]\n }\n }\n return undefined\n }\n\n// ancestors\nexport const visitAncestorsAndSelf =\n (node: Node, visitor: (node: Node) => void, stopIfFn?: () => boolean) =>\n (record: Record): void => {\n let currentNode: Node | undefined = node\n while (currentNode) {\n visitor(currentNode)\n if (stopIfFn?.()) break\n currentNode = getParent(currentNode)(record)\n }\n }\n\nexport const findAncestor =\n (node: Node, predicate: (node: Node) => boolean) =>\n (record: Record): Node | undefined => {\n let result: Node | undefined = undefined\n visitAncestorsAndSelf(\n node,\n (visitedNode) => {\n if (predicate(visitedNode)) {\n result = visitedNode\n }\n },\n () => !!result\n )(record)\n return result\n }\n\nexport const getAncestor = (params: { record: Record; node: Node; ancestorDefUuid: string }): Node | undefined => {\n const { record, node, ancestorDefUuid } = params\n if (node.nodeDefUuid === ancestorDefUuid) return node\n\n let ancestor = getParent(node)(record)\n while (ancestor && ancestor.nodeDefUuid !== ancestorDefUuid) {\n ancestor = getParent(ancestor)(record)\n }\n return ancestor\n}\n\n/**\n * Returns the list of ancestors from the given node to the root entity\n */\nexport const getAncestorsAndSelf = (params: { record: Record; node: Node }): Array<Node> => {\n const { record, node } = params\n const ancestors: Array<Node> = []\n visitAncestorsAndSelf(node, (currentNode) => {\n ancestors.push(currentNode)\n })(record)\n return ancestors\n}\n\n// descendants\n\nexport const getDescendantsOrSelf = (params: {\n record: Record\n node: Node\n nodeDefDescendant: NodeDef<any>\n}): Node[] => {\n const { record, node, nodeDefDescendant } = params\n\n if (nodeDefDescendant.uuid === node.nodeDefUuid) return [node]\n\n const nodeDefDescendantFullHierarchy = [...nodeDefDescendant.meta.h, nodeDefDescendant.uuid]\n\n // 1. get the descendant node defs uuids starting from node nodeDefUuid (not inclusive) down to the specified nodeDefDescendant uuid\n const descendantNodeDefUuids = nodeDefDescendantFullHierarchy.slice(\n nodeDefDescendantFullHierarchy.indexOf(node.nodeDefUuid) + 1\n )\n // 2. for every level in the hierarchy, find the children having the nodeDefUuid equal to the current one\n let currentAncestors = [node]\n let currentDescendants: Node[] = []\n for (const currentDescendantDefUuid of descendantNodeDefUuids) {\n for (const currentAncestor of currentAncestors) {\n currentDescendants.push(...getChildren(currentAncestor, currentDescendantDefUuid)(record))\n }\n currentAncestors = currentDescendants\n currentDescendants = []\n }\n return currentAncestors // currentAncestors is equal to the currentDescendants of the last level\n}\n\nexport const getDescendant = (params: { record: Record; node: Node; nodeDefDescendant: NodeDef<any> }): Node => {\n const { record, node, nodeDefDescendant } = params\n\n return getDescendantsOrSelf({ record, node, nodeDefDescendant })[0]\n}\n\nexport const isDescendantOf = (params: { node: Node; ancestor: Node }): boolean => {\n const { node, ancestor } = params\n return Nodes.getHierarchy(node).includes(ancestor.uuid)\n}\n\nexport const visitDescendantsAndSelf = (params: {\n record: Record\n node: Node\n visitor: (node: Node) => boolean | void\n traverseMethod?: TraverseMethod\n}): void => {\n const { record, node, visitor, traverseMethod = TraverseMethod.bfs } = params\n\n if (traverseMethod === TraverseMethod.bfs) {\n const queue = new Queue()\n\n queue.enqueue(node)\n\n while (!queue.isEmpty()) {\n const visitedNode = queue.dequeue()\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n queue.enqueueItems(children)\n }\n } else {\n const stack = []\n\n stack.push(node)\n\n while (stack.length > 0) {\n const visitedNode = stack.pop() as Node\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n\n // add children to stack in reverse order\n for (let index = children.length - 1; index >= 0; index--) {\n const child = children[index]\n stack.push(child)\n }\n }\n }\n}\n\nexport const findDescendantOrSelf =\n (node: Node, predicate: (node: Node) => boolean) =>\n (record: Record): Node | undefined => {\n let found = undefined\n\n visitDescendantsAndSelf({\n record,\n node,\n visitor: (currentNode) => {\n if (predicate(currentNode)) {\n found = currentNode\n return true\n }\n return false\n },\n })\n return found\n }\n\nconst getClosestAncestorNode = (params: {\n record: Record\n node: Node\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n dependentDef: NodeDef<NodeDefType, NodeDefProps>\n dependencyType: SurveyDependencyType\n}): Node | undefined => {\n const { record, node, nodeDef, dependentDef, dependencyType } = params\n\n // 1a if dependent def is the same as node def, potentially all nodes with\n // nodeDefUuid === dependentDef.uuid in record could be dependent of nodeDef;\n // consider the root node as the closest ancestor node,\n // unless the node def references itself only among the children of its parent entity (e.g. validation \"dbh > 0\")\n if (nodeDef.uuid === dependentDef.uuid) {\n return NodeDefSelfReferences.isSelfReferenceLocal({ nodeDef, dependencyType })\n ? getParent(node)(record)\n : getRoot(record)\n }\n // 1 find common ancestor def\n const commonAncestorDefUuid = Arrays.last(Arrays.intersection(nodeDef.meta.h, dependentDef.meta.h))\n if (!commonAncestorDefUuid) return undefined\n\n // 2 get ancestor node with common parent def\n return getAncestor({ record, node, ancestorDefUuid: commonAncestorDefUuid })\n}\n\ntype EntityKeyNodesGetterParams = {\n survey: Survey\n cycle?: string\n record: Record\n entity: Node\n keyDefs?: NodeDef<NodeDefType, NodeDefProps>[]\n}\n\nexport const getEntityKeyNodesByDefUuid = (params: EntityKeyNodesGetterParams): NodesMap => {\n const { survey, cycle, record, entity, keyDefs } = params\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: entity.nodeDefUuid })\n const nodeDefKeys = keyDefs ?? Surveys.getNodeDefKeys({ survey, cycle, nodeDef })\n return nodeDefKeys.reduce((acc: NodesMap, nodeDefKey) => {\n const nodeKey = getDescendant({ record, node: entity, nodeDefDescendant: nodeDefKey })\n acc[nodeDefKey.uuid] = nodeKey\n return acc\n }, {})\n}\n\nexport const getEntityKeyNodes = (params: EntityKeyNodesGetterParams): Node[] =>\n Object.values(getEntityKeyNodesByDefUuid(params))\n\nexport const getEntityKeyValuesByDefUuid = (params: EntityKeyNodesGetterParams): Dictionary<any> => {\n const keyNodesByDefUuid = getEntityKeyNodesByDefUuid(params)\n return Object.entries(keyNodesByDefUuid).reduce((acc: Dictionary<any>, [uuid, keyNode]) => {\n acc[uuid] = keyNode?.value\n return acc\n }, {})\n}\n\nexport const getEntityKeyValues = (params: EntityKeyNodesGetterParams): any[] =>\n Object.values(getEntityKeyValuesByDefUuid(params))\n\nexport const getEntitySiblings = (params: { record: Record; entity: Node; includeSelf?: boolean }) => {\n const { record, entity, includeSelf = false } = params\n const parentEntity = getParent(entity)(record)\n if (!parentEntity) return []\n const siblingEntities = getChildren(parentEntity, entity.nodeDefUuid)(record)\n return includeSelf ? siblingEntities : siblingEntities.filter((sibling) => !Nodes.areEqual(sibling, entity))\n}\n\nexport const getAttributeSiblings = (params: {\n record: Record\n node: Node\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n}) => {\n const { record, node, nodeDef } = params\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return []\n const siblingParentEntities = getEntitySiblings({ record, entity: parentEntity })\n return siblingParentEntities.reduce((siblingsAcc: Node[], siblingEntity) => {\n siblingsAcc.push(...getChildren(siblingEntity, nodeDef.uuid)(record))\n return siblingsAcc\n }, [])\n}\n\nexport const getNodeIndex = (params: { record: Record; node: Node }) => {\n const { record, node } = params\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return 0 // root entity\n const siblings = getChildren(parentEntity, node.nodeDefUuid)(record)\n return siblings.indexOf(node)\n}\n\nexport const findEntityByKeyValues = (params: {\n survey: Survey\n cycle: string\n record: Record\n parentEntity: Node\n entityDefUuid: string\n keyValuesByDefUuid: Dictionary<any>\n}): Node | undefined => {\n const { survey, cycle, record, parentEntity, entityDefUuid, keyValuesByDefUuid } = params\n const entityDef = Surveys.getNodeDefByUuid({ survey, uuid: entityDefUuid })\n const siblingEntities = getChildren(parentEntity, entityDefUuid)(record)\n if (NodeDefs.isSingle(entityDef)) {\n return siblingEntities[0]\n }\n const keyDefs = Surveys.getNodeDefKeys({ survey, cycle, nodeDef: entityDef })\n\n return siblingEntities.find((siblingEntity) => {\n const siblingEntityKeyValuesByDefUuid = getEntityKeyValuesByDefUuid({\n survey,\n record,\n entity: siblingEntity,\n keyDefs,\n })\n return keyDefs.every((keyDef) => {\n const keyValue = siblingEntityKeyValuesByDefUuid[keyDef.uuid]\n const keyValueSearch = keyValuesByDefUuid[keyDef.uuid]\n return NodeValues.isValueEqual({\n survey,\n nodeDef: keyDef,\n value: keyValue,\n valueSearch: keyValueSearch,\n })\n })\n })\n}\n\nexport const findEntityWithSameKeysInAnotherRecord = (params: {\n survey: Survey\n cycle: string\n entityUuid: string\n record: Record\n recordOther: Record\n}): Node | undefined => {\n const { survey, cycle, entityUuid, record, recordOther } = params\n const entity = getNodeByUuid(entityUuid)(record)\n if (!entity) return undefined\n\n let otherRecordCurrentParentEntity = getRoot(recordOther)\n if (!otherRecordCurrentParentEntity) return undefined\n\n const entityAncestorsAndSelf = getAncestorsAndSelf({\n record,\n node: entity,\n })\n const ancestorDefUuidsAndKeys = entityAncestorsAndSelf.map((ancestor) => ({\n entityDefUuid: ancestor.nodeDefUuid,\n keyValuesByDefUuid: getEntityKeyValuesByDefUuid({\n survey,\n record,\n entity: ancestor,\n }),\n }))\n\n const ancestorDefUuidsAndKeysToVisit = [...ancestorDefUuidsAndKeys].reverse()\n\n for (let index = 1; otherRecordCurrentParentEntity && index < ancestorDefUuidsAndKeysToVisit.length; index++) {\n const { entityDefUuid, keyValuesByDefUuid } = ancestorDefUuidsAndKeysToVisit[index]\n otherRecordCurrentParentEntity = findEntityByKeyValues({\n survey,\n cycle,\n record: recordOther,\n parentEntity: otherRecordCurrentParentEntity,\n entityDefUuid,\n keyValuesByDefUuid,\n })\n }\n return otherRecordCurrentParentEntity\n}\n\nexport const getDependentNodePointers = (params: {\n survey: Survey\n record: Record\n node: Node\n dependencyType: SurveyDependencyType\n includeSelf?: boolean\n filterFn?: (nodePointer: NodePointer) => boolean\n}) => {\n const { survey, record, node, dependencyType, includeSelf = false, filterFn = null } = params\n const nodeDefUuid = node.nodeDefUuid\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: nodeDefUuid })\n const dependentDefs = Surveys.getNodeDefDependents({ survey, nodeDefUuid, dependencyType })\n const nodePointers: Array<NodePointer> = []\n\n const addToNodePointers = (nodePointer: NodePointer): void => {\n if (filterFn === null || filterFn(nodePointer)) {\n nodePointers.push(nodePointer)\n }\n }\n\n for (const dependentDef of dependentDefs) {\n // 1 find common ancestor node\n const commonAncestorNode = getClosestAncestorNode({ record, node, nodeDef, dependentDef, dependencyType })\n if (!commonAncestorNode) continue\n\n const nodeDefDependentParent = Surveys.getNodeDefParent({ survey, nodeDef: dependentDef })\n if (!nodeDefDependentParent) throw new SystemError('record.nodes.dependents.dependencyOnRootFound')\n\n // 2 find descendant nodes of common parent node with nodeDefUuid = dependentDef uuid\n const dependentContextNodes = getDescendantsOrSelf({\n record,\n node: commonAncestorNode,\n nodeDefDescendant: nodeDefDependentParent,\n })\n\n for (const dependentContextNode of dependentContextNodes) {\n addToNodePointers({\n nodeCtx: dependentContextNode,\n nodeDef: dependentDef,\n })\n }\n }\n if (includeSelf) {\n const parentNode = getParent(node)(record)\n if (parentNode) {\n addToNodePointers({\n nodeCtx: parentNode,\n nodeDef,\n })\n }\n }\n\n return nodePointers\n}\n\nexport const getAncestorCodePath = (params: {\n survey: Survey\n record: Record\n parentNode: Node\n nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>\n}): string[] => {\n const { record, parentNode, nodeDef, survey } = params\n\n const getCodeAttributeItemCode = (codeAttribute: Node | undefined): string => {\n const codeItemUuid = codeAttribute ? NodeValues.getItemUuid(codeAttribute) : undefined\n if (!codeItemUuid) return ''\n const item = Surveys.getCategoryItemByUuid({ survey, itemUuid: codeItemUuid })\n return item?.props.code ?? ''\n }\n\n const codePaths = []\n let currentParentCodeAttribute = getParentCodeAttribute({ parentNode, nodeDef })(record)\n\n while (currentParentCodeAttribute) {\n const ancestorItemCode = getCodeAttributeItemCode(currentParentCodeAttribute)\n codePaths.unshift(ancestorItemCode)\n const ancestorCodeDef = Surveys.getNodeDefByUuid({\n survey,\n uuid: currentParentCodeAttribute.nodeDefUuid,\n }) as NodeDefCode\n currentParentCodeAttribute = getParentCodeAttribute({ parentNode, nodeDef: ancestorCodeDef })(record)\n }\n return codePaths\n}\n\nexport const getCategoryItemUuid = (params: {\n survey: Survey\n nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>\n record: Record\n parentNode: Node\n code: string\n}): string | undefined => {\n const { survey, nodeDef, record, parentNode, code } = params\n const categoryUuid = nodeDef.props.categoryUuid\n\n const codePaths = [...getAncestorCodePath({ survey, record, parentNode, nodeDef }), code]\n\n const item = Surveys.getCategoryItemByCodePaths({ survey, categoryUuid, codePaths })\n\n return item?.uuid\n}\n\nexport const isNodeFilledByUser =\n (node: Node) =>\n (record: Record): boolean =>\n !!findDescendantOrSelf(node, (visitedNode) => Nodes.hasUserInputValue(visitedNode))(record)\n\nexport const isNodeEmpty =\n (node: Node) =>\n (record: Record): boolean =>\n !isNodeFilledByUser(node)(record)\n\nexport const isEmpty = (record: Record): boolean => {\n const rootNode = getRoot(record)\n return rootNode ? isNodeEmpty(rootNode)(record) : true\n}\n\nexport const getStep = (record: Record): string => record.step ?? RECORD_STEP_DEFAULT\n\nexport const isInAnalysisStep = (record: Record): boolean => getStep(record) === RecordStepAnalysisCode\n"]}
|
|
@@ -5,6 +5,7 @@ import { ExpressionNode, ExpressionNodeEvaluatorConstructor, ExpressionNodeType
|
|
|
5
5
|
type Evaluators<C extends ExpressionContext> = {
|
|
6
6
|
[nodeType in ExpressionNodeType]?: ExpressionNodeEvaluatorConstructor<C, ExpressionNode<ExpressionNodeType>>;
|
|
7
7
|
};
|
|
8
|
+
export declare const parseExpression: (expression: string) => ExpressionNode<ExpressionNodeType>;
|
|
8
9
|
export declare class JavascriptExpressionEvaluator<C extends ExpressionContext> implements ExpressionEvaluator<C> {
|
|
9
10
|
functions: ExpressionFunctions<C>;
|
|
10
11
|
evaluators: Evaluators<C>;
|
|
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.JavascriptExpressionEvaluator = void 0;
|
|
12
|
+
exports.JavascriptExpressionEvaluator = exports.parseExpression = void 0;
|
|
13
13
|
const node_1 = require("../node");
|
|
14
14
|
const error_1 = require("../../error");
|
|
15
15
|
const functionsDefault_1 = require("./functionsDefault");
|
|
@@ -57,6 +57,7 @@ const parseExpression = (expression) => {
|
|
|
57
57
|
}
|
|
58
58
|
return expressionNode;
|
|
59
59
|
};
|
|
60
|
+
exports.parseExpression = parseExpression;
|
|
60
61
|
class JavascriptExpressionEvaluator {
|
|
61
62
|
constructor(functions = {}, evaluators = {}) {
|
|
62
63
|
this.evaluators = Object.assign(Object.assign({}, defaultEvaluators), evaluators);
|
|
@@ -64,7 +65,7 @@ class JavascriptExpressionEvaluator {
|
|
|
64
65
|
}
|
|
65
66
|
evaluate(expression, context) {
|
|
66
67
|
return __awaiter(this, void 0, void 0, function* () {
|
|
67
|
-
return this.evaluateNode(parseExpression(expression), context !== null && context !== void 0 ? context : {});
|
|
68
|
+
return this.evaluateNode((0, exports.parseExpression)(expression), context !== null && context !== void 0 ? context : {});
|
|
68
69
|
});
|
|
69
70
|
}
|
|
70
71
|
evaluateNode(expressionNode, context) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"evaluator.js","sourceRoot":"","sources":["../../../src/expression/javascript/evaluator.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,kCAAgG;AAChG,uCAAyC;AAEzC,yDAAqD;AACrD,wCAA6C;AAC7C,0CAA+C;AAC/C,sCAA2C;AAC3C,8CAAmD;AACnD,oDAAyD;AACzD,kDAAuD;AACvD,4CAAiD;AACjD,0CAA+C;AAC/C,8CAAmD;AACnD,sCAA2C;AAC3C,wCAA6C;AAC7C,4CAA4D;AAM5D,MAAM,iBAAiB,GAAG;IACxB,CAAC,yBAAkB,CAAC,KAAK,CA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e,mBAY3B;AAED,MAAa,6BAA6B;IAIxC,YAAY,YAAoC,EAAE,EAAE,aAA4B,EAAE;QAChF,IAAI,CAAC,UAAU,mCAAQ,iBAAiB,GAAK,UAAU,CAAE,CAAA;QACzD,IAAI,CAAC,SAAS,mCAAQ,mCAAgB,GAAK,SAAS,CAAE,CAAA;IACxD,CAAC;IAEK,QAAQ,CAAC,UAAkB,EAAE,OAAW;;YAC5C,OAAO,IAAI,CAAC,YAAY,CAAC,IAAA,uBAAe,EAAC,UAAU,CAAC,EAAE,OAAO,aAAP,OAAO,cAAP,OAAO,GAAK,EAAQ,CAAC,CAAA;QAC7E,CAAC;KAAA;IAEK,YAAY,CAAC,cAAkD,EAAE,OAAU;;YAC/E,MAAM,EAAE,IAAI,EAAE,GAAG,cAAc,CAAA;YAE/B,MAAM,aAAa,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;YAC3C,IAAI,CAAC,aAAa,EAAE,CAAC;gBACnB,MAAM,IAAI,mBAAW,CAAC,oCAAoC,EAAE,EAAE,IAAI,EAAE,CAAC,CAAA;YACvE,CAAC;YACD,OAAO,IAAI,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAA;QAClE,CAAC;KAAA;CACF;AAtBD,sEAsBC","sourcesContent":["import { ExpressionContext } from '../context'\nimport { ExpressionEvaluator } from '../evaluator'\nimport { ExpressionFunctions } from '../function'\nimport { ExpressionNode, ExpressionNodeEvaluatorConstructor, ExpressionNodeType } from '../node'\nimport { SystemError } from '../../error'\n\nimport { functionsDefault } from './functionsDefault'\nimport { ArrayEvaluator } from './node/array'\nimport { BinaryEvaluator } from './node/binary'\nimport { CallEvaluator } from './node/call'\nimport { CompoundEvaluator } from './node/compound'\nimport { ConditionalEvaluator } from './node/conditional'\nimport { IdentifierEvaluator } from './node/identifier'\nimport { LiteralEvaluator } from './node/literal'\nimport { MemberEvaluator } from './node/member'\nimport { SequenceEvaluator } from './node/sequence'\nimport { ThisEvaluator } from './node/this'\nimport { UnaryEvaluator } from './node/unary'\nimport { JavascriptExpressionParser } from './parser/parser'\n\ntype Evaluators<C extends ExpressionContext> = {\n [nodeType in ExpressionNodeType]?: ExpressionNodeEvaluatorConstructor<C, ExpressionNode<ExpressionNodeType>>\n}\n\nconst defaultEvaluators = {\n [ExpressionNodeType.Array]: ArrayEvaluator,\n [ExpressionNodeType.Binary]: BinaryEvaluator,\n [ExpressionNodeType.Call]: CallEvaluator,\n [ExpressionNodeType.Compound]: CompoundEvaluator,\n [ExpressionNodeType.Conditional]: ConditionalEvaluator,\n [ExpressionNodeType.Identifier]: IdentifierEvaluator,\n [ExpressionNodeType.Literal]: LiteralEvaluator,\n [ExpressionNodeType.Member]: MemberEvaluator,\n [ExpressionNodeType.Sequence]: SequenceEvaluator,\n [ExpressionNodeType.This]: ThisEvaluator,\n [ExpressionNodeType.Unary]: UnaryEvaluator,\n}\n\n// Parsed expressions cache: the same expressions are evaluated many times (e.g. for every node during a record update).\n// The cached expression nodes are shared, so evaluators must never modify them.\nconst PARSED_EXPRESSIONS_CACHE_MAX_SIZE = 1000\nconst parsedExpressionsCache = new Map<string, ExpressionNode<ExpressionNodeType>>()\nconst expressionParser = new JavascriptExpressionParser()\n\nexport const parseExpression = (expression: string): ExpressionNode<ExpressionNodeType> => {\n let expressionNode = parsedExpressionsCache.get(expression)\n if (!expressionNode) {\n expressionNode = expressionParser.parse(expression)\n if (parsedExpressionsCache.size >= PARSED_EXPRESSIONS_CACHE_MAX_SIZE) {\n // evict the oldest entry (Map keeps insertion order)\n const oldestExpression = parsedExpressionsCache.keys().next().value\n if (oldestExpression !== undefined) parsedExpressionsCache.delete(oldestExpression)\n }\n parsedExpressionsCache.set(expression, expressionNode)\n }\n return expressionNode\n}\n\nexport class JavascriptExpressionEvaluator<C extends ExpressionContext> implements ExpressionEvaluator<C> {\n functions: ExpressionFunctions<C>\n evaluators: Evaluators<C>\n\n constructor(functions: ExpressionFunctions<C> = {}, evaluators: Evaluators<C> = {}) {\n this.evaluators = { ...defaultEvaluators, ...evaluators }\n this.functions = { ...functionsDefault, ...functions }\n }\n\n async evaluate(expression: string, context?: C): Promise<any> {\n return this.evaluateNode(parseExpression(expression), context ?? ({} as C))\n }\n\n async evaluateNode(expressionNode: ExpressionNode<ExpressionNodeType>, context: C): Promise<any> {\n const { type } = expressionNode\n\n const NodeEvaluator = this.evaluators[type]\n if (!NodeEvaluator) {\n throw new SystemError('expression.unsupportedFunctionType', { type })\n }\n return new NodeEvaluator(this, context).evaluate(expressionNode)\n }\n}\n"]}
|
package/dist/job/JobBase.d.ts
CHANGED
|
@@ -72,8 +72,9 @@ export declare abstract class JobBase<C extends JobContext, R = undefined> imple
|
|
|
72
72
|
/**
|
|
73
73
|
* Registers the listener notified of job events (status changes and progress).
|
|
74
74
|
* Only one listener can be registered at a time; registering a new one replaces the previous one.
|
|
75
|
+
* Errors thrown (or rejections returned) by the listener are logged and do not affect the job execution.
|
|
75
76
|
*/
|
|
76
|
-
onEvent(listener: (event: JobEvent) =>
|
|
77
|
+
onEvent(listener: (event: JobEvent) => unknown): this;
|
|
77
78
|
isPending(): boolean;
|
|
78
79
|
isRunning(): boolean;
|
|
79
80
|
isSucceeded(): boolean;
|
|
@@ -177,5 +178,11 @@ export declare abstract class JobBase<C extends JobContext, R = undefined> imple
|
|
|
177
178
|
* Cancels any pending throttled progress notification and resets the throttle state.
|
|
178
179
|
*/
|
|
179
180
|
private cancelNotifyProgress;
|
|
181
|
+
/**
|
|
182
|
+
* Notifies the event to the registered listener.
|
|
183
|
+
* Listener errors are only logged: they would otherwise fail the job or, when thrown inside the progress
|
|
184
|
+
* throttle timeout, crash the process.
|
|
185
|
+
*/
|
|
180
186
|
private notifyEvent;
|
|
187
|
+
private logListenerError;
|
|
181
188
|
}
|
package/dist/job/JobBase.js
CHANGED
|
@@ -103,6 +103,7 @@ class JobBase {
|
|
|
103
103
|
/**
|
|
104
104
|
* Registers the listener notified of job events (status changes and progress).
|
|
105
105
|
* Only one listener can be registered at a time; registering a new one replaces the previous one.
|
|
106
|
+
* Errors thrown (or rejections returned) by the listener are logged and do not affect the job execution.
|
|
106
107
|
*/
|
|
107
108
|
onEvent(listener) {
|
|
108
109
|
this.eventListener = listener;
|
|
@@ -194,7 +195,8 @@ class JobBase {
|
|
|
194
195
|
}
|
|
195
196
|
}
|
|
196
197
|
catch (error) {
|
|
197
|
-
|
|
198
|
+
// a job can fail while still pending (e.g. the transaction cannot be opened, or onStart fails)
|
|
199
|
+
if (!this.cancelRequested && !this.isFailed() && !this.isCanceled()) {
|
|
198
200
|
this.logError((_a = error.stack) !== null && _a !== void 0 ? _a : error);
|
|
199
201
|
const { key, params } = this.getErrorInfo(error);
|
|
200
202
|
this.addError({ error: { valid: false, errors: [{ key, params }] } });
|
|
@@ -518,9 +520,25 @@ class JobBase {
|
|
|
518
520
|
}
|
|
519
521
|
this.progressThrottleLastRunTime = 0;
|
|
520
522
|
}
|
|
523
|
+
/**
|
|
524
|
+
* Notifies the event to the registered listener.
|
|
525
|
+
* Listener errors are only logged: they would otherwise fail the job or, when thrown inside the progress
|
|
526
|
+
* throttle timeout, crash the process.
|
|
527
|
+
*/
|
|
521
528
|
notifyEvent(event) {
|
|
529
|
+
const listener = this.eventListener;
|
|
530
|
+
if (!listener)
|
|
531
|
+
return;
|
|
532
|
+
try {
|
|
533
|
+
Promise.resolve(listener(event)).catch((error) => this.logListenerError(error));
|
|
534
|
+
}
|
|
535
|
+
catch (error) {
|
|
536
|
+
this.logListenerError(error);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
logListenerError(error) {
|
|
522
540
|
var _a;
|
|
523
|
-
(_a =
|
|
541
|
+
this.logError(`error in job event listener: ${(_a = error === null || error === void 0 ? void 0 : error.stack) !== null && _a !== void 0 ? _a : error}`);
|
|
524
542
|
}
|
|
525
543
|
}
|
|
526
544
|
exports.JobBase = JobBase;
|
package/dist/job/JobBase.js.map
CHANGED
|
@@ -1 +1 @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G,CAAC,CAAA;IACtC,CAAC;IAEO,WAAW,CAAC,KAAe;;QACjC,MAAA,IAAI,CAAC,aAAa,qDAAG,KAAK,CAAC,CAAA;IAC7B,CAAC;;AA7hBH,0BA8hBC;AA7hBiB,mBAAW,GAAG;IAC5B,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;IAChB,IAAI,EAAE,MAAM;CACb,AAJ0B,CAI1B","sourcesContent":["import { Dictionary } from '../common'\nimport { SystemError } from '../error'\nimport { Logger } from '../logger'\nimport { UUIDs } from '../utils'\n\nimport { Job } from './job'\nimport { JobContext } from './jobContext'\nimport { JobEvent, JobEventType } from './jobEvent'\nimport { JobSerialized } from './jobSerialized'\nimport { JobStatus } from './status'\n\nexport interface JobConstructor {\n new <C extends JobContext, R>(context: C, innerJobs?: JobBase<any>[]): JobBase<C, R>\n readonly prototype: JobBase<any, any>\n}\n\nconst PROGRESS_NOTIFICATION_THROTTLE_MILLIS = 1000\n\n/**\n * Asynchronous task handler.\n *\n * Status workflow:\n * - pending\n * - running\n * - (end)\n * -- succeeded\n * -- failed\n * -- canceled\n *\n * Methods that can be overwritten by subclasses:\n * - shouldExecute (in tx)\n * - onStart (in tx)\n * - execute (in tx)\n * - beforeSuccess (in tx)\n * - generateResult (in tx)\n * - beforeEnd (in tx)\n * - onEnd (out of tx)\n * - getErrorInfo\n */\nexport abstract class JobBase<C extends JobContext, R = undefined> implements Job<R> {\n static readonly keysContext = {\n surveyId: 'surveyId',\n survey: 'survey',\n user: 'user',\n }\n\n readonly uuid: string\n readonly type: string\n status: JobStatus = JobStatus.pending\n startTime?: Date\n endTime?: Date\n total: number\n result: R | undefined = undefined\n errors: Record<string, any> = {}\n canceledByAdmin?: boolean\n\n protected logger: Logger\n protected context: C\n protected innerJobs: JobBase<C, any>[]\n protected currentInnerJobIndex = -1\n\n private _processed = 0\n private eventListener: ((event: JobEvent) => void) | undefined = undefined\n private progressThrottleTimeoutId: ReturnType<typeof setTimeout> | undefined = undefined\n private progressThrottleLastRunTime = 0\n private _stopOnInnerJobFailure = true\n // set as soon as cancel() is called (the canceled status is set only after beforeEnd has run)\n private cancelRequested = false\n private beforeEndCalled = false\n // inner job events are handled in sequence; executeJobs waits for them before going on\n private innerJobEventsQueue: Promise<void> = Promise.resolve()\n\n public constructor(context: C, innerJobs: JobBase<C, any>[] = []) {\n this.context = { ...context }\n this.innerJobs = innerJobs\n\n this.uuid = UUIDs.v4()\n this.type = this.context.type ?? this.constructor.name\n this.total = innerJobs.length > 0 ? innerJobs.length : 1\n\n // Created last, so that createLogger() overrides can safely build the logger name out of\n // the job identity (e.g. arena's `Job <ClassName> (<uuid>)` log correlation id).\n this.logger = this.createLogger()\n }\n\n get processed(): number {\n return this._processed\n }\n\n set processed(value: number) {\n this._processed = value\n this.notifyProgress()\n }\n\n get stopOnInnerJobFailure(): boolean {\n return this._stopOnInnerJobFailure\n }\n\n set stopOnInnerJobFailure(value: boolean) {\n this._stopOnInnerJobFailure = value\n }\n\n protected get surveyId(): number | null {\n return this.getContextProp(JobBase.keysContext.surveyId)\n }\n\n protected get user(): any {\n return this.getContextProp(JobBase.keysContext.user)\n }\n\n protected get userUuid(): string | undefined {\n return this.user?.uuid\n }\n\n protected get contextSurvey(): any {\n return this.getContextProp(JobBase.keysContext.survey)\n }\n\n protected getContextProp<T = any>(prop: string, defaultValue: T | null = null): T | null {\n const value = (this.context as any)[prop]\n return value ?? defaultValue\n }\n\n protected setContext(context: Partial<C>): void {\n Object.assign(this.context, context)\n }\n\n protected deleteContextProps(...propNames: string[]): void {\n propNames.forEach((propName) => {\n delete (this.context as any)[propName]\n })\n }\n\n /**\n * Registers the listener notified of job events (status changes and progress).\n * Only one listener can be registered at a time; registering a new one replaces the previous one.\n */\n onEvent(listener: (event: JobEvent) => void): this {\n this.eventListener = listener\n return this\n }\n\n isPending(): boolean {\n return this.status === JobStatus.pending\n }\n\n isRunning(): boolean {\n return this.status === JobStatus.running\n }\n\n isSucceeded(): boolean {\n return this.status === JobStatus.succeeded\n }\n\n isFailed(): boolean {\n return this.status === JobStatus.failed\n }\n\n isCanceled(): boolean {\n return this.status === JobStatus.canceled\n }\n\n isEnded(): boolean {\n return [JobStatus.succeeded, JobStatus.failed, JobStatus.canceled].includes(this.status)\n }\n\n hasErrors(): boolean {\n return Object.keys(this.errors).length > 0\n }\n\n protected getCurrentInnerJob(): JobBase<C, any> | undefined {\n return this.innerJobs[this.currentInnerJobIndex]\n }\n\n protected combineInnerJobsResults(): Record<string, any> {\n const results: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(results, innerJob.result ?? {}))\n return results\n }\n\n protected combineInnerJobsErrors(): Record<string, any> {\n const errors: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(errors, innerJob.errors ?? {}))\n return errors\n }\n\n async cancel(options: { canceledByAdmin?: boolean } = {}): Promise<void> {\n const { canceledByAdmin = false } = options\n if (this.isEnded()) return\n\n this.cancelRequested = true\n\n const currentInnerJob = this.getCurrentInnerJob()\n if (currentInnerJob?.isRunning()) {\n // the parent job status will be set to canceled when handling the canceled event of the inner job\n await currentInnerJob.cancel({ canceledByAdmin })\n return\n }\n // no inner job running (job without inner jobs, or between two inner jobs)\n this.canceledByAdmin = canceledByAdmin\n // release the resources (temp files/directories, streams) allocated before the cancellation\n await this.runBeforeEnd()\n await this.setStatus(JobStatus.canceled)\n }\n\n private isCancelRequestedOrNotRunning(): boolean {\n return this.cancelRequested || !this.isRunning()\n }\n\n /**\n * Runs beforeEnd only once (it can be called by cancel() and when the job execution ends).\n */\n private async runBeforeEnd(): Promise<void> {\n if (this.beforeEndCalled) return\n this.beforeEndCalled = true\n await this.beforeEnd()\n }\n\n async start(client: any = null): Promise<void> {\n this.logDebug('start')\n\n try {\n if (client) {\n await client.tx(async (tx: any) => {\n this.context.tx = tx\n await this.executeInTransaction()\n })\n } else {\n await this.executeInTransaction()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.setStatus(JobStatus.succeeded)\n }\n } catch (error: any) {\n if (!this.cancelRequested && !this.isFailed() && (this.isRunning() || this.isSucceeded())) {\n this.logError(error.stack ?? error)\n const { key, params } = this.getErrorInfo(error)\n this.addError({ error: { valid: false, errors: [{ key, params }] } })\n await this.setStatus(JobStatus.failed)\n }\n } finally {\n this.context.tx = undefined\n }\n }\n\n private async executeInTransaction(): Promise<void> {\n try {\n await this.onStart()\n\n const shouldExecute = await this.shouldExecute()\n if (shouldExecute) {\n if (this.innerJobs.length > 0) {\n await this.executeJobs()\n } else {\n await this.execute()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.beforeSuccess()\n }\n }\n } finally {\n // runs only if not already run by cancel()\n await this.runBeforeEnd()\n this.context.tx = undefined\n }\n\n if (this.isCancelRequestedOrNotRunning()) {\n this.throwError('jobCanceledOrErrorsFound')\n }\n }\n\n /**\n * Generates a plain JSON-serializable representation of the job, including its inner jobs.\n */\n toJSON(): JobSerialized<R> {\n const { errors, processed, result, status, total, type, userUuid, uuid } = this\n\n return {\n uuid,\n type,\n userUuid,\n surveyId: this.surveyId,\n innerJobs: this.innerJobs.map((job) => job.toJSON()),\n currentInnerJobIndex: this.currentInnerJobIndex,\n\n status,\n pending: this.isPending(),\n running: this.isRunning(),\n succeeded: this.isSucceeded(),\n canceled: this.isCanceled(),\n failed: this.isFailed(),\n ended: this.isEnded(),\n\n total,\n processed,\n progressPercent: this.calculateProgressPercent(),\n elapsedMillis: this.calculateElapsedMillis(),\n\n errors: this.isFailed() ? errors : undefined,\n result: this.isSucceeded() ? result : undefined,\n }\n }\n\n private async executeJobs(): Promise<void> {\n this.logDebug(`- ${this.total} inner jobs found`)\n\n for (let i = 0; i < this.innerJobs.length; i++) {\n this.logDebug(`- executing inner job ${i + 1}`)\n this.currentInnerJobIndex = i\n const currentInnerJob = this.innerJobs[i]\n if (currentInnerJob.context) {\n Object.assign(this.context, currentInnerJob.context)\n }\n currentInnerJob.context = this.context\n currentInnerJob.onEvent((event) => {\n // handle the inner job events in sequence; errors are logged (they would be unhandled rejections otherwise)\n this.innerJobEventsQueue = this.innerJobEventsQueue\n .then(() => this.onInnerJobEvent(event))\n .catch((error) => this.logError(error?.stack ?? error))\n })\n\n // The inner job shares this very context object, and its own start()/executeInTransaction()\n // clear `context.tx` when they terminate: without saving and restoring it here, the first\n // inner job would wipe the parent's transaction handle, leaving every following inner job\n // (and the parent's own beforeSuccess()/beforeEnd()) running outside of the transaction.\n // start() never throws (it swallows/records errors internally), so a plain restore is enough.\n const parentTx = this.context.tx\n await currentInnerJob.start(parentTx)\n this.context.tx = parentTx\n // the inner job events (e.g. canceled, failed) update the status of this job\n await this.innerJobEventsQueue\n\n if (this.cancelRequested || this.isCanceled() || currentInnerJob.isCanceled()) {\n break\n }\n if (currentInnerJob.isSucceeded()) {\n this.incrementProcessedItems()\n } else if (this.stopOnInnerJobFailure) {\n break\n }\n }\n\n this.logDebug(`- ${this.processed} inner jobs processed successfully`)\n }\n\n /**\n * Runs the job's own work when it has no inner jobs. Default implementation is a no-op, so\n * subclasses that only supply inner jobs (and never override this) don't need to. It also means\n * a subclass can safely call `super.execute()` defensively without knowing whether any ancestor\n * overrides it - if this were `abstract` instead, TypeScript would compile away any runtime\n * property for it entirely, so `super.execute()` would throw the moment no ancestor overrides it\n * (confirmed in production: a subclass whose immediate parent didn't override `execute()` crashed\n * with \"(intermediate value).execute is not a function\" the instant it called `super.execute()`).\n */\n protected async execute(): Promise<void> {\n // to be extended by subclasses\n }\n\n /**\n * Determines whether the job should actually run.\n * When it returns false, \"execute\" (or the inner jobs) will be skipped, but the job will still succeed.\n */\n protected shouldExecute(): Promise<boolean> {\n return Promise.resolve(true)\n }\n\n protected incrementProcessedItems(incrementBy = 1): void {\n this.processed += incrementBy\n }\n\n protected async setStatus(status: JobStatus): Promise<void> {\n this.logDebug(`set status: ${status}`)\n this.status = status\n\n const event: JobEvent = { type: JobEventType.statusChange, status, total: this.total, processed: this.processed }\n if (status === JobStatus.failed) {\n event.errors = this.errors\n }\n\n if (this.isEnded()) {\n this.logDebug('onEnd...')\n await this.onEnd()\n this.logDebug(`onEnd run. Job completed in ${this.elapsedTimePrettyFormat}`)\n }\n\n this.notifyEvent(event)\n }\n\n /**\n * Inner job event handler.\n */\n protected async onInnerJobEvent(event: JobEvent): Promise<void> {\n const { status } = event\n if (status === JobStatus.canceled) {\n this.canceledByAdmin = this.getCurrentInnerJob()?.canceledByAdmin ?? false\n return this.setStatus(status)\n }\n if (status === JobStatus.failed) {\n // report the errors of the failed inner job in the failed event (and in the errors) of this job\n Object.assign(this.errors, this.getCurrentInnerJob()?.errors ?? {})\n return this.setStatus(status)\n }\n if (status === JobStatus.running) {\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n return\n }\n this.logDebug(`Unknown inner job status: ${status}`)\n }\n\n /**\n * Called when the job just has been started.\n */\n protected async onStart(): Promise<void> {\n this.startTime = new Date()\n await this.setStatus(JobStatus.running)\n }\n\n /**\n * Called before beforeEnd only if the status will change to 'success'.\n * Default implementation stores the value returned by generateResult() via setResult().\n * It runs INSIDE the current db transaction.\n */\n protected async beforeSuccess(): Promise<void> {\n this.setResult(await this.generateResult())\n }\n\n /**\n * Computes the value beforeSuccess() will store as this job's result.\n * Default implementation returns whatever is already in `this.result`\n * (e.g. accumulated via earlier setResult() calls during execute()).\n */\n protected generateResult(): Promise<R | undefined> {\n return Promise.resolve(this.result)\n }\n\n /**\n * Updates this job's result. When both the current and incoming values are plain objects,\n * they are merged (Object.assign); otherwise the incoming value replaces the current one.\n * This keeps it safe for subclasses whose result is a primitive (e.g. a plain number) as\n * well as ones that build an object result incrementally across multiple setResult() calls.\n */\n protected setResult(result: R | undefined): void {\n if (result && typeof result === 'object' && this.result && typeof this.result === 'object') {\n Object.assign(this.result, result)\n } else {\n this.result = result\n }\n }\n\n /**\n * Called before onEnd. Useful for flushing resources used by the job before it terminates completely.\n * It runs INSIDE the current db transaction.\n */\n protected beforeEnd(): Promise<void> {\n this.logDebug('Cleanup')\n return Promise.resolve()\n }\n\n /**\n * Called when the job status changes to success, failed or canceled\n * (it runs OUTSIDE of the current db transaction)\n */\n protected onEnd(): Promise<void> {\n this.endTime = new Date()\n this.cancelNotifyProgress()\n return Promise.resolve()\n }\n\n protected addError(error: any, errorKey?: string): void {\n const key = errorKey ?? String(this.processed + 1)\n this.errors[key] = error\n }\n\n protected throwError(errorKey: string, params?: Dictionary<any>): void {\n // SystemError: getErrorInfo will report the translatable key instead of a generic error\n throw new SystemError(errorKey, params)\n }\n\n protected getErrorInfo(error: any): { key: string; params: Record<string, any> } {\n if (error instanceof SystemError) {\n return { key: `appErrors:${error.key}`, params: error.params }\n }\n return { key: 'appErrors:generic', params: { text: error.toString() } }\n }\n\n protected abstract createLogger(): Logger\n\n protected logDebug(...msgs: any[]): void {\n this.logger.debug(...msgs)\n }\n\n protected logInfo(...msgs: any[]): void {\n this.logger.info(...msgs)\n }\n\n protected logWarn(...msgs: any[]): void {\n this.logger.warn(...msgs)\n }\n\n protected logError(...msgs: any[]): void {\n this.logger.error(...msgs)\n }\n\n private get elapsedTimePrettyFormat(): string {\n const elapsedTime = this.calculateElapsedMillis()\n const elapsedMins = Math.floor(elapsedTime / 1000 / 60)\n const elapsedSeconds = String(Math.floor(elapsedTime / 1000) % 60).padStart(2, '0')\n const elapsedMillis = String(elapsedTime % 1000).padStart(3, '0')\n return `${elapsedMins}:${elapsedSeconds}.${elapsedMillis}`\n }\n\n private calculatePartialProgress(): number {\n if (this.isSucceeded()) return 100\n if (this.total > 0) return Math.floor((100 * this.processed) / this.total)\n return 0\n }\n\n private calculateProgressPercent(): number {\n const partialProgress = this.calculatePartialProgress()\n const currentInnerJob = this.getCurrentInnerJob()\n if (\n !currentInnerJob ||\n this.currentInnerJobIndex < 0 ||\n partialProgress === 100 ||\n this.processed > this.currentInnerJobIndex\n ) {\n return partialProgress\n }\n return partialProgress + Math.floor(currentInnerJob.calculateProgressPercent() / this.total)\n }\n\n private calculateElapsedMillis(): number {\n if (!this.startTime) return 0\n return (this.endTime ?? new Date()).getTime() - this.startTime.getTime()\n }\n\n /**\n * Notifies a progress event to the registered listener, throttled so that fast-changing\n * progress does not flood consumers (e.g. web socket clients).\n */\n private notifyProgress(): void {\n const run = (): void => {\n this.progressThrottleTimeoutId = undefined\n this.progressThrottleLastRunTime = Date.now()\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n }\n\n if (this.progressThrottleTimeoutId) return\n\n const elapsed = Date.now() - this.progressThrottleLastRunTime\n if (!this.progressThrottleLastRunTime || elapsed >= PROGRESS_NOTIFICATION_THROTTLE_MILLIS) {\n run()\n } else {\n this.progressThrottleTimeoutId = setTimeout(run, PROGRESS_NOTIFICATION_THROTTLE_MILLIS - elapsed)\n }\n }\n\n /**\n * Cancels any pending throttled progress notification and resets the throttle state.\n */\n private cancelNotifyProgress(): void {\n if (this.progressThrottleTimeoutId) {\n clearTimeout(this.progressThrottleTimeoutId)\n this.progressThrottleTimeoutId = undefined\n }\n this.progressThrottleLastRunTime = 0\n }\n\n private notifyEvent(event: JobEvent): void {\n this.eventListener?.(event)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"JobBase.js","sourceRoot":"","sources":["../../src/job/JobBase.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,oCAAsC;AAEtC,oCAAgC;AAIhC,yCAAmD;AAEnD,qCAAoC;AAOpC,MAAM,qCAAqC,GAAG,IAAI,CAAA;AAElD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAsB,OAAO;IAiC3B,YAAmB,OAAU,EAAE,YAA+B,EAAE;;QAxBhE,WAAM,GAAc,kBAAS,CAAC,OAAO,CAAA;QAIrC,WAAM,GAAkB,SAAS,CAAA;QACjC,WAAM,GAAwB,EAAE,CAAA;QAMtB,yBAAoB,GAAG,CAAC,CAAC,CAAA;QAE3B,eAAU,GAAG,CAAC,CAAA;QACd,kBAAa,GAA+C,SAAS,CAAA;QACrE,8BAAy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BAAL,KAAK,CAAE,KAAK,mCAAI,KAAK,EAAE,CAAC,CAAA;IACxE,CAAC;;AA9iBH,0BA+iBC;AA9iBiB,mBAAW,GAAG;IAC5B,QAAQ,EAAE,UAAU;IACpB,MAAM,EAAE,QAAQ;IAChB,IAAI,EAAE,MAAM;CACb,AAJ0B,CAI1B","sourcesContent":["import { Dictionary } from '../common'\nimport { SystemError } from '../error'\nimport { Logger } from '../logger'\nimport { UUIDs } from '../utils'\n\nimport { Job } from './job'\nimport { JobContext } from './jobContext'\nimport { JobEvent, JobEventType } from './jobEvent'\nimport { JobSerialized } from './jobSerialized'\nimport { JobStatus } from './status'\n\nexport interface JobConstructor {\n new <C extends JobContext, R>(context: C, innerJobs?: JobBase<any>[]): JobBase<C, R>\n readonly prototype: JobBase<any, any>\n}\n\nconst PROGRESS_NOTIFICATION_THROTTLE_MILLIS = 1000\n\n/**\n * Asynchronous task handler.\n *\n * Status workflow:\n * - pending\n * - running\n * - (end)\n * -- succeeded\n * -- failed\n * -- canceled\n *\n * Methods that can be overwritten by subclasses:\n * - shouldExecute (in tx)\n * - onStart (in tx)\n * - execute (in tx)\n * - beforeSuccess (in tx)\n * - generateResult (in tx)\n * - beforeEnd (in tx)\n * - onEnd (out of tx)\n * - getErrorInfo\n */\nexport abstract class JobBase<C extends JobContext, R = undefined> implements Job<R> {\n static readonly keysContext = {\n surveyId: 'surveyId',\n survey: 'survey',\n user: 'user',\n }\n\n readonly uuid: string\n readonly type: string\n status: JobStatus = JobStatus.pending\n startTime?: Date\n endTime?: Date\n total: number\n result: R | undefined = undefined\n errors: Record<string, any> = {}\n canceledByAdmin?: boolean\n\n protected logger: Logger\n protected context: C\n protected innerJobs: JobBase<C, any>[]\n protected currentInnerJobIndex = -1\n\n private _processed = 0\n private eventListener: ((event: JobEvent) => unknown) | undefined = undefined\n private progressThrottleTimeoutId: ReturnType<typeof setTimeout> | undefined = undefined\n private progressThrottleLastRunTime = 0\n private _stopOnInnerJobFailure = true\n // set as soon as cancel() is called (the canceled status is set only after beforeEnd has run)\n private cancelRequested = false\n private beforeEndCalled = false\n // inner job events are handled in sequence; executeJobs waits for them before going on\n private innerJobEventsQueue: Promise<void> = Promise.resolve()\n\n public constructor(context: C, innerJobs: JobBase<C, any>[] = []) {\n this.context = { ...context }\n this.innerJobs = innerJobs\n\n this.uuid = UUIDs.v4()\n this.type = this.context.type ?? this.constructor.name\n this.total = innerJobs.length > 0 ? innerJobs.length : 1\n\n // Created last, so that createLogger() overrides can safely build the logger name out of\n // the job identity (e.g. arena's `Job <ClassName> (<uuid>)` log correlation id).\n this.logger = this.createLogger()\n }\n\n get processed(): number {\n return this._processed\n }\n\n set processed(value: number) {\n this._processed = value\n this.notifyProgress()\n }\n\n get stopOnInnerJobFailure(): boolean {\n return this._stopOnInnerJobFailure\n }\n\n set stopOnInnerJobFailure(value: boolean) {\n this._stopOnInnerJobFailure = value\n }\n\n protected get surveyId(): number | null {\n return this.getContextProp(JobBase.keysContext.surveyId)\n }\n\n protected get user(): any {\n return this.getContextProp(JobBase.keysContext.user)\n }\n\n protected get userUuid(): string | undefined {\n return this.user?.uuid\n }\n\n protected get contextSurvey(): any {\n return this.getContextProp(JobBase.keysContext.survey)\n }\n\n protected getContextProp<T = any>(prop: string, defaultValue: T | null = null): T | null {\n const value = (this.context as any)[prop]\n return value ?? defaultValue\n }\n\n protected setContext(context: Partial<C>): void {\n Object.assign(this.context, context)\n }\n\n protected deleteContextProps(...propNames: string[]): void {\n propNames.forEach((propName) => {\n delete (this.context as any)[propName]\n })\n }\n\n /**\n * Registers the listener notified of job events (status changes and progress).\n * Only one listener can be registered at a time; registering a new one replaces the previous one.\n * Errors thrown (or rejections returned) by the listener are logged and do not affect the job execution.\n */\n onEvent(listener: (event: JobEvent) => unknown): this {\n this.eventListener = listener\n return this\n }\n\n isPending(): boolean {\n return this.status === JobStatus.pending\n }\n\n isRunning(): boolean {\n return this.status === JobStatus.running\n }\n\n isSucceeded(): boolean {\n return this.status === JobStatus.succeeded\n }\n\n isFailed(): boolean {\n return this.status === JobStatus.failed\n }\n\n isCanceled(): boolean {\n return this.status === JobStatus.canceled\n }\n\n isEnded(): boolean {\n return [JobStatus.succeeded, JobStatus.failed, JobStatus.canceled].includes(this.status)\n }\n\n hasErrors(): boolean {\n return Object.keys(this.errors).length > 0\n }\n\n protected getCurrentInnerJob(): JobBase<C, any> | undefined {\n return this.innerJobs[this.currentInnerJobIndex]\n }\n\n protected combineInnerJobsResults(): Record<string, any> {\n const results: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(results, innerJob.result ?? {}))\n return results\n }\n\n protected combineInnerJobsErrors(): Record<string, any> {\n const errors: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(errors, innerJob.errors ?? {}))\n return errors\n }\n\n async cancel(options: { canceledByAdmin?: boolean } = {}): Promise<void> {\n const { canceledByAdmin = false } = options\n if (this.isEnded()) return\n\n this.cancelRequested = true\n\n const currentInnerJob = this.getCurrentInnerJob()\n if (currentInnerJob?.isRunning()) {\n // the parent job status will be set to canceled when handling the canceled event of the inner job\n await currentInnerJob.cancel({ canceledByAdmin })\n return\n }\n // no inner job running (job without inner jobs, or between two inner jobs)\n this.canceledByAdmin = canceledByAdmin\n // release the resources (temp files/directories, streams) allocated before the cancellation\n await this.runBeforeEnd()\n await this.setStatus(JobStatus.canceled)\n }\n\n private isCancelRequestedOrNotRunning(): boolean {\n return this.cancelRequested || !this.isRunning()\n }\n\n /**\n * Runs beforeEnd only once (it can be called by cancel() and when the job execution ends).\n */\n private async runBeforeEnd(): Promise<void> {\n if (this.beforeEndCalled) return\n this.beforeEndCalled = true\n await this.beforeEnd()\n }\n\n async start(client: any = null): Promise<void> {\n this.logDebug('start')\n\n try {\n if (client) {\n await client.tx(async (tx: any) => {\n this.context.tx = tx\n await this.executeInTransaction()\n })\n } else {\n await this.executeInTransaction()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.setStatus(JobStatus.succeeded)\n }\n } catch (error: any) {\n // a job can fail while still pending (e.g. the transaction cannot be opened, or onStart fails)\n if (!this.cancelRequested && !this.isFailed() && !this.isCanceled()) {\n this.logError(error.stack ?? error)\n const { key, params } = this.getErrorInfo(error)\n this.addError({ error: { valid: false, errors: [{ key, params }] } })\n await this.setStatus(JobStatus.failed)\n }\n } finally {\n this.context.tx = undefined\n }\n }\n\n private async executeInTransaction(): Promise<void> {\n try {\n await this.onStart()\n\n const shouldExecute = await this.shouldExecute()\n if (shouldExecute) {\n if (this.innerJobs.length > 0) {\n await this.executeJobs()\n } else {\n await this.execute()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.beforeSuccess()\n }\n }\n } finally {\n // runs only if not already run by cancel()\n await this.runBeforeEnd()\n this.context.tx = undefined\n }\n\n if (this.isCancelRequestedOrNotRunning()) {\n this.throwError('jobCanceledOrErrorsFound')\n }\n }\n\n /**\n * Generates a plain JSON-serializable representation of the job, including its inner jobs.\n */\n toJSON(): JobSerialized<R> {\n const { errors, processed, result, status, total, type, userUuid, uuid } = this\n\n return {\n uuid,\n type,\n userUuid,\n surveyId: this.surveyId,\n innerJobs: this.innerJobs.map((job) => job.toJSON()),\n currentInnerJobIndex: this.currentInnerJobIndex,\n\n status,\n pending: this.isPending(),\n running: this.isRunning(),\n succeeded: this.isSucceeded(),\n canceled: this.isCanceled(),\n failed: this.isFailed(),\n ended: this.isEnded(),\n\n total,\n processed,\n progressPercent: this.calculateProgressPercent(),\n elapsedMillis: this.calculateElapsedMillis(),\n\n errors: this.isFailed() ? errors : undefined,\n result: this.isSucceeded() ? result : undefined,\n }\n }\n\n private async executeJobs(): Promise<void> {\n this.logDebug(`- ${this.total} inner jobs found`)\n\n for (let i = 0; i < this.innerJobs.length; i++) {\n this.logDebug(`- executing inner job ${i + 1}`)\n this.currentInnerJobIndex = i\n const currentInnerJob = this.innerJobs[i]\n if (currentInnerJob.context) {\n Object.assign(this.context, currentInnerJob.context)\n }\n currentInnerJob.context = this.context\n currentInnerJob.onEvent((event) => {\n // handle the inner job events in sequence; errors are logged (they would be unhandled rejections otherwise)\n this.innerJobEventsQueue = this.innerJobEventsQueue\n .then(() => this.onInnerJobEvent(event))\n .catch((error) => this.logError(error?.stack ?? error))\n })\n\n // The inner job shares this very context object, and its own start()/executeInTransaction()\n // clear `context.tx` when they terminate: without saving and restoring it here, the first\n // inner job would wipe the parent's transaction handle, leaving every following inner job\n // (and the parent's own beforeSuccess()/beforeEnd()) running outside of the transaction.\n // start() never throws (it swallows/records errors internally), so a plain restore is enough.\n const parentTx = this.context.tx\n await currentInnerJob.start(parentTx)\n this.context.tx = parentTx\n // the inner job events (e.g. canceled, failed) update the status of this job\n await this.innerJobEventsQueue\n\n if (this.cancelRequested || this.isCanceled() || currentInnerJob.isCanceled()) {\n break\n }\n if (currentInnerJob.isSucceeded()) {\n this.incrementProcessedItems()\n } else if (this.stopOnInnerJobFailure) {\n break\n }\n }\n\n this.logDebug(`- ${this.processed} inner jobs processed successfully`)\n }\n\n /**\n * Runs the job's own work when it has no inner jobs. Default implementation is a no-op, so\n * subclasses that only supply inner jobs (and never override this) don't need to. It also means\n * a subclass can safely call `super.execute()` defensively without knowing whether any ancestor\n * overrides it - if this were `abstract` instead, TypeScript would compile away any runtime\n * property for it entirely, so `super.execute()` would throw the moment no ancestor overrides it\n * (confirmed in production: a subclass whose immediate parent didn't override `execute()` crashed\n * with \"(intermediate value).execute is not a function\" the instant it called `super.execute()`).\n */\n protected async execute(): Promise<void> {\n // to be extended by subclasses\n }\n\n /**\n * Determines whether the job should actually run.\n * When it returns false, \"execute\" (or the inner jobs) will be skipped, but the job will still succeed.\n */\n protected shouldExecute(): Promise<boolean> {\n return Promise.resolve(true)\n }\n\n protected incrementProcessedItems(incrementBy = 1): void {\n this.processed += incrementBy\n }\n\n protected async setStatus(status: JobStatus): Promise<void> {\n this.logDebug(`set status: ${status}`)\n this.status = status\n\n const event: JobEvent = { type: JobEventType.statusChange, status, total: this.total, processed: this.processed }\n if (status === JobStatus.failed) {\n event.errors = this.errors\n }\n\n if (this.isEnded()) {\n this.logDebug('onEnd...')\n await this.onEnd()\n this.logDebug(`onEnd run. Job completed in ${this.elapsedTimePrettyFormat}`)\n }\n\n this.notifyEvent(event)\n }\n\n /**\n * Inner job event handler.\n */\n protected async onInnerJobEvent(event: JobEvent): Promise<void> {\n const { status } = event\n if (status === JobStatus.canceled) {\n this.canceledByAdmin = this.getCurrentInnerJob()?.canceledByAdmin ?? false\n return this.setStatus(status)\n }\n if (status === JobStatus.failed) {\n // report the errors of the failed inner job in the failed event (and in the errors) of this job\n Object.assign(this.errors, this.getCurrentInnerJob()?.errors ?? {})\n return this.setStatus(status)\n }\n if (status === JobStatus.running) {\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n return\n }\n this.logDebug(`Unknown inner job status: ${status}`)\n }\n\n /**\n * Called when the job just has been started.\n */\n protected async onStart(): Promise<void> {\n this.startTime = new Date()\n await this.setStatus(JobStatus.running)\n }\n\n /**\n * Called before beforeEnd only if the status will change to 'success'.\n * Default implementation stores the value returned by generateResult() via setResult().\n * It runs INSIDE the current db transaction.\n */\n protected async beforeSuccess(): Promise<void> {\n this.setResult(await this.generateResult())\n }\n\n /**\n * Computes the value beforeSuccess() will store as this job's result.\n * Default implementation returns whatever is already in `this.result`\n * (e.g. accumulated via earlier setResult() calls during execute()).\n */\n protected generateResult(): Promise<R | undefined> {\n return Promise.resolve(this.result)\n }\n\n /**\n * Updates this job's result. When both the current and incoming values are plain objects,\n * they are merged (Object.assign); otherwise the incoming value replaces the current one.\n * This keeps it safe for subclasses whose result is a primitive (e.g. a plain number) as\n * well as ones that build an object result incrementally across multiple setResult() calls.\n */\n protected setResult(result: R | undefined): void {\n if (result && typeof result === 'object' && this.result && typeof this.result === 'object') {\n Object.assign(this.result, result)\n } else {\n this.result = result\n }\n }\n\n /**\n * Called before onEnd. Useful for flushing resources used by the job before it terminates completely.\n * It runs INSIDE the current db transaction.\n */\n protected beforeEnd(): Promise<void> {\n this.logDebug('Cleanup')\n return Promise.resolve()\n }\n\n /**\n * Called when the job status changes to success, failed or canceled\n * (it runs OUTSIDE of the current db transaction)\n */\n protected onEnd(): Promise<void> {\n this.endTime = new Date()\n this.cancelNotifyProgress()\n return Promise.resolve()\n }\n\n protected addError(error: any, errorKey?: string): void {\n const key = errorKey ?? String(this.processed + 1)\n this.errors[key] = error\n }\n\n protected throwError(errorKey: string, params?: Dictionary<any>): void {\n // SystemError: getErrorInfo will report the translatable key instead of a generic error\n throw new SystemError(errorKey, params)\n }\n\n protected getErrorInfo(error: any): { key: string; params: Record<string, any> } {\n if (error instanceof SystemError) {\n return { key: `appErrors:${error.key}`, params: error.params }\n }\n return { key: 'appErrors:generic', params: { text: error.toString() } }\n }\n\n protected abstract createLogger(): Logger\n\n protected logDebug(...msgs: any[]): void {\n this.logger.debug(...msgs)\n }\n\n protected logInfo(...msgs: any[]): void {\n this.logger.info(...msgs)\n }\n\n protected logWarn(...msgs: any[]): void {\n this.logger.warn(...msgs)\n }\n\n protected logError(...msgs: any[]): void {\n this.logger.error(...msgs)\n }\n\n private get elapsedTimePrettyFormat(): string {\n const elapsedTime = this.calculateElapsedMillis()\n const elapsedMins = Math.floor(elapsedTime / 1000 / 60)\n const elapsedSeconds = String(Math.floor(elapsedTime / 1000) % 60).padStart(2, '0')\n const elapsedMillis = String(elapsedTime % 1000).padStart(3, '0')\n return `${elapsedMins}:${elapsedSeconds}.${elapsedMillis}`\n }\n\n private calculatePartialProgress(): number {\n if (this.isSucceeded()) return 100\n if (this.total > 0) return Math.floor((100 * this.processed) / this.total)\n return 0\n }\n\n private calculateProgressPercent(): number {\n const partialProgress = this.calculatePartialProgress()\n const currentInnerJob = this.getCurrentInnerJob()\n if (\n !currentInnerJob ||\n this.currentInnerJobIndex < 0 ||\n partialProgress === 100 ||\n this.processed > this.currentInnerJobIndex\n ) {\n return partialProgress\n }\n return partialProgress + Math.floor(currentInnerJob.calculateProgressPercent() / this.total)\n }\n\n private calculateElapsedMillis(): number {\n if (!this.startTime) return 0\n return (this.endTime ?? new Date()).getTime() - this.startTime.getTime()\n }\n\n /**\n * Notifies a progress event to the registered listener, throttled so that fast-changing\n * progress does not flood consumers (e.g. web socket clients).\n */\n private notifyProgress(): void {\n const run = (): void => {\n this.progressThrottleTimeoutId = undefined\n this.progressThrottleLastRunTime = Date.now()\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n }\n\n if (this.progressThrottleTimeoutId) return\n\n const elapsed = Date.now() - this.progressThrottleLastRunTime\n if (!this.progressThrottleLastRunTime || elapsed >= PROGRESS_NOTIFICATION_THROTTLE_MILLIS) {\n run()\n } else {\n this.progressThrottleTimeoutId = setTimeout(run, PROGRESS_NOTIFICATION_THROTTLE_MILLIS - elapsed)\n }\n }\n\n /**\n * Cancels any pending throttled progress notification and resets the throttle state.\n */\n private cancelNotifyProgress(): void {\n if (this.progressThrottleTimeoutId) {\n clearTimeout(this.progressThrottleTimeoutId)\n this.progressThrottleTimeoutId = undefined\n }\n this.progressThrottleLastRunTime = 0\n }\n\n /**\n * Notifies the event to the registered listener.\n * Listener errors are only logged: they would otherwise fail the job or, when thrown inside the progress\n * throttle timeout, crash the process.\n */\n private notifyEvent(event: JobEvent): void {\n const listener = this.eventListener\n if (!listener) return\n try {\n Promise.resolve(listener(event)).catch((error) => this.logListenerError(error))\n } catch (error) {\n this.logListenerError(error)\n }\n }\n\n private logListenerError(error: any): void {\n this.logError(`error in job event listener: ${error?.stack ?? error}`)\n }\n}\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { NodeDef, NodeDefProps, NodeDefType } from '../../nodeDef';
|
|
2
|
+
import { SurveyDependencyType } from '../../survey/survey';
|
|
3
|
+
export declare const NodeDefSelfReferences: {
|
|
4
|
+
isSelfReferenceLocal: (params: {
|
|
5
|
+
nodeDef: NodeDef<NodeDefType, NodeDefProps>;
|
|
6
|
+
dependencyType: SurveyDependencyType;
|
|
7
|
+
}) => boolean;
|
|
8
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.NodeDefSelfReferences = void 0;
|
|
4
|
+
const expression_1 = require("../../expression");
|
|
5
|
+
const evaluator_1 = require("../../expression/javascript/evaluator");
|
|
6
|
+
const nodeDef_1 = require("../../nodeDef");
|
|
7
|
+
const survey_1 = require("../../survey/survey");
|
|
8
|
+
/**
|
|
9
|
+
* True if the identifier is used as (or inside) the property of a member expression (e.g. "dbh" in
|
|
10
|
+
* "parent(tree).tree.dbh" or in "tree[dbh > 10]"): there it can refer to nodes outside the context entity.
|
|
11
|
+
*/
|
|
12
|
+
const isReferencedThroughMember = (params) => {
|
|
13
|
+
const { expressionNode, name, inMemberProperty } = params;
|
|
14
|
+
if (!expressionNode || typeof expressionNode !== 'object')
|
|
15
|
+
return false;
|
|
16
|
+
if (Array.isArray(expressionNode)) {
|
|
17
|
+
return expressionNode.some((item) => isReferencedThroughMember({ expressionNode: item, name, inMemberProperty }));
|
|
18
|
+
}
|
|
19
|
+
const { type } = expressionNode;
|
|
20
|
+
if (type === expression_1.ExpressionNodeType.Identifier) {
|
|
21
|
+
return inMemberProperty && expressionNode.name === name;
|
|
22
|
+
}
|
|
23
|
+
if (type === expression_1.ExpressionNodeType.Member) {
|
|
24
|
+
const { object, property } = expressionNode;
|
|
25
|
+
return (isReferencedThroughMember({ expressionNode: object, name, inMemberProperty }) ||
|
|
26
|
+
isReferencedThroughMember({ expressionNode: property, name, inMemberProperty: true }));
|
|
27
|
+
}
|
|
28
|
+
return Object.values(expressionNode).some((child) => isReferencedThroughMember({ expressionNode: child, name, inMemberProperty }));
|
|
29
|
+
};
|
|
30
|
+
const isExpressionSelfReferenceLocal = (params) => {
|
|
31
|
+
const { expression, name } = params;
|
|
32
|
+
if (!expression)
|
|
33
|
+
return true;
|
|
34
|
+
try {
|
|
35
|
+
return !isReferencedThroughMember({ expressionNode: (0, evaluator_1.parseExpression)(expression), name, inMemberProperty: false });
|
|
36
|
+
}
|
|
37
|
+
catch (_a) {
|
|
38
|
+
// invalid expression: be conservative
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Returns true if the node def references itself in its expressions of the specified dependency type only
|
|
44
|
+
* as a plain identifier (e.g. "dbh > 0" in a validation of "dbh"): such a reference is resolved among the
|
|
45
|
+
* children of the node's parent entity, so only the node and its siblings depend on it, not every node with
|
|
46
|
+
* the same node def in the record.
|
|
47
|
+
*/
|
|
48
|
+
const isSelfReferenceLocal = (params) => {
|
|
49
|
+
const { nodeDef, dependencyType } = params;
|
|
50
|
+
// self references by plain identifier are allowed only in validation expressions (see dependencies.ts)
|
|
51
|
+
if (dependencyType !== survey_1.SurveyDependencyType.validations)
|
|
52
|
+
return false;
|
|
53
|
+
const name = nodeDef_1.NodeDefs.getName(nodeDef);
|
|
54
|
+
return nodeDef_1.NodeDefs.getValidationsExpressions(nodeDef).every(({ expression, applyIf }) => isExpressionSelfReferenceLocal({ expression, name }) &&
|
|
55
|
+
isExpressionSelfReferenceLocal({ expression: applyIf, name }));
|
|
56
|
+
};
|
|
57
|
+
exports.NodeDefSelfReferences = {
|
|
58
|
+
isSelfReferenceLocal,
|
|
59
|
+
};
|
|
60
|
+
//# sourceMappingURL=nodeDefSelfReferences.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nodeDefSelfReferences.js","sourceRoot":"","sources":["../../../src/record/_records/nodeDefSelfReferences.ts"],"names":[],"mappings":";;;AAAA,iDAA6G;AAC7G,qEAAuE;AACvE,2CAA4E;AAC5E,gDAA0D;AAE1D;;;GAGG;AACH,MAAM,yBAAyB,GAAG,CAAC,MAIlC,EAAW,EAAE;IACZ,MAAM,EAAE,cAAc,EAAE,IAAI,EAAE,gBAAgB,EAAE,GAAG,MAAM,CAAA;IACzD,IAAI,CAA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AAE,IAAA,2BAAe,EAAC,UAAU,CAAC,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,CAAC,CAAA;IACnH,CAAC;IAAC,WAAM,CAAC;QACP,sCAAsC;QACtC,OAAO,KAAK,CAAA;IACd,CAAC;AACH,CAAC,CAAA;AAED;;;;;GAKG;AACH,MAAM,oBAAoB,GAAG,CAAC,MAG7B,EAAW,EAAE;IACZ,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,MAAM,CAAA;IAC1C,uGAAuG;IACvG,IAAI,cAAc,KAAK,6BAAoB,CAAC,WAAW;QAAE,OAAO,KAAK,CAAA;IACrE,MAAM,IAAI,GAAG,kBAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;IACtC,OAAO,kBAAQ,CAAC,yBAAyB,CAAC,OAAO,CAAC,CAAC,KAAK,CACtD,CAAC,EAAE,UAAU,EAAE,OAAO,EAAE,EAAE,EAAE,CAC1B,8BAA8B,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;QACpD,8BAA8B,CAAC,EAAE,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAChE,CAAA;AACH,CAAC,CAAA;AAEY,QAAA,qBAAqB,GAAG;IACnC,oBAAoB;CACrB,CAAA","sourcesContent":["import { ExpressionNode, ExpressionNodeType, IdentifierExpression, MemberExpression } from '../../expression'\nimport { parseExpression } from '../../expression/javascript/evaluator'\nimport { NodeDef, NodeDefProps, NodeDefs, NodeDefType } from '../../nodeDef'\nimport { SurveyDependencyType } from '../../survey/survey'\n\n/**\n * True if the identifier is used as (or inside) the property of a member expression (e.g. \"dbh\" in\n * \"parent(tree).tree.dbh\" or in \"tree[dbh > 10]\"): there it can refer to nodes outside the context entity.\n */\nconst isReferencedThroughMember = (params: {\n expressionNode: unknown\n name: string\n inMemberProperty: boolean\n}): boolean => {\n const { expressionNode, name, inMemberProperty } = params\n if (!expressionNode || typeof expressionNode !== 'object') return false\n if (Array.isArray(expressionNode)) {\n return expressionNode.some((item) => isReferencedThroughMember({ expressionNode: item, name, inMemberProperty }))\n }\n const { type } = expressionNode as ExpressionNode<ExpressionNodeType>\n if (type === ExpressionNodeType.Identifier) {\n return inMemberProperty && (expressionNode as IdentifierExpression).name === name\n }\n if (type === ExpressionNodeType.Member) {\n const { object, property } = expressionNode as MemberExpression\n return (\n isReferencedThroughMember({ expressionNode: object, name, inMemberProperty }) ||\n isReferencedThroughMember({ expressionNode: property, name, inMemberProperty: true })\n )\n }\n return Object.values(expressionNode).some((child) =>\n isReferencedThroughMember({ expressionNode: child, name, inMemberProperty })\n )\n}\n\nconst isExpressionSelfReferenceLocal = (params: { expression: string | undefined; name: string }): boolean => {\n const { expression, name } = params\n if (!expression) return true\n try {\n return !isReferencedThroughMember({ expressionNode: parseExpression(expression), name, inMemberProperty: false })\n } catch {\n // invalid expression: be conservative\n return false\n }\n}\n\n/**\n * Returns true if the node def references itself in its expressions of the specified dependency type only\n * as a plain identifier (e.g. \"dbh > 0\" in a validation of \"dbh\"): such a reference is resolved among the\n * children of the node's parent entity, so only the node and its siblings depend on it, not every node with\n * the same node def in the record.\n */\nconst isSelfReferenceLocal = (params: {\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n dependencyType: SurveyDependencyType\n}): boolean => {\n const { nodeDef, dependencyType } = params\n // self references by plain identifier are allowed only in validation expressions (see dependencies.ts)\n if (dependencyType !== SurveyDependencyType.validations) return false\n const name = NodeDefs.getName(nodeDef)\n return NodeDefs.getValidationsExpressions(nodeDef).every(\n ({ expression, applyIf }) =>\n isExpressionSelfReferenceLocal({ expression, name }) &&\n isExpressionSelfReferenceLocal({ expression: applyIf, name })\n )\n}\n\nexport const NodeDefSelfReferences = {\n isSelfReferenceLocal,\n}\n"]}
|
|
@@ -11,6 +11,7 @@ const utils_1 = require("../../utils");
|
|
|
11
11
|
const record_1 = require("../record");
|
|
12
12
|
const recordStep_1 = require("../recordStep");
|
|
13
13
|
const recordNodesIndexReader_1 = require("./recordNodesIndexReader");
|
|
14
|
+
const nodeDefSelfReferences_1 = require("./nodeDefSelfReferences");
|
|
14
15
|
const getCycle = (record) => { var _a; return (_a = record.cycle) !== null && _a !== void 0 ? _a : survey_1.defaultCycle; };
|
|
15
16
|
exports.getCycle = getCycle;
|
|
16
17
|
const getNodes = (record) => { var _a; return (_a = record.nodes) !== null && _a !== void 0 ? _a : {}; };
|
|
@@ -227,12 +228,15 @@ const findDescendantOrSelf = (node, predicate) => (record) => {
|
|
|
227
228
|
};
|
|
228
229
|
exports.findDescendantOrSelf = findDescendantOrSelf;
|
|
229
230
|
const getClosestAncestorNode = (params) => {
|
|
230
|
-
const { record, node, nodeDef, dependentDef } = params;
|
|
231
|
+
const { record, node, nodeDef, dependentDef, dependencyType } = params;
|
|
231
232
|
// 1a if dependent def is the same as node def, potentially all nodes with
|
|
232
233
|
// nodeDefUuid === dependentDef.uuid in record could be dependent of nodeDef;
|
|
233
|
-
// consider the root node as the closest ancestor node
|
|
234
|
+
// consider the root node as the closest ancestor node,
|
|
235
|
+
// unless the node def references itself only among the children of its parent entity (e.g. validation "dbh > 0")
|
|
234
236
|
if (nodeDef.uuid === dependentDef.uuid) {
|
|
235
|
-
return (
|
|
237
|
+
return nodeDefSelfReferences_1.NodeDefSelfReferences.isSelfReferenceLocal({ nodeDef, dependencyType })
|
|
238
|
+
? (0, exports.getParent)(node)(record)
|
|
239
|
+
: (0, exports.getRoot)(record);
|
|
236
240
|
}
|
|
237
241
|
// 1 find common ancestor def
|
|
238
242
|
const commonAncestorDefUuid = utils_1.Arrays.last(utils_1.Arrays.intersection(nodeDef.meta.h, dependentDef.meta.h));
|
|
@@ -370,7 +374,7 @@ const getDependentNodePointers = (params) => {
|
|
|
370
374
|
};
|
|
371
375
|
for (const dependentDef of dependentDefs) {
|
|
372
376
|
// 1 find common ancestor node
|
|
373
|
-
const commonAncestorNode = getClosestAncestorNode({ record, node, nodeDef, dependentDef });
|
|
377
|
+
const commonAncestorNode = getClosestAncestorNode({ record, node, nodeDef, dependentDef, dependencyType });
|
|
374
378
|
if (!commonAncestorNode)
|
|
375
379
|
continue;
|
|
376
380
|
const nodeDefDependentParent = survey_1.Surveys.getNodeDefParent({ survey, nodeDef: dependentDef });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recordGetters.js","sourceRoot":"","sources":["../../../src/record/_records/recordGetters.ts"],"names":[],"mappings":";;;AAAA,yCAAyD;AACzD,uCAAyC;AACzC,qCAA+D;AAC/D,sDAAkD;AAClD,2CAA2G;AAC3G,yCAAoD;AAEpD,uCAA2C;AAC3C,sCAAuD;AACvD,8CAAsD;AACtD,qEAAiE;AAE1D,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAU,EAAE,WAAC,OAAA,MAAA,MAAM,CAAC,KAAK,mCAAI,qBAAY,CAAA,EAAA,CAAA;AAAnE,QAAA,QAAQ,YAA2D;AAEzE,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAoB,EAAE,WAAC,OAAA,MAAA,MAAM,CAAC,KAAK,mCAAI,EAAE,CAAA,EAAA,CAAA;AAAnE,QAAA,QAAQ,YAA2D;AAEzE,MAAM,aAAa,GAAG,CAAC,MAAc,EAAU,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAA,gBAAQ,EAAC,MAAM,CAAC,CAAC,CAAA;AAA3E,QAAA,aAAa,iBAA8D;AAEjF,MAAM,aAAa,GACxB,CAAC,IAAY,EAAE,EAAE,CACjB,CAAC,MAAc,EAAoB,EAAE,WACnC,OAAA,MAAA,MAAM,CAAC,KAAK,0CAAG,IAAI,CAAC,CAAA,EAAA,CAAA;AAHX,QAAA,aAAa,iBAGF;AAEjB,MAAM,eAAe,GAC1B,CAAC,KAAe,EAAE,EAAE,CACpB,CAAC,MAAc,EAAU,EAAE,CACzB,KAAK,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,qBAAa,EAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAW,CAAA;AAH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B,uBAe/B;AAEM,MAAM,kBAAkB,GAC7B,CAAC,IAAU,EAAE,EAAE,CACf,CAAC,MAAc,EAAW,EAAE,CAC1B,CAAC,CAAC,IAAA,4BAAoB,EAAC,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,YAAK,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAA;AAHlF,QAAA,kBAAkB,sBAGgE;AAExF,MAAM,WAAW,GACtB,CAAC,IAAU,EAAE,EAAE,CACf,CAAC,MAAc,EAAW,EAAE,CAC1B,CAAC,IAAA,0BAAkB,EAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAA;AAHxB,QAAA,WAAW,eAGa;AAE9B,MAAM,OAAO,GAAG,CAAC,MAAc,EAAW,EAAE;IACjD,MAAM,QAAQ,GAAG,IAAA,eAAO,EAAC,MAAM,CAAC,CAAA;IAChC,OAAO,QAAQ,CAAC,CAAC,CAAC,IAAA,mBAAW,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;AACxD,CAAC,CAAA;AAHY,QAAA,OAAO,WAGnB;AAEM,MAAM,OAAO,GAAG,CAAC,MAAc,EAAU,EAAE,WAAC,OAAA,MAAA,MAAM,CAAC,IAAI,mCAAI,4BAAmB,CAAA,EAAA,CAAA;AAAxE,QAAA,OAAO,WAAiE;AAE9E,MAAM,gBAAgB,GAAG,CAAC,MAAc,EAAW,EAAE,CAAC,IAAA,eAAO,EAAC,MAAM,CAAC,KAAK,mCAAsB,CAAA;AAA1F,QAAA,gBAAgB,oBAA0E","sourcesContent":["import { Dictionary, TraverseMethod } from '../../common'\nimport { SystemError } from '../../error'\nimport { Node, NodePointer, Nodes, NodesMap } from '../../node'\nimport { NodeValues } from '../../node/nodeValues'\nimport { NodeDef, NodeDefCode, NodeDefCodeProps, NodeDefProps, NodeDefs, NodeDefType } from '../../nodeDef'\nimport { defaultCycle, Surveys } from '../../survey'\nimport { Survey, SurveyDependencyType } from '../../survey/survey'\nimport { Arrays, Queue } from '../../utils'\nimport { Record, RECORD_STEP_DEFAULT } from '../record'\nimport { RecordStepAnalysisCode } from '../recordStep'\nimport { RecordNodesIndexReader } from './recordNodesIndexReader'\n\nexport const getCycle = (record: Record): string => record.cycle ?? defaultCycle\n\nexport const getNodes = (record: Record): Dictionary<Node> => record.nodes ?? {}\n\nexport const getNodesArray = (record: Record): Node[] => Object.values(getNodes(record))\n\nexport const getNodeByUuid =\n (uuid: string) =>\n (record: Record): Node | undefined =>\n record.nodes?.[uuid]\n\nexport const getNodesByUuids =\n (uuids: string[]) =>\n (record: Record): Node[] =>\n uuids.map((uuid: string) => getNodeByUuid(uuid)(record)) as Node[]\n\nexport const getRoot = (record: Record): Node | undefined => {\n const rootUuid = record._nodesIndex ? RecordNodesIndexReader.getNodeRootUuid(record._nodesIndex) : null\n if (rootUuid) {\n return getNodeByUuid(rootUuid)(record)\n }\n return getNodesArray(record).find((node) => !node.parentUuid)\n}\n\nexport const getChildren =\n (parentNode: Node, childDefUuid?: string) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const childrenUuids = childDefUuid\n ? RecordNodesIndexReader.getNodeUuidsByParentAndChildDef({\n parentNodeUuid: parentNode.uuid,\n childDefUuid,\n })(record._nodesIndex)\n : RecordNodesIndexReader.getNodeUuidsByParent(parentNode.uuid)(record._nodesIndex)\n return getNodesByUuids(childrenUuids)(record)\n }\n return getNodesArray(record).filter(\n (node) => node.parentUuid === parentNode.uuid && (!childDefUuid || node.nodeDefUuid == childDefUuid)\n )\n }\n\nexport const getChild =\n (parentNode: Node, childDefUuid: string) =>\n (record: Record): Node => {\n const children = getChildren(parentNode, childDefUuid)(record)\n const errorParams = { childDefUuid, parentNodeUuid: parentNode.uuid, recordUuid: record.uuid }\n if (children.length === 1) {\n return children[0]\n }\n if (children.length > 1) {\n throw new SystemError('systemError.record.multipleNodesFound', errorParams)\n }\n throw new SystemError('systemError.record.childNotFound', errorParams)\n }\n\nexport const getParent =\n (node: Node) =>\n (record: Record): Node | undefined =>\n node.parentUuid ? getNodeByUuid(node.parentUuid)(record) : undefined\n\nexport const getNodesByDefUuid =\n (nodeDefUuid: string) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeUuidsByDef(nodeDefUuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n return getNodesArray(record).filter((node) => node.nodeDefUuid === nodeDefUuid)\n }\n\nconst isNodeFlagTrue =\n (isChildFlagTrue: (parent: Node, nodeDefUuid: string) => boolean) =>\n (params: { record: Record; node: Node }): boolean => {\n const { record, node } = params\n const ancestorsAndSelf = getAncestorsAndSelf({ record, node })\n for (let i = 0; i < ancestorsAndSelf.length - 1; i++) {\n const child = ancestorsAndSelf[i]\n const parent = ancestorsAndSelf[i + 1]\n if (!isChildFlagTrue(parent, child.nodeDefUuid)) return false\n }\n return true\n }\n\nexport const isNodeApplicable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildApplicable(parent, nodeDefUuid))\nexport const isNodeEditable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildEditable(parent, nodeDefUuid))\nexport const isNodeVisible = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildVisible(parent, nodeDefUuid))\n\nexport const getDependentCodeAttributes =\n (node: Node) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeCodeDependentUuids(node.uuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n throw new SystemError('record.nodesIndexNotInitialized')\n }\n\nexport const getParentCodeAttribute =\n (params: { parentNode: Node; nodeDef: NodeDefCode }) =>\n (record: Record): Node | undefined => {\n const { parentNode, nodeDef } = params\n\n const parentCodeDefUuid = NodeDefs.getParentCodeDefUuid(nodeDef)\n if (!parentCodeDefUuid) return undefined\n\n const ancestors = getAncestorsAndSelf({ record, node: parentNode })\n for (const ancestor of ancestors) {\n const children = getChildren(ancestor, parentCodeDefUuid)(record)\n if (children.length === 1) {\n return children[0]\n }\n }\n return undefined\n }\n\n// ancestors\nexport const visitAncestorsAndSelf =\n (node: Node, visitor: (node: Node) => void, stopIfFn?: () => boolean) =>\n (record: Record): void => {\n let currentNode: Node | undefined = node\n while (currentNode) {\n visitor(currentNode)\n if (stopIfFn?.()) break\n currentNode = getParent(currentNode)(record)\n }\n }\n\nexport const findAncestor =\n (node: Node, predicate: (node: Node) => boolean) =>\n (record: Record): Node | undefined => {\n let result: Node | undefined = undefined\n visitAncestorsAndSelf(\n node,\n (visitedNode) => {\n if (predicate(visitedNode)) {\n result = visitedNode\n }\n },\n () => !!result\n )(record)\n return result\n }\n\nexport const getAncestor = (params: { record: Record; node: Node; ancestorDefUuid: string }): Node | undefined => {\n const { record, node, ancestorDefUuid } = params\n if (node.nodeDefUuid === ancestorDefUuid) return node\n\n let ancestor = getParent(node)(record)\n while (ancestor && ancestor.nodeDefUuid !== ancestorDefUuid) {\n ancestor = getParent(ancestor)(record)\n }\n return ancestor\n}\n\n/**\n * Returns the list of ancestors from the given node to the root entity\n */\nexport const getAncestorsAndSelf = (params: { record: Record; node: Node }): Array<Node> => {\n const { record, node } = params\n const ancestors: Array<Node> = []\n visitAncestorsAndSelf(node, (currentNode) => {\n ancestors.push(currentNode)\n })(record)\n return ancestors\n}\n\n// descendants\n\nexport const getDescendantsOrSelf = (params: {\n record: Record\n node: Node\n nodeDefDescendant: NodeDef<any>\n}): Node[] => {\n const { record, node, nodeDefDescendant } = params\n\n if (nodeDefDescendant.uuid === node.nodeDefUuid) return [node]\n\n const nodeDefDescendantFullHierarchy = [...nodeDefDescendant.meta.h, nodeDefDescendant.uuid]\n\n // 1. get the descendant node defs uuids starting from node nodeDefUuid (not inclusive) down to the specified nodeDefDescendant uuid\n const descendantNodeDefUuids = nodeDefDescendantFullHierarchy.slice(\n nodeDefDescendantFullHierarchy.indexOf(node.nodeDefUuid) + 1\n )\n // 2. for every level in the hierarchy, find the children having the nodeDefUuid equal to the current one\n let currentAncestors = [node]\n let currentDescendants: Node[] = []\n for (const currentDescendantDefUuid of descendantNodeDefUuids) {\n for (const currentAncestor of currentAncestors) {\n currentDescendants.push(...getChildren(currentAncestor, currentDescendantDefUuid)(record))\n }\n currentAncestors = currentDescendants\n currentDescendants = []\n }\n return currentAncestors // currentAncestors is equal to the currentDescendants of the last level\n}\n\nexport const getDescendant = (params: { record: Record; node: Node; nodeDefDescendant: NodeDef<any> }): Node => {\n const { record, node, nodeDefDescendant } = params\n\n return getDescendantsOrSelf({ record, node, nodeDefDescendant })[0]\n}\n\nexport const isDescendantOf = (params: { node: Node; ancestor: Node }): boolean => {\n const { node, ancestor } = params\n return Nodes.getHierarchy(node).includes(ancestor.uuid)\n}\n\nexport const visitDescendantsAndSelf = (params: {\n record: Record\n node: Node\n visitor: (node: Node) => boolean | void\n traverseMethod?: TraverseMethod\n}): void => {\n const { record, node, visitor, traverseMethod = TraverseMethod.bfs } = params\n\n if (traverseMethod === TraverseMethod.bfs) {\n const queue = new Queue()\n\n queue.enqueue(node)\n\n while (!queue.isEmpty()) {\n const visitedNode = queue.dequeue()\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n queue.enqueueItems(children)\n }\n } else {\n const stack = []\n\n stack.push(node)\n\n while (stack.length > 0) {\n const visitedNode = stack.pop() as Node\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n\n // add children to stack in reverse order\n for (let index = children.length - 1; index >= 0; index--) {\n const child = children[index]\n stack.push(child)\n }\n }\n }\n}\n\nexport const findDescendantOrSelf =\n (node: Node, predicate: (node: Node) => boolean) =>\n (record: Record): Node | undefined => {\n let found = undefined\n\n visitDescendantsAndSelf({\n record,\n node,\n visitor: (currentNode) => {\n if (predicate(currentNode)) {\n found = currentNode\n return true\n }\n return false\n },\n })\n return found\n }\n\nconst getClosestAncestorNode = (params: {\n record: Record\n node: Node\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n dependentDef: NodeDef<NodeDefType, NodeDefProps>\n}): Node | undefined => {\n const { record, node, nodeDef, dependentDef } = params\n\n // 1a if dependent def is the same as node def, potentially all nodes with\n // nodeDefUuid === dependentDef.uuid in record could be dependent of nodeDef;\n // consider the root node as the closest ancestor node\n if (nodeDef.uuid === dependentDef.uuid) {\n return getRoot(record)\n }\n // 1 find common ancestor def\n const commonAncestorDefUuid = Arrays.last(Arrays.intersection(nodeDef.meta.h, dependentDef.meta.h))\n if (!commonAncestorDefUuid) return undefined\n\n // 2 get ancestor node with common parent def\n return getAncestor({ record, node, ancestorDefUuid: commonAncestorDefUuid })\n}\n\ntype EntityKeyNodesGetterParams = {\n survey: Survey\n cycle?: string\n record: Record\n entity: Node\n keyDefs?: NodeDef<NodeDefType, NodeDefProps>[]\n}\n\nexport const getEntityKeyNodesByDefUuid = (params: EntityKeyNodesGetterParams): NodesMap => {\n const { survey, cycle, record, entity, keyDefs } = params\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: entity.nodeDefUuid })\n const nodeDefKeys = keyDefs ?? Surveys.getNodeDefKeys({ survey, cycle, nodeDef })\n return nodeDefKeys.reduce((acc: NodesMap, nodeDefKey) => {\n const nodeKey = getDescendant({ record, node: entity, nodeDefDescendant: nodeDefKey })\n acc[nodeDefKey.uuid] = nodeKey\n return acc\n }, {})\n}\n\nexport const getEntityKeyNodes = (params: EntityKeyNodesGetterParams): Node[] =>\n Object.values(getEntityKeyNodesByDefUuid(params))\n\nexport const getEntityKeyValuesByDefUuid = (params: EntityKeyNodesGetterParams): Dictionary<any> => {\n const keyNodesByDefUuid = getEntityKeyNodesByDefUuid(params)\n return Object.entries(keyNodesByDefUuid).reduce((acc: Dictionary<any>, [uuid, keyNode]) => {\n acc[uuid] = keyNode?.value\n return acc\n }, {})\n}\n\nexport const getEntityKeyValues = (params: EntityKeyNodesGetterParams): any[] =>\n Object.values(getEntityKeyValuesByDefUuid(params))\n\nexport const getEntitySiblings = (params: { record: Record; entity: Node; includeSelf?: boolean }) => {\n const { record, entity, includeSelf = false } = params\n const parentEntity = getParent(entity)(record)\n if (!parentEntity) return []\n const siblingEntities = getChildren(parentEntity, entity.nodeDefUuid)(record)\n return includeSelf ? siblingEntities : siblingEntities.filter((sibling) => !Nodes.areEqual(sibling, entity))\n}\n\nexport const getAttributeSiblings = (params: {\n record: Record\n node: Node\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n}) => {\n const { record, node, nodeDef } = params\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return []\n const siblingParentEntities = getEntitySiblings({ record, entity: parentEntity })\n return siblingParentEntities.reduce((siblingsAcc: Node[], siblingEntity) => {\n siblingsAcc.push(...getChildren(siblingEntity, nodeDef.uuid)(record))\n return siblingsAcc\n }, [])\n}\n\nexport const getNodeIndex = (params: { record: Record; node: Node }) => {\n const { record, node } = params\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return 0 // root entity\n const siblings = getChildren(parentEntity, node.nodeDefUuid)(record)\n return siblings.indexOf(node)\n}\n\nexport const findEntityByKeyValues = (params: {\n survey: Survey\n cycle: string\n record: Record\n parentEntity: Node\n entityDefUuid: string\n keyValuesByDefUuid: Dictionary<any>\n}): Node | undefined => {\n const { survey, cycle, record, parentEntity, entityDefUuid, keyValuesByDefUuid } = params\n const entityDef = Surveys.getNodeDefByUuid({ survey, uuid: entityDefUuid })\n const siblingEntities = getChildren(parentEntity, entityDefUuid)(record)\n if (NodeDefs.isSingle(entityDef)) {\n return siblingEntities[0]\n }\n const keyDefs = Surveys.getNodeDefKeys({ survey, cycle, nodeDef: entityDef })\n\n return siblingEntities.find((siblingEntity) => {\n const siblingEntityKeyValuesByDefUuid = getEntityKeyValuesByDefUuid({\n survey,\n record,\n entity: siblingEntity,\n keyDefs,\n })\n return keyDefs.every((keyDef) => {\n const keyValue = siblingEntityKeyValuesByDefUuid[keyDef.uuid]\n const keyValueSearch = keyValuesByDefUuid[keyDef.uuid]\n return NodeValues.isValueEqual({\n survey,\n nodeDef: keyDef,\n value: keyValue,\n valueSearch: keyValueSearch,\n })\n })\n })\n}\n\nexport const findEntityWithSameKeysInAnotherRecord = (params: {\n survey: Survey\n cycle: string\n entityUuid: string\n record: Record\n recordOther: Record\n}): Node | undefined => {\n const { survey, cycle, entityUuid, record, recordOther } = params\n const entity = getNodeByUuid(entityUuid)(record)\n if (!entity) return undefined\n\n let otherRecordCurrentParentEntity = getRoot(recordOther)\n if (!otherRecordCurrentParentEntity) return undefined\n\n const entityAncestorsAndSelf = getAncestorsAndSelf({\n record,\n node: entity,\n })\n const ancestorDefUuidsAndKeys = entityAncestorsAndSelf.map((ancestor) => ({\n entityDefUuid: ancestor.nodeDefUuid,\n keyValuesByDefUuid: getEntityKeyValuesByDefUuid({\n survey,\n record,\n entity: ancestor,\n }),\n }))\n\n const ancestorDefUuidsAndKeysToVisit = [...ancestorDefUuidsAndKeys].reverse()\n\n for (let index = 1; otherRecordCurrentParentEntity && index < ancestorDefUuidsAndKeysToVisit.length; index++) {\n const { entityDefUuid, keyValuesByDefUuid } = ancestorDefUuidsAndKeysToVisit[index]\n otherRecordCurrentParentEntity = findEntityByKeyValues({\n survey,\n cycle,\n record: recordOther,\n parentEntity: otherRecordCurrentParentEntity,\n entityDefUuid,\n keyValuesByDefUuid,\n })\n }\n return otherRecordCurrentParentEntity\n}\n\nexport const getDependentNodePointers = (params: {\n survey: Survey\n record: Record\n node: Node\n dependencyType: SurveyDependencyType\n includeSelf?: boolean\n filterFn?: (nodePointer: NodePointer) => boolean\n}) => {\n const { survey, record, node, dependencyType, includeSelf = false, filterFn = null } = params\n const nodeDefUuid = node.nodeDefUuid\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: nodeDefUuid })\n const dependentDefs = Surveys.getNodeDefDependents({ survey, nodeDefUuid, dependencyType })\n const nodePointers: Array<NodePointer> = []\n\n const addToNodePointers = (nodePointer: NodePointer): void => {\n if (filterFn === null || filterFn(nodePointer)) {\n nodePointers.push(nodePointer)\n }\n }\n\n for (const dependentDef of dependentDefs) {\n // 1 find common ancestor node\n const commonAncestorNode = getClosestAncestorNode({ record, node, nodeDef, dependentDef })\n if (!commonAncestorNode) continue\n\n const nodeDefDependentParent = Surveys.getNodeDefParent({ survey, nodeDef: dependentDef })\n if (!nodeDefDependentParent) throw new SystemError('record.nodes.dependents.dependencyOnRootFound')\n\n // 2 find descendant nodes of common parent node with nodeDefUuid = dependentDef uuid\n const dependentContextNodes = getDescendantsOrSelf({\n record,\n node: commonAncestorNode,\n nodeDefDescendant: nodeDefDependentParent,\n })\n\n for (const dependentContextNode of dependentContextNodes) {\n addToNodePointers({\n nodeCtx: dependentContextNode,\n nodeDef: dependentDef,\n })\n }\n }\n if (includeSelf) {\n const parentNode = getParent(node)(record)\n if (parentNode) {\n addToNodePointers({\n nodeCtx: parentNode,\n nodeDef,\n })\n }\n }\n\n return nodePointers\n}\n\nexport const getAncestorCodePath = (params: {\n survey: Survey\n record: Record\n parentNode: Node\n nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>\n}): string[] => {\n const { record, parentNode, nodeDef, survey } = params\n\n const getCodeAttributeItemCode = (codeAttribute: Node | undefined): string => {\n const codeItemUuid = codeAttribute ? NodeValues.getItemUuid(codeAttribute) : undefined\n if (!codeItemUuid) return ''\n const item = Surveys.getCategoryItemByUuid({ survey, itemUuid: codeItemUuid })\n return item?.props.code ?? ''\n }\n\n const codePaths = []\n let currentParentCodeAttribute = getParentCodeAttribute({ parentNode, nodeDef })(record)\n\n while (currentParentCodeAttribute) {\n const ancestorItemCode = getCodeAttributeItemCode(currentParentCodeAttribute)\n codePaths.unshift(ancestorItemCode)\n const ancestorCodeDef = Surveys.getNodeDefByUuid({\n survey,\n uuid: currentParentCodeAttribute.nodeDefUuid,\n }) as NodeDefCode\n currentParentCodeAttribute = getParentCodeAttribute({ parentNode, nodeDef: ancestorCodeDef })(record)\n }\n return codePaths\n}\n\nexport const getCategoryItemUuid = (params: {\n survey: Survey\n nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>\n record: Record\n parentNode: Node\n code: string\n}): string | undefined => {\n const { survey, nodeDef, record, parentNode, code } = params\n const categoryUuid = nodeDef.props.categoryUuid\n\n const codePaths = [...getAncestorCodePath({ survey, record, parentNode, nodeDef }), code]\n\n const item = Surveys.getCategoryItemByCodePaths({ survey, categoryUuid, codePaths })\n\n return item?.uuid\n}\n\nexport const isNodeFilledByUser =\n (node: Node) =>\n (record: Record): boolean =>\n !!findDescendantOrSelf(node, (visitedNode) => Nodes.hasUserInputValue(visitedNode))(record)\n\nexport const isNodeEmpty =\n (node: Node) =>\n (record: Record): boolean =>\n !isNodeFilledByUser(node)(record)\n\nexport const isEmpty = (record: Record): boolean => {\n const rootNode = getRoot(record)\n return rootNode ? isNodeEmpty(rootNode)(record) : true\n}\n\nexport const getStep = (record: Record): string => record.step ?? RECORD_STEP_DEFAULT\n\nexport const isInAnalysisStep = (record: Record): boolean => getStep(record) === RecordStepAnalysisCode\n"]}
|
|
1
|
+
{"version":3,"file":"recordGetters.js","sourceRoot":"","sources":["../../../src/record/_records/recordGetters.ts"],"names":[],"mappings":";;;AAAA,yCAAyD;AACzD,uCAAyC;AACzC,qCAA+D;AAC/D,sDAAkD;AAClD,2CAA2G;AAC3G,yCAAoD;AAEpD,uCAA2C;AAC3C,sCAAuD;AACvD,8CAAsD;AACtD,qEAAiE;AACjE,mEAA+D;AAExD,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAU,EAAE,WAAC,OAAA,MAAA,MAAM,CAAC,KAAK,mCAAI,qBAAY,CAAA,EAAA,CAAA;AAAnE,QAAA,QAAQ,YAA2D;AAEzE,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAoB,EAAE,WAAC,OAAA,MAAA,MAAM,CAAC,KAAK,mCAAI,EAAE,CAAA,EAAA,CAAA;AAAnE,QAAA,QAAQ,YAA2D;AAEzE,MAAM,aAAa,GAAG,CAAC,MAAc,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CAAC,CAAA;IAChC,OAAO,QAAQ,CAAC,CAAC,CAAC,IAAA,mBAAW,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;AACxD,CAAC,CAAA;AAHY,QAAA,OAAO,WAGnB;AAEM,MAAM,OAAO,GAAG,CAAC,MAAc,EAAU,EAAE,WAAC,OAAA,MAAA,MAAM,CAAC,IAAI,mCAAI,4BAAmB,CAAA,EAAA,CAAA;AAAxE,QAAA,OAAO,WAAiE;AAE9E,MAAM,gBAAgB,GAAG,CAAC,MAAc,EAAW,EAAE,CAAC,IAAA,eAAO,EAAC,MAAM,CAAC,KAAK,mCAAsB,CAAA;AAA1F,QAAA,gBAAgB,oBAA0E","sourcesContent":["import { Dictionary, TraverseMethod } from '../../common'\nimport { SystemError } from '../../error'\nimport { Node, NodePointer, Nodes, NodesMap } from '../../node'\nimport { NodeValues } from '../../node/nodeValues'\nimport { NodeDef, NodeDefCode, NodeDefCodeProps, NodeDefProps, NodeDefs, NodeDefType } from '../../nodeDef'\nimport { defaultCycle, Surveys } from '../../survey'\nimport { Survey, SurveyDependencyType } from '../../survey/survey'\nimport { Arrays, Queue } from '../../utils'\nimport { Record, RECORD_STEP_DEFAULT } from '../record'\nimport { RecordStepAnalysisCode } from '../recordStep'\nimport { RecordNodesIndexReader } from './recordNodesIndexReader'\nimport { NodeDefSelfReferences } from './nodeDefSelfReferences'\n\nexport const getCycle = (record: Record): string => record.cycle ?? defaultCycle\n\nexport const getNodes = (record: Record): Dictionary<Node> => record.nodes ?? {}\n\nexport const getNodesArray = (record: Record): Node[] => Object.values(getNodes(record))\n\nexport const getNodeByUuid =\n (uuid: string) =>\n (record: Record): Node | undefined =>\n record.nodes?.[uuid]\n\nexport const getNodesByUuids =\n (uuids: string[]) =>\n (record: Record): Node[] =>\n uuids.map((uuid: string) => getNodeByUuid(uuid)(record)) as Node[]\n\nexport const getRoot = (record: Record): Node | undefined => {\n const rootUuid = record._nodesIndex ? RecordNodesIndexReader.getNodeRootUuid(record._nodesIndex) : null\n if (rootUuid) {\n return getNodeByUuid(rootUuid)(record)\n }\n return getNodesArray(record).find((node) => !node.parentUuid)\n}\n\nexport const getChildren =\n (parentNode: Node, childDefUuid?: string) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const childrenUuids = childDefUuid\n ? RecordNodesIndexReader.getNodeUuidsByParentAndChildDef({\n parentNodeUuid: parentNode.uuid,\n childDefUuid,\n })(record._nodesIndex)\n : RecordNodesIndexReader.getNodeUuidsByParent(parentNode.uuid)(record._nodesIndex)\n return getNodesByUuids(childrenUuids)(record)\n }\n return getNodesArray(record).filter(\n (node) => node.parentUuid === parentNode.uuid && (!childDefUuid || node.nodeDefUuid == childDefUuid)\n )\n }\n\nexport const getChild =\n (parentNode: Node, childDefUuid: string) =>\n (record: Record): Node => {\n const children = getChildren(parentNode, childDefUuid)(record)\n const errorParams = { childDefUuid, parentNodeUuid: parentNode.uuid, recordUuid: record.uuid }\n if (children.length === 1) {\n return children[0]\n }\n if (children.length > 1) {\n throw new SystemError('systemError.record.multipleNodesFound', errorParams)\n }\n throw new SystemError('systemError.record.childNotFound', errorParams)\n }\n\nexport const getParent =\n (node: Node) =>\n (record: Record): Node | undefined =>\n node.parentUuid ? getNodeByUuid(node.parentUuid)(record) : undefined\n\nexport const getNodesByDefUuid =\n (nodeDefUuid: string) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeUuidsByDef(nodeDefUuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n return getNodesArray(record).filter((node) => node.nodeDefUuid === nodeDefUuid)\n }\n\nconst isNodeFlagTrue =\n (isChildFlagTrue: (parent: Node, nodeDefUuid: string) => boolean) =>\n (params: { record: Record; node: Node }): boolean => {\n const { record, node } = params\n const ancestorsAndSelf = getAncestorsAndSelf({ record, node })\n for (let i = 0; i < ancestorsAndSelf.length - 1; i++) {\n const child = ancestorsAndSelf[i]\n const parent = ancestorsAndSelf[i + 1]\n if (!isChildFlagTrue(parent, child.nodeDefUuid)) return false\n }\n return true\n }\n\nexport const isNodeApplicable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildApplicable(parent, nodeDefUuid))\nexport const isNodeEditable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildEditable(parent, nodeDefUuid))\nexport const isNodeVisible = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildVisible(parent, nodeDefUuid))\n\nexport const getDependentCodeAttributes =\n (node: Node) =>\n (record: Record): Node[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeCodeDependentUuids(node.uuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n throw new SystemError('record.nodesIndexNotInitialized')\n }\n\nexport const getParentCodeAttribute =\n (params: { parentNode: Node; nodeDef: NodeDefCode }) =>\n (record: Record): Node | undefined => {\n const { parentNode, nodeDef } = params\n\n const parentCodeDefUuid = NodeDefs.getParentCodeDefUuid(nodeDef)\n if (!parentCodeDefUuid) return undefined\n\n const ancestors = getAncestorsAndSelf({ record, node: parentNode })\n for (const ancestor of ancestors) {\n const children = getChildren(ancestor, parentCodeDefUuid)(record)\n if (children.length === 1) {\n return children[0]\n }\n }\n return undefined\n }\n\n// ancestors\nexport const visitAncestorsAndSelf =\n (node: Node, visitor: (node: Node) => void, stopIfFn?: () => boolean) =>\n (record: Record): void => {\n let currentNode: Node | undefined = node\n while (currentNode) {\n visitor(currentNode)\n if (stopIfFn?.()) break\n currentNode = getParent(currentNode)(record)\n }\n }\n\nexport const findAncestor =\n (node: Node, predicate: (node: Node) => boolean) =>\n (record: Record): Node | undefined => {\n let result: Node | undefined = undefined\n visitAncestorsAndSelf(\n node,\n (visitedNode) => {\n if (predicate(visitedNode)) {\n result = visitedNode\n }\n },\n () => !!result\n )(record)\n return result\n }\n\nexport const getAncestor = (params: { record: Record; node: Node; ancestorDefUuid: string }): Node | undefined => {\n const { record, node, ancestorDefUuid } = params\n if (node.nodeDefUuid === ancestorDefUuid) return node\n\n let ancestor = getParent(node)(record)\n while (ancestor && ancestor.nodeDefUuid !== ancestorDefUuid) {\n ancestor = getParent(ancestor)(record)\n }\n return ancestor\n}\n\n/**\n * Returns the list of ancestors from the given node to the root entity\n */\nexport const getAncestorsAndSelf = (params: { record: Record; node: Node }): Array<Node> => {\n const { record, node } = params\n const ancestors: Array<Node> = []\n visitAncestorsAndSelf(node, (currentNode) => {\n ancestors.push(currentNode)\n })(record)\n return ancestors\n}\n\n// descendants\n\nexport const getDescendantsOrSelf = (params: {\n record: Record\n node: Node\n nodeDefDescendant: NodeDef<any>\n}): Node[] => {\n const { record, node, nodeDefDescendant } = params\n\n if (nodeDefDescendant.uuid === node.nodeDefUuid) return [node]\n\n const nodeDefDescendantFullHierarchy = [...nodeDefDescendant.meta.h, nodeDefDescendant.uuid]\n\n // 1. get the descendant node defs uuids starting from node nodeDefUuid (not inclusive) down to the specified nodeDefDescendant uuid\n const descendantNodeDefUuids = nodeDefDescendantFullHierarchy.slice(\n nodeDefDescendantFullHierarchy.indexOf(node.nodeDefUuid) + 1\n )\n // 2. for every level in the hierarchy, find the children having the nodeDefUuid equal to the current one\n let currentAncestors = [node]\n let currentDescendants: Node[] = []\n for (const currentDescendantDefUuid of descendantNodeDefUuids) {\n for (const currentAncestor of currentAncestors) {\n currentDescendants.push(...getChildren(currentAncestor, currentDescendantDefUuid)(record))\n }\n currentAncestors = currentDescendants\n currentDescendants = []\n }\n return currentAncestors // currentAncestors is equal to the currentDescendants of the last level\n}\n\nexport const getDescendant = (params: { record: Record; node: Node; nodeDefDescendant: NodeDef<any> }): Node => {\n const { record, node, nodeDefDescendant } = params\n\n return getDescendantsOrSelf({ record, node, nodeDefDescendant })[0]\n}\n\nexport const isDescendantOf = (params: { node: Node; ancestor: Node }): boolean => {\n const { node, ancestor } = params\n return Nodes.getHierarchy(node).includes(ancestor.uuid)\n}\n\nexport const visitDescendantsAndSelf = (params: {\n record: Record\n node: Node\n visitor: (node: Node) => boolean | void\n traverseMethod?: TraverseMethod\n}): void => {\n const { record, node, visitor, traverseMethod = TraverseMethod.bfs } = params\n\n if (traverseMethod === TraverseMethod.bfs) {\n const queue = new Queue()\n\n queue.enqueue(node)\n\n while (!queue.isEmpty()) {\n const visitedNode = queue.dequeue()\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n queue.enqueueItems(children)\n }\n } else {\n const stack = []\n\n stack.push(node)\n\n while (stack.length > 0) {\n const visitedNode = stack.pop() as Node\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n\n // add children to stack in reverse order\n for (let index = children.length - 1; index >= 0; index--) {\n const child = children[index]\n stack.push(child)\n }\n }\n }\n}\n\nexport const findDescendantOrSelf =\n (node: Node, predicate: (node: Node) => boolean) =>\n (record: Record): Node | undefined => {\n let found = undefined\n\n visitDescendantsAndSelf({\n record,\n node,\n visitor: (currentNode) => {\n if (predicate(currentNode)) {\n found = currentNode\n return true\n }\n return false\n },\n })\n return found\n }\n\nconst getClosestAncestorNode = (params: {\n record: Record\n node: Node\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n dependentDef: NodeDef<NodeDefType, NodeDefProps>\n dependencyType: SurveyDependencyType\n}): Node | undefined => {\n const { record, node, nodeDef, dependentDef, dependencyType } = params\n\n // 1a if dependent def is the same as node def, potentially all nodes with\n // nodeDefUuid === dependentDef.uuid in record could be dependent of nodeDef;\n // consider the root node as the closest ancestor node,\n // unless the node def references itself only among the children of its parent entity (e.g. validation \"dbh > 0\")\n if (nodeDef.uuid === dependentDef.uuid) {\n return NodeDefSelfReferences.isSelfReferenceLocal({ nodeDef, dependencyType })\n ? getParent(node)(record)\n : getRoot(record)\n }\n // 1 find common ancestor def\n const commonAncestorDefUuid = Arrays.last(Arrays.intersection(nodeDef.meta.h, dependentDef.meta.h))\n if (!commonAncestorDefUuid) return undefined\n\n // 2 get ancestor node with common parent def\n return getAncestor({ record, node, ancestorDefUuid: commonAncestorDefUuid })\n}\n\ntype EntityKeyNodesGetterParams = {\n survey: Survey\n cycle?: string\n record: Record\n entity: Node\n keyDefs?: NodeDef<NodeDefType, NodeDefProps>[]\n}\n\nexport const getEntityKeyNodesByDefUuid = (params: EntityKeyNodesGetterParams): NodesMap => {\n const { survey, cycle, record, entity, keyDefs } = params\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: entity.nodeDefUuid })\n const nodeDefKeys = keyDefs ?? Surveys.getNodeDefKeys({ survey, cycle, nodeDef })\n return nodeDefKeys.reduce((acc: NodesMap, nodeDefKey) => {\n const nodeKey = getDescendant({ record, node: entity, nodeDefDescendant: nodeDefKey })\n acc[nodeDefKey.uuid] = nodeKey\n return acc\n }, {})\n}\n\nexport const getEntityKeyNodes = (params: EntityKeyNodesGetterParams): Node[] =>\n Object.values(getEntityKeyNodesByDefUuid(params))\n\nexport const getEntityKeyValuesByDefUuid = (params: EntityKeyNodesGetterParams): Dictionary<any> => {\n const keyNodesByDefUuid = getEntityKeyNodesByDefUuid(params)\n return Object.entries(keyNodesByDefUuid).reduce((acc: Dictionary<any>, [uuid, keyNode]) => {\n acc[uuid] = keyNode?.value\n return acc\n }, {})\n}\n\nexport const getEntityKeyValues = (params: EntityKeyNodesGetterParams): any[] =>\n Object.values(getEntityKeyValuesByDefUuid(params))\n\nexport const getEntitySiblings = (params: { record: Record; entity: Node; includeSelf?: boolean }) => {\n const { record, entity, includeSelf = false } = params\n const parentEntity = getParent(entity)(record)\n if (!parentEntity) return []\n const siblingEntities = getChildren(parentEntity, entity.nodeDefUuid)(record)\n return includeSelf ? siblingEntities : siblingEntities.filter((sibling) => !Nodes.areEqual(sibling, entity))\n}\n\nexport const getAttributeSiblings = (params: {\n record: Record\n node: Node\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n}) => {\n const { record, node, nodeDef } = params\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return []\n const siblingParentEntities = getEntitySiblings({ record, entity: parentEntity })\n return siblingParentEntities.reduce((siblingsAcc: Node[], siblingEntity) => {\n siblingsAcc.push(...getChildren(siblingEntity, nodeDef.uuid)(record))\n return siblingsAcc\n }, [])\n}\n\nexport const getNodeIndex = (params: { record: Record; node: Node }) => {\n const { record, node } = params\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return 0 // root entity\n const siblings = getChildren(parentEntity, node.nodeDefUuid)(record)\n return siblings.indexOf(node)\n}\n\nexport const findEntityByKeyValues = (params: {\n survey: Survey\n cycle: string\n record: Record\n parentEntity: Node\n entityDefUuid: string\n keyValuesByDefUuid: Dictionary<any>\n}): Node | undefined => {\n const { survey, cycle, record, parentEntity, entityDefUuid, keyValuesByDefUuid } = params\n const entityDef = Surveys.getNodeDefByUuid({ survey, uuid: entityDefUuid })\n const siblingEntities = getChildren(parentEntity, entityDefUuid)(record)\n if (NodeDefs.isSingle(entityDef)) {\n return siblingEntities[0]\n }\n const keyDefs = Surveys.getNodeDefKeys({ survey, cycle, nodeDef: entityDef })\n\n return siblingEntities.find((siblingEntity) => {\n const siblingEntityKeyValuesByDefUuid = getEntityKeyValuesByDefUuid({\n survey,\n record,\n entity: siblingEntity,\n keyDefs,\n })\n return keyDefs.every((keyDef) => {\n const keyValue = siblingEntityKeyValuesByDefUuid[keyDef.uuid]\n const keyValueSearch = keyValuesByDefUuid[keyDef.uuid]\n return NodeValues.isValueEqual({\n survey,\n nodeDef: keyDef,\n value: keyValue,\n valueSearch: keyValueSearch,\n })\n })\n })\n}\n\nexport const findEntityWithSameKeysInAnotherRecord = (params: {\n survey: Survey\n cycle: string\n entityUuid: string\n record: Record\n recordOther: Record\n}): Node | undefined => {\n const { survey, cycle, entityUuid, record, recordOther } = params\n const entity = getNodeByUuid(entityUuid)(record)\n if (!entity) return undefined\n\n let otherRecordCurrentParentEntity = getRoot(recordOther)\n if (!otherRecordCurrentParentEntity) return undefined\n\n const entityAncestorsAndSelf = getAncestorsAndSelf({\n record,\n node: entity,\n })\n const ancestorDefUuidsAndKeys = entityAncestorsAndSelf.map((ancestor) => ({\n entityDefUuid: ancestor.nodeDefUuid,\n keyValuesByDefUuid: getEntityKeyValuesByDefUuid({\n survey,\n record,\n entity: ancestor,\n }),\n }))\n\n const ancestorDefUuidsAndKeysToVisit = [...ancestorDefUuidsAndKeys].reverse()\n\n for (let index = 1; otherRecordCurrentParentEntity && index < ancestorDefUuidsAndKeysToVisit.length; index++) {\n const { entityDefUuid, keyValuesByDefUuid } = ancestorDefUuidsAndKeysToVisit[index]\n otherRecordCurrentParentEntity = findEntityByKeyValues({\n survey,\n cycle,\n record: recordOther,\n parentEntity: otherRecordCurrentParentEntity,\n entityDefUuid,\n keyValuesByDefUuid,\n })\n }\n return otherRecordCurrentParentEntity\n}\n\nexport const getDependentNodePointers = (params: {\n survey: Survey\n record: Record\n node: Node\n dependencyType: SurveyDependencyType\n includeSelf?: boolean\n filterFn?: (nodePointer: NodePointer) => boolean\n}) => {\n const { survey, record, node, dependencyType, includeSelf = false, filterFn = null } = params\n const nodeDefUuid = node.nodeDefUuid\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: nodeDefUuid })\n const dependentDefs = Surveys.getNodeDefDependents({ survey, nodeDefUuid, dependencyType })\n const nodePointers: Array<NodePointer> = []\n\n const addToNodePointers = (nodePointer: NodePointer): void => {\n if (filterFn === null || filterFn(nodePointer)) {\n nodePointers.push(nodePointer)\n }\n }\n\n for (const dependentDef of dependentDefs) {\n // 1 find common ancestor node\n const commonAncestorNode = getClosestAncestorNode({ record, node, nodeDef, dependentDef, dependencyType })\n if (!commonAncestorNode) continue\n\n const nodeDefDependentParent = Surveys.getNodeDefParent({ survey, nodeDef: dependentDef })\n if (!nodeDefDependentParent) throw new SystemError('record.nodes.dependents.dependencyOnRootFound')\n\n // 2 find descendant nodes of common parent node with nodeDefUuid = dependentDef uuid\n const dependentContextNodes = getDescendantsOrSelf({\n record,\n node: commonAncestorNode,\n nodeDefDescendant: nodeDefDependentParent,\n })\n\n for (const dependentContextNode of dependentContextNodes) {\n addToNodePointers({\n nodeCtx: dependentContextNode,\n nodeDef: dependentDef,\n })\n }\n }\n if (includeSelf) {\n const parentNode = getParent(node)(record)\n if (parentNode) {\n addToNodePointers({\n nodeCtx: parentNode,\n nodeDef,\n })\n }\n }\n\n return nodePointers\n}\n\nexport const getAncestorCodePath = (params: {\n survey: Survey\n record: Record\n parentNode: Node\n nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>\n}): string[] => {\n const { record, parentNode, nodeDef, survey } = params\n\n const getCodeAttributeItemCode = (codeAttribute: Node | undefined): string => {\n const codeItemUuid = codeAttribute ? NodeValues.getItemUuid(codeAttribute) : undefined\n if (!codeItemUuid) return ''\n const item = Surveys.getCategoryItemByUuid({ survey, itemUuid: codeItemUuid })\n return item?.props.code ?? ''\n }\n\n const codePaths = []\n let currentParentCodeAttribute = getParentCodeAttribute({ parentNode, nodeDef })(record)\n\n while (currentParentCodeAttribute) {\n const ancestorItemCode = getCodeAttributeItemCode(currentParentCodeAttribute)\n codePaths.unshift(ancestorItemCode)\n const ancestorCodeDef = Surveys.getNodeDefByUuid({\n survey,\n uuid: currentParentCodeAttribute.nodeDefUuid,\n }) as NodeDefCode\n currentParentCodeAttribute = getParentCodeAttribute({ parentNode, nodeDef: ancestorCodeDef })(record)\n }\n return codePaths\n}\n\nexport const getCategoryItemUuid = (params: {\n survey: Survey\n nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>\n record: Record\n parentNode: Node\n code: string\n}): string | undefined => {\n const { survey, nodeDef, record, parentNode, code } = params\n const categoryUuid = nodeDef.props.categoryUuid\n\n const codePaths = [...getAncestorCodePath({ survey, record, parentNode, nodeDef }), code]\n\n const item = Surveys.getCategoryItemByCodePaths({ survey, categoryUuid, codePaths })\n\n return item?.uuid\n}\n\nexport const isNodeFilledByUser =\n (node: Node) =>\n (record: Record): boolean =>\n !!findDescendantOrSelf(node, (visitedNode) => Nodes.hasUserInputValue(visitedNode))(record)\n\nexport const isNodeEmpty =\n (node: Node) =>\n (record: Record): boolean =>\n !isNodeFilledByUser(node)(record)\n\nexport const isEmpty = (record: Record): boolean => {\n const rootNode = getRoot(record)\n return rootNode ? isNodeEmpty(rootNode)(record) : true\n}\n\nexport const getStep = (record: Record): string => record.step ?? RECORD_STEP_DEFAULT\n\nexport const isInAnalysisStep = (record: Record): boolean => getStep(record) === RecordStepAnalysisCode\n"]}
|