hierarchical-approval 2.1.0 → 2.3.0

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +51 -0
  3. package/dist/{ApprovalEngine-DqRIadYg.d.cts → ApprovalEngine-C1dUPnLM.d.cts} +101 -2
  4. package/dist/{ApprovalEngine-CJwnpnpL.d.ts → ApprovalEngine-Ci9urTDI.d.ts} +101 -2
  5. package/dist/{IStorageAdapter-DjRvHUF0.d.ts → IStorageAdapter-BU3sau5W.d.ts} +14 -0
  6. package/dist/{IStorageAdapter-Bk7ybd3z.d.cts → IStorageAdapter-DdHO4Rf1.d.cts} +14 -0
  7. package/dist/adapters/MemoryAdapter.cjs +4 -0
  8. package/dist/adapters/MemoryAdapter.cjs.map +1 -1
  9. package/dist/adapters/MemoryAdapter.d.cts +2 -1
  10. package/dist/adapters/MemoryAdapter.d.ts +2 -1
  11. package/dist/adapters/MemoryAdapter.js +4 -0
  12. package/dist/adapters/MemoryAdapter.js.map +1 -1
  13. package/dist/adapters/PostgresAdapter.cjs +12 -0
  14. package/dist/adapters/PostgresAdapter.cjs.map +1 -1
  15. package/dist/adapters/PostgresAdapter.d.cts +2 -1
  16. package/dist/adapters/PostgresAdapter.d.ts +2 -1
  17. package/dist/adapters/PostgresAdapter.js +12 -0
  18. package/dist/adapters/PostgresAdapter.js.map +1 -1
  19. package/dist/index.cjs +195 -0
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +3 -3
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.js +195 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/nestjs.cjs +190 -0
  26. package/dist/nestjs.cjs.map +1 -1
  27. package/dist/nestjs.d.cts +2 -2
  28. package/dist/nestjs.d.ts +2 -2
  29. package/dist/nestjs.js +190 -0
  30. package/dist/nestjs.js.map +1 -1
  31. package/dist/testing.cjs +194 -0
  32. package/dist/testing.cjs.map +1 -1
  33. package/dist/testing.d.cts +2 -2
  34. package/dist/testing.d.ts +2 -2
  35. package/dist/testing.js +194 -0
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +1 -1
package/dist/nestjs.cjs CHANGED
@@ -916,6 +916,7 @@ function computeTimingStats(samples) {
916
916
 
917
917
  // src/engine/ApprovalEngine.ts
918
918
  var MAX_SUBWORKFLOW_DEPTH = 5;
919
+ var DEFAULT_PURGE_LIMIT = 1e3;
919
920
  var DEFAULT_MAX_REMINDERS = 3;
920
921
  var DEFAULT_MAX_ATTEMPTS = 3;
921
922
  var DEFAULT_BASE_DELAY_MS = 50;
@@ -927,6 +928,7 @@ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
927
928
  ]);
928
929
  var CYCLE_TIME_STATUSES = ["approved", "rejected", "cancelled"];
929
930
  var CYCLE_TIME_FETCH_BATCH_SIZE = 500;
931
+ var TEMPLATE_BUNDLE_VERSION = 1;
930
932
  var ApprovalEngine = class _ApprovalEngine {
931
933
  constructor(opts) {
932
934
  this.opts = opts;
@@ -3008,6 +3010,194 @@ var ApprovalEngine = class _ApprovalEngine {
3008
3010
  oldestAgeMs: Number.isFinite(row.oldest) ? now.getTime() - row.oldest : 0
3009
3011
  })).sort((a, b) => b.pending - a.pending || a.approverId.localeCompare(b.approverId));
3010
3012
  }
3013
+ /**
3014
+ * Export templates as a portable bundle.
3015
+ *
3016
+ * Approval configuration is written once and then has to travel — authored in
3017
+ * a sandbox, reviewed, promoted to production. Reading `listTemplates()` and
3018
+ * re-posting the rows carried each environment's own `id`, `tenantId` and
3019
+ * version lineage with it, which either collided on arrival or silently
3020
+ * claimed a history the target never had. This strips all of it.
3021
+ *
3022
+ * @param names - Templates to include; omit for all of them.
3023
+ */
3024
+ async exportTemplates(names) {
3025
+ const all = await this.registry.list();
3026
+ const wanted = names ? all.filter((t) => names.includes(t.name)) : all;
3027
+ if (names) {
3028
+ const missing = names.filter((n) => !all.some((t) => t.name === n));
3029
+ if (missing.length > 0) {
3030
+ throw new ApprovalTemplateNotFoundError(missing.join(", "));
3031
+ }
3032
+ }
3033
+ return {
3034
+ bundleVersion: TEMPLATE_BUNDLE_VERSION,
3035
+ exportedAt: this.clock.now(),
3036
+ templates: wanted.map((t) => {
3037
+ const {
3038
+ id: _id,
3039
+ tenantId: _tenantId,
3040
+ createdAt: _createdAt,
3041
+ version: _version,
3042
+ previousVersionId: _previousVersionId,
3043
+ ...config
3044
+ } = t;
3045
+ return config;
3046
+ })
3047
+ };
3048
+ }
3049
+ /**
3050
+ * Import a bundle produced by {@link exportTemplates}.
3051
+ *
3052
+ * **Every template is validated before any is written.** A bundle that is
3053
+ * half-applied is worse than one rejected outright: the tenant is left in a
3054
+ * state matching neither environment, and the operator has no way to tell
3055
+ * which half landed. Per-template failures during the write phase are still
3056
+ * reported individually, since a storage error can occur after validation
3057
+ * passes.
3058
+ *
3059
+ * @param bundle - The bundle to apply.
3060
+ * @param opts - `mode: 'create'` (default) refuses to touch existing
3061
+ * templates; `'upsert'` updates them. `dryRun` reports without writing.
3062
+ */
3063
+ async importTemplates(bundle, opts = {}) {
3064
+ const mode = opts.mode ?? "create";
3065
+ const dryRun = opts.dryRun ?? false;
3066
+ if (bundle.bundleVersion !== TEMPLATE_BUNDLE_VERSION) {
3067
+ throw new ApprovalValidationError(
3068
+ `Unsupported template bundle version ${bundle.bundleVersion}; this engine reads version ${TEMPLATE_BUNDLE_VERSION}.`
3069
+ );
3070
+ }
3071
+ if (!Array.isArray(bundle.templates) || bundle.templates.length === 0) {
3072
+ throw new ApprovalValidationError("Template bundle contains no templates.");
3073
+ }
3074
+ const duplicates = bundle.templates.map((t) => t.name).filter((name, i, all) => all.indexOf(name) !== i);
3075
+ if (duplicates.length > 0) {
3076
+ throw new ApprovalValidationError(
3077
+ `Template bundle contains duplicate names: ${[...new Set(duplicates)].join(", ")}.`
3078
+ );
3079
+ }
3080
+ const invalid = [];
3081
+ for (const config of bundle.templates) {
3082
+ const result2 = this.validateTemplate(config);
3083
+ if (!result2.valid) {
3084
+ invalid.push({
3085
+ name: config.name,
3086
+ message: result2.errors[0]?.message ?? "unknown validation error"
3087
+ });
3088
+ }
3089
+ }
3090
+ if (invalid.length > 0) {
3091
+ throw new ApprovalValidationError(
3092
+ `Template bundle failed validation and was not applied: ${invalid.map((e) => `${e.name}: ${e.message}`).join("; ")}`
3093
+ );
3094
+ }
3095
+ const result = { created: [], updated: [], skipped: [], errors: [], dryRun };
3096
+ for (const config of bundle.templates) {
3097
+ const existing = await this.opts.adapter.getTemplate(this.tenantId, config.name);
3098
+ try {
3099
+ if (existing && mode === "create") {
3100
+ result.skipped.push(config.name);
3101
+ continue;
3102
+ }
3103
+ if (existing) {
3104
+ if (!dryRun) await this.registry.update(config);
3105
+ result.updated.push(config.name);
3106
+ } else {
3107
+ if (!dryRun) await this.registry.define(config);
3108
+ result.created.push(config.name);
3109
+ }
3110
+ } catch (err) {
3111
+ result.errors.push({ name: config.name, message: err.message });
3112
+ }
3113
+ }
3114
+ this.logger.info("importTemplates: bundle applied", {
3115
+ tenantId: this.tenantId,
3116
+ mode,
3117
+ dryRun,
3118
+ created: result.created.length,
3119
+ updated: result.updated.length,
3120
+ skipped: result.skipped.length,
3121
+ errors: result.errors.length
3122
+ });
3123
+ return result;
3124
+ }
3125
+ /**
3126
+ * Permanently remove finished approvals older than a cut-off.
3127
+ *
3128
+ * Approval tables only grow, and data-minimisation rules eventually require
3129
+ * old records to go. There was no way to remove one, so operators reached
3130
+ * around the library and deleted rows directly — which is exactly where
3131
+ * orphaned audit rows and half-deleted instances come from.
3132
+ *
3133
+ * **Only terminal instances are eligible.** A pending approval is live work;
3134
+ * deleting one would strand a document with no way to finish and no record of
3135
+ * why. Passing a non-terminal status is rejected rather than quietly ignored,
3136
+ * because a caller who asked to purge pending work has misunderstood
3137
+ * something and should hear about it.
3138
+ *
3139
+ * This is irreversible and removes the audit trail with the instance. In many
3140
+ * deployments that trail *is* the compliance record, which is why the
3141
+ * underlying `deleteInstance` is an optional adapter method: an adapter that
3142
+ * does not implement it makes the whole operation unavailable, and this
3143
+ * throws rather than reporting a successful purge of nothing.
3144
+ *
3145
+ * @param opts - Cut-off, optional status/type scoping, safety limit, dry run.
3146
+ * @returns What was removed, or would be under `dryRun`.
3147
+ */
3148
+ async purgeInstances(opts) {
3149
+ const dryRun = opts.dryRun ?? false;
3150
+ const limit = opts.limit ?? DEFAULT_PURGE_LIMIT;
3151
+ if (!(opts.olderThan instanceof Date) || Number.isNaN(opts.olderThan.getTime())) {
3152
+ throw new ApprovalValidationError("purgeInstances requires a valid olderThan date.");
3153
+ }
3154
+ const requested = opts.statuses ?? [...TERMINAL_STATUSES];
3155
+ const nonTerminal = requested.filter((st) => !TERMINAL_STATUSES.has(st));
3156
+ if (nonTerminal.length > 0) {
3157
+ throw new ApprovalValidationError(
3158
+ `purgeInstances refuses non-terminal statuses (${nonTerminal.join(", ")}): a pending approval is live work, and removing it would strand the document it belongs to.`
3159
+ );
3160
+ }
3161
+ const deleteInstance = this.opts.adapter.deleteInstance?.bind(this.opts.adapter);
3162
+ if (!deleteInstance && !dryRun) {
3163
+ throw new ApprovalValidationError(
3164
+ "The configured storage adapter does not implement deleteInstance(), so instances cannot be purged."
3165
+ );
3166
+ }
3167
+ const result = { purged: [], scanned: 0, dryRun };
3168
+ for (const status of requested) {
3169
+ if (result.purged.length >= limit) break;
3170
+ const page = await this.opts.adapter.getInstancesByFilter(
3171
+ this.tenantId,
3172
+ {
3173
+ status,
3174
+ toDate: opts.olderThan,
3175
+ ...opts.documentType ? { documentType: opts.documentType } : {}
3176
+ },
3177
+ { limit, offset: 0 }
3178
+ );
3179
+ for (const instance of page.items) {
3180
+ if (result.purged.length >= limit) break;
3181
+ result.scanned++;
3182
+ if (!TERMINAL_STATUSES.has(instance.status)) continue;
3183
+ if (new Date(instance.createdAt) > opts.olderThan) continue;
3184
+ if (!dryRun) await deleteInstance(this.tenantId, instance.id);
3185
+ result.purged.push({
3186
+ instanceId: instance.id,
3187
+ documentId: instance.documentId,
3188
+ status: instance.status
3189
+ });
3190
+ }
3191
+ }
3192
+ this.logger.info("purgeInstances: sweep complete", {
3193
+ tenantId: this.tenantId,
3194
+ olderThan: opts.olderThan.toISOString(),
3195
+ scanned: result.scanned,
3196
+ purged: result.purged.length,
3197
+ dryRun
3198
+ });
3199
+ return result;
3200
+ }
3011
3201
  async getStatistics(filter = {}) {
3012
3202
  const statuses = [
3013
3203
  "pending",