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