@revenexx/integrations-node-devkit 0.8.1 → 0.8.3
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/README.md +2 -1
- package/dist/testing/author.d.ts +7 -7
- package/dist/testing/context.d.ts +15 -15
- package/dist/testing/credentials.d.ts +6 -6
- package/dist/testing/fetch.d.ts +4 -4
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/mock.d.ts +12 -0
- package/package.json +6 -5
- package/preview-host/package.json +1 -1
package/README.md
CHANGED
|
@@ -219,7 +219,8 @@ expect(persistDurableCreds).toHaveBeenCalledWith({ refreshToken: 'RT' });
|
|
|
219
219
|
stub.restore();
|
|
220
220
|
```
|
|
221
221
|
|
|
222
|
-
`vitest` is an optional peer dependency (the harness uses `vi` spies)
|
|
222
|
+
`vitest` is an optional peer dependency (the harness uses `vi` spies); from Vitest 5 on,
|
|
223
|
+
install its `vite` peer alongside.
|
|
223
224
|
|
|
224
225
|
## Fidelity caveats
|
|
225
226
|
|
package/dist/testing/author.d.ts
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
import type { INodeAuthorContext } from '@revenexx/integrations-node-sdk';
|
|
2
|
-
import {
|
|
2
|
+
import type { AnyMock } from './mock.js';
|
|
3
3
|
/**
|
|
4
4
|
* Builds an {@link INodeAuthorContext} for unit-testing a node's *author-time*
|
|
5
5
|
* resolvers (`loadOptions`, `resolveConfigSchema`, `resolveOutputs`). Until this
|
|
6
6
|
* package existed, this factory was reinvented inline in each repo's resolver
|
|
7
7
|
* tests. Mirrors {@link createMockContext}: `secrets.get` / `credentials.get`
|
|
8
|
-
* are `vi.fn()`-backed and seedable.
|
|
8
|
+
* are `vi.fn<AnyFn>()`-backed and seedable.
|
|
9
9
|
*/
|
|
10
10
|
export type MockAuthorLogger = {
|
|
11
|
-
info:
|
|
12
|
-
warn:
|
|
13
|
-
error:
|
|
11
|
+
info: AnyMock;
|
|
12
|
+
warn: AnyMock;
|
|
13
|
+
error: AnyMock;
|
|
14
14
|
};
|
|
15
15
|
export type MockAuthorContext = INodeAuthorContext & {
|
|
16
16
|
logger: MockAuthorLogger;
|
|
17
17
|
secrets: {
|
|
18
|
-
get:
|
|
18
|
+
get: AnyMock;
|
|
19
19
|
};
|
|
20
20
|
credentials: {
|
|
21
|
-
get:
|
|
21
|
+
get: AnyMock;
|
|
22
22
|
};
|
|
23
23
|
};
|
|
24
24
|
export interface CreateAuthorContextOptions {
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { INodeContext } from '@revenexx/integrations-node-sdk';
|
|
2
|
-
import {
|
|
2
|
+
import type { AnyMock } from './mock.js';
|
|
3
3
|
/**
|
|
4
4
|
* Drop-in replacement for the `createMockContext` helper that was, until this
|
|
5
5
|
* package existed, copy-pasted byte-for-byte into every node repo's
|
|
6
6
|
* `tests/helpers/context.ts`. Builds a full {@link INodeContext} with
|
|
7
|
-
* `vi.fn()`-backed `logger`, `secrets.get`, `credentials.get` and `state` so a
|
|
7
|
+
* `vi.fn<AnyFn>()`-backed `logger`, `secrets.get`, `credentials.get` and `state` so a
|
|
8
8
|
* node's `execute` can be unit-tested in isolation.
|
|
9
9
|
*
|
|
10
10
|
* The state mock is **stateful on purpose**: what the node writes, it reads
|
|
@@ -22,30 +22,30 @@ import { vi } from 'vitest';
|
|
|
22
22
|
* that failed and left the watermark where it was.
|
|
23
23
|
*/
|
|
24
24
|
export type MockLogger = {
|
|
25
|
-
info:
|
|
26
|
-
warn:
|
|
27
|
-
error:
|
|
25
|
+
info: AnyMock;
|
|
26
|
+
warn: AnyMock;
|
|
27
|
+
error: AnyMock;
|
|
28
28
|
};
|
|
29
29
|
export type MockSecrets = {
|
|
30
|
-
get:
|
|
30
|
+
get: AnyMock;
|
|
31
31
|
};
|
|
32
32
|
export type MockCredentials = {
|
|
33
|
-
get:
|
|
33
|
+
get: AnyMock;
|
|
34
34
|
};
|
|
35
|
-
/** Every state operation is a `vi.fn()`, so calls can be asserted on. */
|
|
35
|
+
/** Every state operation is a `vi.fn<AnyFn>()`, so calls can be asserted on. */
|
|
36
36
|
export type MockState = {
|
|
37
37
|
mapping: {
|
|
38
|
-
get:
|
|
39
|
-
put:
|
|
38
|
+
get: AnyMock;
|
|
39
|
+
put: AnyMock;
|
|
40
40
|
};
|
|
41
41
|
cursor: {
|
|
42
|
-
get:
|
|
43
|
-
set:
|
|
42
|
+
get: AnyMock;
|
|
43
|
+
set: AnyMock;
|
|
44
44
|
};
|
|
45
|
-
claim:
|
|
45
|
+
claim: AnyMock;
|
|
46
46
|
digest: {
|
|
47
|
-
unchanged:
|
|
48
|
-
set:
|
|
47
|
+
unchanged: AnyMock;
|
|
48
|
+
set: AnyMock;
|
|
49
49
|
};
|
|
50
50
|
};
|
|
51
51
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ICredential, ICredentialContext, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';
|
|
2
|
-
import {
|
|
2
|
+
import type { AnyMock } from './mock.js';
|
|
3
3
|
/**
|
|
4
4
|
* Harness for unit-testing a credential type's `test` / `resolve` / 3-legged
|
|
5
5
|
* OAuth without the credentials broker or a real provider. Combine with
|
|
@@ -8,14 +8,14 @@ import { vi } from 'vitest';
|
|
|
8
8
|
* rotation.
|
|
9
9
|
*/
|
|
10
10
|
export type MockCredentialLogger = {
|
|
11
|
-
info:
|
|
12
|
-
warn:
|
|
13
|
-
error:
|
|
11
|
+
info: AnyMock;
|
|
12
|
+
warn: AnyMock;
|
|
13
|
+
error: AnyMock;
|
|
14
14
|
};
|
|
15
15
|
export type MockCredentialContext = ICredentialContext & {
|
|
16
16
|
logger: MockCredentialLogger;
|
|
17
17
|
/** Spy wired to `ctx.persistDurableCreds`; assert `.toHaveBeenCalledWith(...)`. */
|
|
18
|
-
persistDurableCreds:
|
|
18
|
+
persistDurableCreds: AnyMock;
|
|
19
19
|
};
|
|
20
20
|
export interface CreateCredentialContextOptions {
|
|
21
21
|
signal?: AbortSignal;
|
|
@@ -36,7 +36,7 @@ export interface RunCredentialResolveOptions {
|
|
|
36
36
|
export interface RunCredentialResolveResult {
|
|
37
37
|
result: ICredentialResolveResult;
|
|
38
38
|
/** Spy wired to `ctx.persistDurableCreds` — assert rotation happened. */
|
|
39
|
-
persistDurableCreds:
|
|
39
|
+
persistDurableCreds: AnyMock;
|
|
40
40
|
/** The context used, for further assertions (logger calls, etc.). */
|
|
41
41
|
ctx: MockCredentialContext;
|
|
42
42
|
}
|
package/dist/testing/fetch.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { AnyMock } from './mock.js';
|
|
2
2
|
/**
|
|
3
3
|
* Utilities for stubbing the global `fetch` so a credential's `resolve` /
|
|
4
4
|
* `test` (which reach an OAuth token endpoint via the SDK's `postForm`) or a
|
|
@@ -24,13 +24,13 @@ export type FetchHandler = (request: StubbedRequest) => StubResponseInit | Respo
|
|
|
24
24
|
/** Builds a real `Response` from a {@link StubResponseInit}. */
|
|
25
25
|
export declare function buildResponse(init: StubResponseInit): Response;
|
|
26
26
|
export interface StubFetchResult {
|
|
27
|
-
/** The `vi.fn()` installed as `globalThis.fetch` — assert calls on it. */
|
|
28
|
-
fetchMock:
|
|
27
|
+
/** The `vi.fn<AnyFn>()` installed as `globalThis.fetch` — assert calls on it. */
|
|
28
|
+
fetchMock: AnyMock;
|
|
29
29
|
/** Restores the previous `globalThis.fetch`. */
|
|
30
30
|
restore(): void;
|
|
31
31
|
}
|
|
32
32
|
/**
|
|
33
|
-
* Replaces `globalThis.fetch` with a `vi.fn()` driven by `handler`. Pass a
|
|
33
|
+
* Replaces `globalThis.fetch` with a `vi.fn<AnyFn>()` driven by `handler`. Pass a
|
|
34
34
|
* static {@link StubResponseInit} to answer every request identically, or a
|
|
35
35
|
* {@link FetchHandler} to branch on url/method. Call `restore()` when done
|
|
36
36
|
* (e.g. in `afterEach`).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/testing/index.ts","../../src/testing/context.ts","../../src/state-rules.ts","../../src/testing/author.ts","../../src/testing/fetch.ts","../../src/testing/credentials.ts"],"sourcesContent":["export * from './context.js';\nexport * from './author.js';\nexport * from './fetch.js';\nexport * from './credentials.js';\n","import type { INodeContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport { assertNotRepointed, assertTtlInRange } from '../state-rules.js';\n\n/**\n * Drop-in replacement for the `createMockContext` helper that was, until this\n * package existed, copy-pasted byte-for-byte into every node repo's\n * `tests/helpers/context.ts`. Builds a full {@link INodeContext} with\n * `vi.fn()`-backed `logger`, `secrets.get`, `credentials.get` and `state` so a\n * node's `execute` can be unit-tested in isolation.\n *\n * The state mock is **stateful on purpose**: what the node writes, it reads\n * back. A node's interesting behaviour is precisely the second run — the one\n * that finds the mapping it created the first time — and a mock that forgets\n * would only ever exercise the create branch. It is the one place an author can\n * test writes at all: in the real product, author-time execution is read-only.\n *\n * It reads back *when the store would let it*, which is not the same for all\n * four roles (SDK 1.0.0, `specs/workflow-state.md`): a mapping and a claim take\n * effect immediately, a cursor and a digest are staged and adopted only once the\n * run completes. So `cursor.get` after `cursor.set` still answers what the last\n * completed run left — call {@link MockContext.completeRun} between two\n * `execute` calls to play the second run, and leave it uncalled to play the run\n * that failed and left the watermark where it was.\n */\n\nexport type MockLogger = {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n};\n\nexport type MockSecrets = {\n get: ReturnType<typeof vi.fn>;\n};\n\nexport type MockCredentials = {\n get: ReturnType<typeof vi.fn>;\n};\n\n/** Every state operation is a `vi.fn()`, so calls can be asserted on. */\nexport type MockState = {\n mapping: { get: ReturnType<typeof vi.fn>; put: ReturnType<typeof vi.fn> };\n cursor: { get: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };\n claim: ReturnType<typeof vi.fn>;\n digest: { unchanged: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };\n};\n\n/**\n * What the store already knows when the node starts — the \"this ran before\"\n * half of any sync test.\n */\nexport interface MockStateSeed {\n /** namespace -> { leftKey: rightKey }; readable from either side. */\n mappings?: Record<string, Record<string, string>>;\n /** namespace -> partitionKey ('' for the unpartitioned one) -> watermark. */\n cursors?: Record<string, Record<string, unknown>>;\n /** namespace -> keys already claimed, so `claim` returns false for them. */\n claims?: Record<string, string[]>;\n /** namespace -> { entityKey: digest }. */\n digests?: Record<string, Record<string, string>>;\n}\n\nexport type MockContext = INodeContext & {\n logger: MockLogger;\n secrets: MockSecrets;\n credentials: MockCredentials;\n state: MockState;\n /**\n * Adopts what this run staged — the cursors and digests it set — the way the\n * engine does when a run completes. Not part of {@link INodeContext}: it is\n * the harness standing in for the run's own ending, and a node can never call\n * it. A test that never calls it has played a run that did not complete.\n */\n completeRun: () => void;\n};\n\nexport interface CreateMockContextOptions {\n signal?: AbortSignal;\n /** Secret key -> value returned by `secrets.get`. Unknown keys fall back to a deterministic stub. */\n secrets?: Record<string, string>;\n /** When set, `secrets.get` rejects with this error instead of resolving. */\n secretsError?: Error;\n /** Credential instance id -> resolved access data returned by `credentials.get`. */\n credentials?: Record<string, Record<string, unknown>>;\n /** When set, `credentials.get` rejects with this error instead of resolving. */\n credentialsError?: Error;\n /** What the state store already holds when the node starts. */\n state?: MockStateSeed;\n /**\n * When set, every state call rejects with this error — the shape of the\n * engine refusing a namespace the workflow never declared.\n */\n stateError?: Error;\n}\n\nexport function createMockContext(options: CreateMockContextOptions = {}): MockContext {\n const signal = options.signal ?? new AbortController().signal;\n const { state, completeRun } = createMockState(options.state, options.stateError);\n\n const secretsGet = options.secretsError\n ? vi.fn(async () => {\n throw options.secretsError;\n })\n : vi.fn(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn(async () => {\n throw options.credentialsError;\n })\n : vi.fn(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n },\n secrets: {\n get: secretsGet,\n },\n credentials: {\n get: credentialsGet,\n },\n state,\n completeRun,\n };\n}\n\n/**\n * A tiny in-memory stand-in for the four state roles. Seeds are copied rather\n * than referenced, so a test that writes cannot leak into the next one.\n *\n * The write calls split the way the store does. A mapping and a claim land in\n * the committed maps at once; a cursor and a digest land in a staging map that\n * only `completeRun` folds in, so a read during the run answers what the last\n * completed one left. That is the whole reason there are four operations rather\n * than a generic get/set, and a mock that adopted everything immediately would\n * hide the case the rule exists for: the run that fails after advancing its\n * watermark.\n */\nfunction createMockState(seed: MockStateSeed = {}, error?: Error): { state: MockState; completeRun: () => void } {\n const mappings = new Map<string, Map<string, string>>();\n const cursors = new Map<string, Map<string, unknown>>();\n const claims = new Map<string, Set<string>>();\n const digests = new Map<string, Map<string, string>>();\n /** What this run has staged: adopted by `completeRun`, dropped otherwise. */\n const stagedCursors = new Map<string, Map<string, unknown>>();\n const stagedDigests = new Map<string, Map<string, string>>();\n\n for (const [namespace, pairs] of Object.entries(seed.mappings ?? {})) {\n mappings.set(namespace, new Map(Object.entries(pairs)));\n }\n for (const [namespace, partitions] of Object.entries(seed.cursors ?? {})) {\n cursors.set(namespace, new Map(Object.entries(partitions)));\n }\n for (const [namespace, keys] of Object.entries(seed.claims ?? {})) {\n claims.set(namespace, new Set(keys));\n }\n for (const [namespace, entries] of Object.entries(seed.digests ?? {})) {\n digests.set(namespace, new Map(Object.entries(entries)));\n }\n\n /** Wraps an operation so `stateError` short-circuits every one of them. */\n const op = <A extends unknown[], R>(fn: (...args: A) => R) =>\n vi.fn(async (...args: A): Promise<R> => {\n if (error) {\n throw error;\n }\n return fn(...args);\n });\n\n const state: MockState = {\n mapping: {\n get: op((namespace: string, key: string, side: 'left' | 'right' = 'left') => {\n const pairs = mappings.get(namespace);\n if (!pairs) {\n return null;\n }\n if (side === 'left') {\n return pairs.get(key) ?? null;\n }\n for (const [left, right] of pairs) {\n if (right === key) {\n return left;\n }\n }\n return null;\n }),\n put: op((namespace: string, left: string, right: string) => {\n const pairs = mappings.get(namespace) ?? new Map<string, string>();\n assertNotRepointed(namespace, pairs, left, right);\n pairs.set(left, right);\n mappings.set(namespace, pairs);\n }),\n },\n cursor: {\n // The committed watermark: what *this* run staged is deliberately not in\n // the answer, exactly as the real store describes it.\n get: op((namespace: string, partitionKey = '') => cursors.get(namespace)?.get(partitionKey)),\n set: op((namespace: string, value: unknown, partitionKey = '') => {\n const partitions = stagedCursors.get(namespace) ?? new Map<string, unknown>();\n partitions.set(partitionKey, value);\n stagedCursors.set(namespace, partitions);\n }),\n },\n // First caller wins, like the real claim — so a test can drive both the\n // fresh and the duplicate path without reconfiguring the mock. A claim is\n // never handed on here: a TTL is a wall-clock window, and no unit test\n // outlives the shortest one the store accepts.\n claim: op((namespace: string, key: string, opts?: { ttlSeconds?: number }) => {\n assertTtlInRange(opts?.ttlSeconds);\n const held = claims.get(namespace) ?? new Set<string>();\n if (held.has(key)) {\n return false;\n }\n held.add(key);\n claims.set(namespace, held);\n return true;\n }),\n digest: {\n unchanged: op((namespace: string, entityKey: string, digest: string) => digests.get(namespace)?.get(entityKey) === digest),\n set: op((namespace: string, entityKey: string, digest: string) => {\n const entries = stagedDigests.get(namespace) ?? new Map<string, string>();\n entries.set(entityKey, digest);\n stagedDigests.set(namespace, entries);\n }),\n },\n };\n\n const completeRun = (): void => {\n for (const [namespace, partitions] of stagedCursors) {\n const committed = cursors.get(namespace) ?? new Map<string, unknown>();\n for (const [partitionKey, value] of partitions) {\n committed.set(partitionKey, value);\n }\n cursors.set(namespace, committed);\n }\n for (const [namespace, entries] of stagedDigests) {\n const committed = digests.get(namespace) ?? new Map<string, string>();\n for (const [entityKey, digest] of entries) {\n committed.set(entityKey, digest);\n }\n digests.set(namespace, committed);\n }\n stagedCursors.clear();\n stagedDigests.clear();\n };\n\n return { state, completeRun };\n}\n","import { NodeError } from '@revenexx/integrations-node-sdk';\n\n/**\n * The two rules the tenant state store keeps that neither the mock context nor\n * the local preview would otherwise have any reason to keep — and both of which\n * a node author only finds out about in production if we do not.\n *\n * They live here rather than in either caller because the testing harness and\n * the preview must refuse the same things: a node that passes its unit tests and\n * then trips the store on its first preview run has learnt nothing from either.\n * The rest of what the store promises — that a granted claim really excludes a\n * parallel run, that an undeclared namespace is refused — is the engine's, and\n * `specs/workflow-state.md` in the SDK records it as such.\n */\n\n/** Mirrors the engine's default claim lifetime (7 days). */\nexport const DEFAULT_CLAIM_TTL_SECONDS = 604_800;\n\n/** The window the store accepts: one second to one year. */\nexport const MIN_CLAIM_TTL_SECONDS = 1;\nexport const MAX_CLAIM_TTL_SECONDS = 31_536_000;\n\n/**\n * A `ttlSeconds` outside the accepted window is refused rather than clamped: the\n * figure is the duplicate-suppression window *and* the retry window, so a node\n * quietly given a different one than it asked for would suppress deliveries for\n * a stretch its author never chose.\n */\nexport function assertTtlInRange(ttlSeconds: number | undefined): void {\n if (ttlSeconds === undefined) {\n return;\n }\n if (!Number.isFinite(ttlSeconds) || ttlSeconds < MIN_CLAIM_TTL_SECONDS || ttlSeconds > MAX_CLAIM_TTL_SECONDS) {\n throw new NodeError('INVALID_TTL', `ttlSeconds must be between ${MIN_CLAIM_TTL_SECONDS} and ${MAX_CLAIM_TTL_SECONDS}, got ${String(ttlSeconds)}.`);\n }\n}\n\n/**\n * Re-pointing one side of an existing pair is refused, in both directions: an id\n * correlated two ways is always a bug, and no later sync can untangle it —\n * whichever of the two answers a lookup happens to give, half the records it\n * touches are the wrong ones. Writing the same pair again is not a re-point and\n * is allowed, so a node that puts unconditionally on every run stays green.\n */\nexport function assertNotRepointed(namespace: string, pairs: Iterable<[string, string]>, left: string, right: string): void {\n for (const [existingLeft, existingRight] of pairs) {\n if (existingLeft === left && existingRight !== right) {\n throw new NodeError('MAPPING_CONFLICT', `'${left}' is already correlated with '${existingRight}' in namespace '${namespace}'.`);\n }\n if (existingRight === right && existingLeft !== left) {\n throw new NodeError('MAPPING_CONFLICT', `'${right}' is already correlated with '${existingLeft}' in namespace '${namespace}'.`);\n }\n }\n}\n","import type { INodeAuthorContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\n\n/**\n * Builds an {@link INodeAuthorContext} for unit-testing a node's *author-time*\n * resolvers (`loadOptions`, `resolveConfigSchema`, `resolveOutputs`). Until this\n * package existed, this factory was reinvented inline in each repo's resolver\n * tests. Mirrors {@link createMockContext}: `secrets.get` / `credentials.get`\n * are `vi.fn()`-backed and seedable.\n */\n\nexport type MockAuthorLogger = {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n};\n\nexport type MockAuthorContext = INodeAuthorContext & {\n logger: MockAuthorLogger;\n secrets: { get: ReturnType<typeof vi.fn> };\n credentials: { get: ReturnType<typeof vi.fn> };\n};\n\nexport interface CreateAuthorContextOptions {\n signal?: AbortSignal;\n /** Preferred locale for resolved labels. */\n locale?: string;\n secrets?: Record<string, string>;\n secretsError?: Error;\n credentials?: Record<string, Record<string, unknown>>;\n credentialsError?: Error;\n}\n\nexport function createAuthorContext(config: Record<string, unknown> = {}, options: CreateAuthorContextOptions = {}): MockAuthorContext {\n const signal = options.signal ?? new AbortController().signal;\n\n const secretsGet = options.secretsError\n ? vi.fn(async () => {\n throw options.secretsError;\n })\n : vi.fn(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn(async () => {\n throw options.credentialsError;\n })\n : vi.fn(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n },\n config,\n secrets: { get: secretsGet },\n credentials: { get: credentialsGet },\n locale: options.locale,\n };\n}\n","import { vi } from 'vitest';\n\n/**\n * Utilities for stubbing the global `fetch` so a credential's `resolve` /\n * `test` (which reach an OAuth token endpoint via the SDK's `postForm`) or a\n * node's `execute` (which uses `safeFetch` → global `fetch`) can be\n * unit-tested without touching the network. Builds real `Response` objects so\n * `res.ok` / `res.status` / `res.text()` / `res.json()` all behave exactly as\n * in production.\n */\n\nexport interface StubResponseInit {\n status?: number;\n headers?: Record<string, string>;\n /** JSON body — serialized and served as `application/json` unless `body` is set. */\n json?: unknown;\n /** Raw string body. Takes precedence over `json`. */\n body?: string;\n}\n\nexport interface StubbedRequest {\n url: string;\n method: string;\n init?: RequestInit;\n}\n\nexport type FetchHandler = (request: StubbedRequest) => StubResponseInit | Response | Promise<StubResponseInit | Response>;\n\n/** Builds a real `Response` from a {@link StubResponseInit}. */\nexport function buildResponse(init: StubResponseInit): Response {\n const headers = new Headers(init.headers ?? {});\n let body: string | undefined;\n if (init.body !== undefined) {\n body = init.body;\n } else if (init.json !== undefined) {\n body = JSON.stringify(init.json);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n return new Response(body, { status: init.status ?? 200, headers });\n}\n\nexport interface StubFetchResult {\n /** The `vi.fn()` installed as `globalThis.fetch` — assert calls on it. */\n fetchMock: ReturnType<typeof vi.fn>;\n /** Restores the previous `globalThis.fetch`. */\n restore(): void;\n}\n\n/**\n * Replaces `globalThis.fetch` with a `vi.fn()` driven by `handler`. Pass a\n * static {@link StubResponseInit} to answer every request identically, or a\n * {@link FetchHandler} to branch on url/method. Call `restore()` when done\n * (e.g. in `afterEach`).\n */\nexport function stubFetch(handler: FetchHandler | StubResponseInit): StubFetchResult {\n const previous = globalThis.fetch;\n const resolveInit: FetchHandler = typeof handler === 'function' ? handler : () => handler;\n\n const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();\n const out = await resolveInit({ url, method, init });\n return out instanceof Response ? out : buildResponse(out);\n });\n\n globalThis.fetch = fetchMock as unknown as typeof fetch;\n return {\n fetchMock,\n restore() {\n globalThis.fetch = previous;\n },\n };\n}\n\nexport interface FakeTokenEndpointOptions {\n /** Only answer requests to this exact URL; other requests 404. Omit to answer any URL. */\n tokenUrl?: string;\n accessToken?: string;\n tokenType?: string;\n /** Seconds until expiry (OAuth `expires_in`). Set `null` to omit the field. */\n expiresIn?: number | null;\n /** Included as `refresh_token` when set (e.g. to assert rotation). */\n refreshToken?: string;\n /** Extra fields merged into the token response body. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * A {@link FetchHandler} that emulates an OAuth token endpoint, returning\n * `{ access_token, token_type, expires_in, refresh_token? }`. Compose with\n * {@link stubFetch} to unit-test `oauth2-*` credentials' `resolve` / OAuth\n * `exchangeCode`.\n */\nexport function fakeTokenEndpoint(options: FakeTokenEndpointOptions = {}): FetchHandler {\n const { tokenUrl, accessToken = 'fake-access-token', tokenType = 'Bearer', expiresIn = 3600, refreshToken, extra } = options;\n\n return ({ url }) => {\n if (tokenUrl && url !== tokenUrl) {\n return { status: 404, json: { error: `no stub for ${url}` } };\n }\n const json: Record<string, unknown> = {\n access_token: accessToken,\n token_type: tokenType,\n ...(expiresIn !== null ? { expires_in: expiresIn } : {}),\n ...(refreshToken !== undefined ? { refresh_token: refreshToken } : {}),\n ...extra,\n };\n return { status: 200, json };\n };\n}\n","import type { ICredential, ICredentialContext, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';\nimport { isOAuthAuthorizeCredential } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\n\n/**\n * Harness for unit-testing a credential type's `test` / `resolve` / 3-legged\n * OAuth without the credentials broker or a real provider. Combine with\n * {@link stubFetch} / {@link fakeTokenEndpoint} to drive the token endpoint,\n * and inspect the returned `persistDurableCreds` spy to assert refresh-token\n * rotation.\n */\n\nexport type MockCredentialLogger = {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n};\n\nexport type MockCredentialContext = ICredentialContext & {\n logger: MockCredentialLogger;\n /** Spy wired to `ctx.persistDurableCreds`; assert `.toHaveBeenCalledWith(...)`. */\n persistDurableCreds: ReturnType<typeof vi.fn>;\n};\n\nexport interface CreateCredentialContextOptions {\n signal?: AbortSignal;\n}\n\nexport function createCredentialContext(options: CreateCredentialContextOptions = {}): MockCredentialContext {\n const signal = options.signal ?? new AbortController().signal;\n const persistDurableCreds = vi.fn(async (_durableCreds: Record<string, unknown>) => {});\n return {\n signal,\n logger: {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n },\n persistDurableCreds,\n };\n}\n\nexport interface RunCredentialTestOptions {\n config: Record<string, unknown>;\n signal?: AbortSignal;\n}\n\n/** Runs a credential's `test(ctx, config)` and returns its result. */\nexport async function runCredentialTest(credential: ICredential, options: RunCredentialTestOptions): Promise<ICredentialTestResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.test(ctx, options.config);\n}\n\nexport interface RunCredentialResolveOptions {\n config: Record<string, unknown>;\n /** System-managed long-lived secrets (e.g. an OAuth `refresh_token`). */\n durableCreds?: Record<string, unknown> | null;\n signal?: AbortSignal;\n}\n\nexport interface RunCredentialResolveResult {\n result: ICredentialResolveResult;\n /** Spy wired to `ctx.persistDurableCreds` — assert rotation happened. */\n persistDurableCreds: ReturnType<typeof vi.fn>;\n /** The context used, for further assertions (logger calls, etc.). */\n ctx: MockCredentialContext;\n}\n\n/** Runs a credential's `resolve(ctx, config, durableCreds)` and captures rotation. */\nexport async function runCredentialResolve(credential: ICredential, options: RunCredentialResolveOptions): Promise<RunCredentialResolveResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n const result = await credential.resolve(ctx, options.config, options.durableCreds ?? null);\n return { result, persistDurableCreds: ctx.persistDurableCreds, ctx };\n}\n\nexport interface RunOAuthAuthorizeUrlOptions {\n config: Record<string, unknown>;\n redirectUri: string;\n state: string;\n signal?: AbortSignal;\n}\n\n/** Runs `buildAuthorizeUrl` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthAuthorizeUrl(credential: ICredential, options: RunOAuthAuthorizeUrlOptions): Promise<{ authorizeUrl: string; codeVerifier?: string }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.buildAuthorizeUrl(ctx, options.config, {\n redirectUri: options.redirectUri,\n state: options.state,\n });\n}\n\nexport interface RunOAuthExchangeCodeOptions {\n config: Record<string, unknown>;\n code: string;\n redirectUri: string;\n codeVerifier?: string;\n signal?: AbortSignal;\n}\n\n/** Runs `exchangeCode` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthExchangeCode(credential: ICredential, options: RunOAuthExchangeCodeOptions): Promise<{ durableCreds: Record<string, unknown> }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.exchangeCode(ctx, options.config, {\n code: options.code,\n redirectUri: options.redirectUri,\n codeVerifier: options.codeVerifier,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,oBAAmB;;;ACDnB,mCAA0B;AAmBnB,IAAM,wBAAwB;AAC9B,IAAM,wBAAwB;AAQ9B,SAAS,iBAAiB,YAAsC;AACrE,MAAI,eAAe,QAAW;AAC5B;AAAA,EACF;AACA,MAAI,CAAC,OAAO,SAAS,UAAU,KAAK,aAAa,yBAAyB,aAAa,uBAAuB;AAC5G,UAAM,IAAI,uCAAU,eAAe,8BAA8B,qBAAqB,QAAQ,qB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Q,OAAO,CAAC;AAC9D,SAAO,WAAW,KAAK,KAAK,QAAQ,MAAM;AAC5C;AAkBA,eAAsB,qBAAqB,YAAyB,SAA2E;AAC7I,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,QAAM,SAAS,MAAM,WAAW,QAAQ,KAAK,QAAQ,QAAQ,QAAQ,gBAAgB,IAAI;AACzF,SAAO,EAAE,QAAQ,qBAAqB,IAAI,qBAAqB,IAAI;AACrE;AAUA,eAAsB,qBAAqB,YAAyB,SAAgG;AAClK,MAAI,KAAC,0DAA2B,UAAU,GAAG;AAC3C,UAAM,IAAI,MAAM,GAAG,WAAW,YAAY,IAAI,qCAAqC;AAAA,EACrF;AACA,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,SAAO,WAAW,kBAAkB,KAAK,QAAQ,QAAQ;AAAA,IACvD,aAAa,QAAQ;AAAA,IACrB,OAAO,QAAQ;AAAA,EACjB,CAAC;AACH;AAWA,eAAsB,qBAAqB,YAAyB,SAA0F;AAC5J,MAAI,KAAC,0DAA2B,UAAU,GAAG;AAC3C,UAAM,IAAI,MAAM,GAAG,WAAW,YAAY,IAAI,qCAAqC;AAAA,EACrF;AACA,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,SAAO,WAAW,aAAa,KAAK,QAAQ,QAAQ;AAAA,IAClD,MAAM,QAAQ;AAAA,IACd,aAAa,QAAQ;AAAA,IACrB,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;","names":["import_vitest","import_vitest","import_integrations_node_sdk","import_vitest"]}
|
|
1
|
+
{"version":3,"sources":["../../src/testing/index.ts","../../src/testing/context.ts","../../src/state-rules.ts","../../src/testing/author.ts","../../src/testing/fetch.ts","../../src/testing/credentials.ts"],"sourcesContent":["export * from './context.js';\nexport * from './author.js';\nexport * from './fetch.js';\nexport * from './credentials.js';\nexport type * from './mock.js';\n","import type { INodeContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\nimport { assertNotRepointed, assertTtlInRange } from '../state-rules.js';\n\n/**\n * Drop-in replacement for the `createMockContext` helper that was, until this\n * package existed, copy-pasted byte-for-byte into every node repo's\n * `tests/helpers/context.ts`. Builds a full {@link INodeContext} with\n * `vi.fn<AnyFn>()`-backed `logger`, `secrets.get`, `credentials.get` and `state` so a\n * node's `execute` can be unit-tested in isolation.\n *\n * The state mock is **stateful on purpose**: what the node writes, it reads\n * back. A node's interesting behaviour is precisely the second run — the one\n * that finds the mapping it created the first time — and a mock that forgets\n * would only ever exercise the create branch. It is the one place an author can\n * test writes at all: in the real product, author-time execution is read-only.\n *\n * It reads back *when the store would let it*, which is not the same for all\n * four roles (SDK 1.0.0, `specs/workflow-state.md`): a mapping and a claim take\n * effect immediately, a cursor and a digest are staged and adopted only once the\n * run completes. So `cursor.get` after `cursor.set` still answers what the last\n * completed run left — call {@link MockContext.completeRun} between two\n * `execute` calls to play the second run, and leave it uncalled to play the run\n * that failed and left the watermark where it was.\n */\n\nexport type MockLogger = {\n info: AnyMock;\n warn: AnyMock;\n error: AnyMock;\n};\n\nexport type MockSecrets = {\n get: AnyMock;\n};\n\nexport type MockCredentials = {\n get: AnyMock;\n};\n\n/** Every state operation is a `vi.fn<AnyFn>()`, so calls can be asserted on. */\nexport type MockState = {\n mapping: { get: AnyMock; put: AnyMock };\n cursor: { get: AnyMock; set: AnyMock };\n claim: AnyMock;\n digest: { unchanged: AnyMock; set: AnyMock };\n};\n\n/**\n * What the store already knows when the node starts — the \"this ran before\"\n * half of any sync test.\n */\nexport interface MockStateSeed {\n /** namespace -> { leftKey: rightKey }; readable from either side. */\n mappings?: Record<string, Record<string, string>>;\n /** namespace -> partitionKey ('' for the unpartitioned one) -> watermark. */\n cursors?: Record<string, Record<string, unknown>>;\n /** namespace -> keys already claimed, so `claim` returns false for them. */\n claims?: Record<string, string[]>;\n /** namespace -> { entityKey: digest }. */\n digests?: Record<string, Record<string, string>>;\n}\n\nexport type MockContext = INodeContext & {\n logger: MockLogger;\n secrets: MockSecrets;\n credentials: MockCredentials;\n state: MockState;\n /**\n * Adopts what this run staged — the cursors and digests it set — the way the\n * engine does when a run completes. Not part of {@link INodeContext}: it is\n * the harness standing in for the run's own ending, and a node can never call\n * it. A test that never calls it has played a run that did not complete.\n */\n completeRun: () => void;\n};\n\nexport interface CreateMockContextOptions {\n signal?: AbortSignal;\n /** Secret key -> value returned by `secrets.get`. Unknown keys fall back to a deterministic stub. */\n secrets?: Record<string, string>;\n /** When set, `secrets.get` rejects with this error instead of resolving. */\n secretsError?: Error;\n /** Credential instance id -> resolved access data returned by `credentials.get`. */\n credentials?: Record<string, Record<string, unknown>>;\n /** When set, `credentials.get` rejects with this error instead of resolving. */\n credentialsError?: Error;\n /** What the state store already holds when the node starts. */\n state?: MockStateSeed;\n /**\n * When set, every state call rejects with this error — the shape of the\n * engine refusing a namespace the workflow never declared.\n */\n stateError?: Error;\n}\n\nexport function createMockContext(options: CreateMockContextOptions = {}): MockContext {\n const signal = options.signal ?? new AbortController().signal;\n const { state, completeRun } = createMockState(options.state, options.stateError);\n\n const secretsGet = options.secretsError\n ? vi.fn<AnyFn>(async () => {\n throw options.secretsError;\n })\n : vi.fn<AnyFn>(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn<AnyFn>(async () => {\n throw options.credentialsError;\n })\n : vi.fn<AnyFn>(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn<AnyFn>(),\n warn: vi.fn<AnyFn>(),\n error: vi.fn<AnyFn>(),\n },\n secrets: {\n get: secretsGet,\n },\n credentials: {\n get: credentialsGet,\n },\n state,\n completeRun,\n };\n}\n\n/**\n * A tiny in-memory stand-in for the four state roles. Seeds are copied rather\n * than referenced, so a test that writes cannot leak into the next one.\n *\n * The write calls split the way the store does. A mapping and a claim land in\n * the committed maps at once; a cursor and a digest land in a staging map that\n * only `completeRun` folds in, so a read during the run answers what the last\n * completed one left. That is the whole reason there are four operations rather\n * than a generic get/set, and a mock that adopted everything immediately would\n * hide the case the rule exists for: the run that fails after advancing its\n * watermark.\n */\nfunction createMockState(seed: MockStateSeed = {}, error?: Error): { state: MockState; completeRun: () => void } {\n const mappings = new Map<string, Map<string, string>>();\n const cursors = new Map<string, Map<string, unknown>>();\n const claims = new Map<string, Set<string>>();\n const digests = new Map<string, Map<string, string>>();\n /** What this run has staged: adopted by `completeRun`, dropped otherwise. */\n const stagedCursors = new Map<string, Map<string, unknown>>();\n const stagedDigests = new Map<string, Map<string, string>>();\n\n for (const [namespace, pairs] of Object.entries(seed.mappings ?? {})) {\n mappings.set(namespace, new Map(Object.entries(pairs)));\n }\n for (const [namespace, partitions] of Object.entries(seed.cursors ?? {})) {\n cursors.set(namespace, new Map(Object.entries(partitions)));\n }\n for (const [namespace, keys] of Object.entries(seed.claims ?? {})) {\n claims.set(namespace, new Set(keys));\n }\n for (const [namespace, entries] of Object.entries(seed.digests ?? {})) {\n digests.set(namespace, new Map(Object.entries(entries)));\n }\n\n /** Wraps an operation so `stateError` short-circuits every one of them. */\n const op = <A extends unknown[], R>(fn: (...args: A) => R) =>\n vi.fn(async (...args: A): Promise<R> => {\n if (error) {\n throw error;\n }\n return fn(...args);\n });\n\n const state: MockState = {\n mapping: {\n get: op((namespace: string, key: string, side: 'left' | 'right' = 'left') => {\n const pairs = mappings.get(namespace);\n if (!pairs) {\n return null;\n }\n if (side === 'left') {\n return pairs.get(key) ?? null;\n }\n for (const [left, right] of pairs) {\n if (right === key) {\n return left;\n }\n }\n return null;\n }),\n put: op((namespace: string, left: string, right: string) => {\n const pairs = mappings.get(namespace) ?? new Map<string, string>();\n assertNotRepointed(namespace, pairs, left, right);\n pairs.set(left, right);\n mappings.set(namespace, pairs);\n }),\n },\n cursor: {\n // The committed watermark: what *this* run staged is deliberately not in\n // the answer, exactly as the real store describes it.\n get: op((namespace: string, partitionKey = '') => cursors.get(namespace)?.get(partitionKey)),\n set: op((namespace: string, value: unknown, partitionKey = '') => {\n const partitions = stagedCursors.get(namespace) ?? new Map<string, unknown>();\n partitions.set(partitionKey, value);\n stagedCursors.set(namespace, partitions);\n }),\n },\n // First caller wins, like the real claim — so a test can drive both the\n // fresh and the duplicate path without reconfiguring the mock. A claim is\n // never handed on here: a TTL is a wall-clock window, and no unit test\n // outlives the shortest one the store accepts.\n claim: op((namespace: string, key: string, opts?: { ttlSeconds?: number }) => {\n assertTtlInRange(opts?.ttlSeconds);\n const held = claims.get(namespace) ?? new Set<string>();\n if (held.has(key)) {\n return false;\n }\n held.add(key);\n claims.set(namespace, held);\n return true;\n }),\n digest: {\n unchanged: op((namespace: string, entityKey: string, digest: string) => digests.get(namespace)?.get(entityKey) === digest),\n set: op((namespace: string, entityKey: string, digest: string) => {\n const entries = stagedDigests.get(namespace) ?? new Map<string, string>();\n entries.set(entityKey, digest);\n stagedDigests.set(namespace, entries);\n }),\n },\n };\n\n const completeRun = (): void => {\n for (const [namespace, partitions] of stagedCursors) {\n const committed = cursors.get(namespace) ?? new Map<string, unknown>();\n for (const [partitionKey, value] of partitions) {\n committed.set(partitionKey, value);\n }\n cursors.set(namespace, committed);\n }\n for (const [namespace, entries] of stagedDigests) {\n const committed = digests.get(namespace) ?? new Map<string, string>();\n for (const [entityKey, digest] of entries) {\n committed.set(entityKey, digest);\n }\n digests.set(namespace, committed);\n }\n stagedCursors.clear();\n stagedDigests.clear();\n };\n\n return { state, completeRun };\n}\n","import { NodeError } from '@revenexx/integrations-node-sdk';\n\n/**\n * The two rules the tenant state store keeps that neither the mock context nor\n * the local preview would otherwise have any reason to keep — and both of which\n * a node author only finds out about in production if we do not.\n *\n * They live here rather than in either caller because the testing harness and\n * the preview must refuse the same things: a node that passes its unit tests and\n * then trips the store on its first preview run has learnt nothing from either.\n * The rest of what the store promises — that a granted claim really excludes a\n * parallel run, that an undeclared namespace is refused — is the engine's, and\n * `specs/workflow-state.md` in the SDK records it as such.\n */\n\n/** Mirrors the engine's default claim lifetime (7 days). */\nexport const DEFAULT_CLAIM_TTL_SECONDS = 604_800;\n\n/** The window the store accepts: one second to one year. */\nexport const MIN_CLAIM_TTL_SECONDS = 1;\nexport const MAX_CLAIM_TTL_SECONDS = 31_536_000;\n\n/**\n * A `ttlSeconds` outside the accepted window is refused rather than clamped: the\n * figure is the duplicate-suppression window *and* the retry window, so a node\n * quietly given a different one than it asked for would suppress deliveries for\n * a stretch its author never chose.\n */\nexport function assertTtlInRange(ttlSeconds: number | undefined): void {\n if (ttlSeconds === undefined) {\n return;\n }\n if (!Number.isFinite(ttlSeconds) || ttlSeconds < MIN_CLAIM_TTL_SECONDS || ttlSeconds > MAX_CLAIM_TTL_SECONDS) {\n throw new NodeError('INVALID_TTL', `ttlSeconds must be between ${MIN_CLAIM_TTL_SECONDS} and ${MAX_CLAIM_TTL_SECONDS}, got ${String(ttlSeconds)}.`);\n }\n}\n\n/**\n * Re-pointing one side of an existing pair is refused, in both directions: an id\n * correlated two ways is always a bug, and no later sync can untangle it —\n * whichever of the two answers a lookup happens to give, half the records it\n * touches are the wrong ones. Writing the same pair again is not a re-point and\n * is allowed, so a node that puts unconditionally on every run stays green.\n */\nexport function assertNotRepointed(namespace: string, pairs: Iterable<[string, string]>, left: string, right: string): void {\n for (const [existingLeft, existingRight] of pairs) {\n if (existingLeft === left && existingRight !== right) {\n throw new NodeError('MAPPING_CONFLICT', `'${left}' is already correlated with '${existingRight}' in namespace '${namespace}'.`);\n }\n if (existingRight === right && existingLeft !== left) {\n throw new NodeError('MAPPING_CONFLICT', `'${right}' is already correlated with '${existingLeft}' in namespace '${namespace}'.`);\n }\n }\n}\n","import type { INodeAuthorContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\n\n/**\n * Builds an {@link INodeAuthorContext} for unit-testing a node's *author-time*\n * resolvers (`loadOptions`, `resolveConfigSchema`, `resolveOutputs`). Until this\n * package existed, this factory was reinvented inline in each repo's resolver\n * tests. Mirrors {@link createMockContext}: `secrets.get` / `credentials.get`\n * are `vi.fn<AnyFn>()`-backed and seedable.\n */\n\nexport type MockAuthorLogger = {\n info: AnyMock;\n warn: AnyMock;\n error: AnyMock;\n};\n\nexport type MockAuthorContext = INodeAuthorContext & {\n logger: MockAuthorLogger;\n secrets: { get: AnyMock };\n credentials: { get: AnyMock };\n};\n\nexport interface CreateAuthorContextOptions {\n signal?: AbortSignal;\n /** Preferred locale for resolved labels. */\n locale?: string;\n secrets?: Record<string, string>;\n secretsError?: Error;\n credentials?: Record<string, Record<string, unknown>>;\n credentialsError?: Error;\n}\n\nexport function createAuthorContext(config: Record<string, unknown> = {}, options: CreateAuthorContextOptions = {}): MockAuthorContext {\n const signal = options.signal ?? new AbortController().signal;\n\n const secretsGet = options.secretsError\n ? vi.fn<AnyFn>(async () => {\n throw options.secretsError;\n })\n : vi.fn<AnyFn>(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn<AnyFn>(async () => {\n throw options.credentialsError;\n })\n : vi.fn<AnyFn>(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn<AnyFn>(),\n warn: vi.fn<AnyFn>(),\n error: vi.fn<AnyFn>(),\n },\n config,\n secrets: { get: secretsGet },\n credentials: { get: credentialsGet },\n locale: options.locale,\n };\n}\n","import { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\n\n/**\n * Utilities for stubbing the global `fetch` so a credential's `resolve` /\n * `test` (which reach an OAuth token endpoint via the SDK's `postForm`) or a\n * node's `execute` (which uses `safeFetch` → global `fetch`) can be\n * unit-tested without touching the network. Builds real `Response` objects so\n * `res.ok` / `res.status` / `res.text()` / `res.json()` all behave exactly as\n * in production.\n */\n\nexport interface StubResponseInit {\n status?: number;\n headers?: Record<string, string>;\n /** JSON body — serialized and served as `application/json` unless `body` is set. */\n json?: unknown;\n /** Raw string body. Takes precedence over `json`. */\n body?: string;\n}\n\nexport interface StubbedRequest {\n url: string;\n method: string;\n init?: RequestInit;\n}\n\nexport type FetchHandler = (request: StubbedRequest) => StubResponseInit | Response | Promise<StubResponseInit | Response>;\n\n/** Builds a real `Response` from a {@link StubResponseInit}. */\nexport function buildResponse(init: StubResponseInit): Response {\n const headers = new Headers(init.headers ?? {});\n let body: string | undefined;\n if (init.body !== undefined) {\n body = init.body;\n } else if (init.json !== undefined) {\n body = JSON.stringify(init.json);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n return new Response(body, { status: init.status ?? 200, headers });\n}\n\nexport interface StubFetchResult {\n /** The `vi.fn<AnyFn>()` installed as `globalThis.fetch` — assert calls on it. */\n fetchMock: AnyMock;\n /** Restores the previous `globalThis.fetch`. */\n restore(): void;\n}\n\n/**\n * Replaces `globalThis.fetch` with a `vi.fn<AnyFn>()` driven by `handler`. Pass a\n * static {@link StubResponseInit} to answer every request identically, or a\n * {@link FetchHandler} to branch on url/method. Call `restore()` when done\n * (e.g. in `afterEach`).\n */\nexport function stubFetch(handler: FetchHandler | StubResponseInit): StubFetchResult {\n const previous = globalThis.fetch;\n const resolveInit: FetchHandler = typeof handler === 'function' ? handler : () => handler;\n\n const fetchMock = vi.fn<AnyFn>(async (input: RequestInfo | URL, init?: RequestInit) => {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();\n const out = await resolveInit({ url, method, init });\n return out instanceof Response ? out : buildResponse(out);\n });\n\n globalThis.fetch = fetchMock as unknown as typeof fetch;\n return {\n fetchMock,\n restore() {\n globalThis.fetch = previous;\n },\n };\n}\n\nexport interface FakeTokenEndpointOptions {\n /** Only answer requests to this exact URL; other requests 404. Omit to answer any URL. */\n tokenUrl?: string;\n accessToken?: string;\n tokenType?: string;\n /** Seconds until expiry (OAuth `expires_in`). Set `null` to omit the field. */\n expiresIn?: number | null;\n /** Included as `refresh_token` when set (e.g. to assert rotation). */\n refreshToken?: string;\n /** Extra fields merged into the token response body. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * A {@link FetchHandler} that emulates an OAuth token endpoint, returning\n * `{ access_token, token_type, expires_in, refresh_token? }`. Compose with\n * {@link stubFetch} to unit-test `oauth2-*` credentials' `resolve` / OAuth\n * `exchangeCode`.\n */\nexport function fakeTokenEndpoint(options: FakeTokenEndpointOptions = {}): FetchHandler {\n const { tokenUrl, accessToken = 'fake-access-token', tokenType = 'Bearer', expiresIn = 3600, refreshToken, extra } = options;\n\n return ({ url }) => {\n if (tokenUrl && url !== tokenUrl) {\n return { status: 404, json: { error: `no stub for ${url}` } };\n }\n const json: Record<string, unknown> = {\n access_token: accessToken,\n token_type: tokenType,\n ...(expiresIn !== null ? { expires_in: expiresIn } : {}),\n ...(refreshToken !== undefined ? { refresh_token: refreshToken } : {}),\n ...extra,\n };\n return { status: 200, json };\n };\n}\n","import type { ICredential, ICredentialContext, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';\nimport { isOAuthAuthorizeCredential } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\n\n/**\n * Harness for unit-testing a credential type's `test` / `resolve` / 3-legged\n * OAuth without the credentials broker or a real provider. Combine with\n * {@link stubFetch} / {@link fakeTokenEndpoint} to drive the token endpoint,\n * and inspect the returned `persistDurableCreds` spy to assert refresh-token\n * rotation.\n */\n\nexport type MockCredentialLogger = {\n info: AnyMock;\n warn: AnyMock;\n error: AnyMock;\n};\n\nexport type MockCredentialContext = ICredentialContext & {\n logger: MockCredentialLogger;\n /** Spy wired to `ctx.persistDurableCreds`; assert `.toHaveBeenCalledWith(...)`. */\n persistDurableCreds: AnyMock;\n};\n\nexport interface CreateCredentialContextOptions {\n signal?: AbortSignal;\n}\n\nexport function createCredentialContext(options: CreateCredentialContextOptions = {}): MockCredentialContext {\n const signal = options.signal ?? new AbortController().signal;\n const persistDurableCreds = vi.fn<AnyFn>(async (_durableCreds: Record<string, unknown>) => {});\n return {\n signal,\n logger: {\n info: vi.fn<AnyFn>(),\n warn: vi.fn<AnyFn>(),\n error: vi.fn<AnyFn>(),\n },\n persistDurableCreds,\n };\n}\n\nexport interface RunCredentialTestOptions {\n config: Record<string, unknown>;\n signal?: AbortSignal;\n}\n\n/** Runs a credential's `test(ctx, config)` and returns its result. */\nexport async function runCredentialTest(credential: ICredential, options: RunCredentialTestOptions): Promise<ICredentialTestResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.test(ctx, options.config);\n}\n\nexport interface RunCredentialResolveOptions {\n config: Record<string, unknown>;\n /** System-managed long-lived secrets (e.g. an OAuth `refresh_token`). */\n durableCreds?: Record<string, unknown> | null;\n signal?: AbortSignal;\n}\n\nexport interface RunCredentialResolveResult {\n result: ICredentialResolveResult;\n /** Spy wired to `ctx.persistDurableCreds` — assert rotation happened. */\n persistDurableCreds: AnyMock;\n /** The context used, for further assertions (logger calls, etc.). */\n ctx: MockCredentialContext;\n}\n\n/** Runs a credential's `resolve(ctx, config, durableCreds)` and captures rotation. */\nexport async function runCredentialResolve(credential: ICredential, options: RunCredentialResolveOptions): Promise<RunCredentialResolveResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n const result = await credential.resolve(ctx, options.config, options.durableCreds ?? null);\n return { result, persistDurableCreds: ctx.persistDurableCreds, ctx };\n}\n\nexport interface RunOAuthAuthorizeUrlOptions {\n config: Record<string, unknown>;\n redirectUri: string;\n state: string;\n signal?: AbortSignal;\n}\n\n/** Runs `buildAuthorizeUrl` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthAuthorizeUrl(credential: ICredential, options: RunOAuthAuthorizeUrlOptions): Promise<{ authorizeUrl: string; codeVerifier?: string }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.buildAuthorizeUrl(ctx, options.config, {\n redirectUri: options.redirectUri,\n state: options.state,\n });\n}\n\nexport interface RunOAuthExchangeCodeOptions {\n config: Record<string, unknown>;\n code: string;\n redirectUri: string;\n codeVerifier?: string;\n signal?: AbortSignal;\n}\n\n/** Runs `exchangeCode` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthExchangeCode(credential: ICredential, options: RunOAuthExchangeCodeOptions): Promise<{ durableCreds: Record<string, unknown> }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.exchangeCode(ctx, options.config, {\n code: options.code,\n redirectUri: options.redirectUri,\n codeVerifier: options.codeVerifier,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,oBAAmB;;;ACDnB,mCAA0B;AAmBnB,IAAM,wBAAwB;AAC9B,IAAM,wBAAwB;AAQ9B,SAAS,iBAAiB,YAAsC;AACrE,MAAI,eAAe,QAAW;AAC5B;AAAA,EACF;AACA,MAAI,CAAC,OAAO,SAAS,UAAU,KAAK,aAAa,yBAAyB,aAAa,uBAAuB;AAC5G,UAAM,IAAI,uCAAU,eAAe,8BAA8B,qBAAqB,QAAQ,qBAAqB,SAAS,OAAO,UAAU,CAAC,GAAG;AAAA,EACnJ;AACF;AASO,SAAS,mBAAmB,WAAmB,OAAmC,MAAc,OAAqB;AAC1H,aAAW,CAAC,cAAc,aAAa,KAAK,OAAO;AACjD,QAAI,iBAAiB,QAAQ,kBAAkB,OAAO;AACp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AW,QAAQ,KAAK,QAAQ,QAAQ,QAAQ,gBAAgB,IAAI;AACzF,SAAO,EAAE,QAAQ,qBAAqB,IAAI,qBAAqB,IAAI;AACrE;AAUA,eAAsB,qBAAqB,YAAyB,SAAgG;AAClK,MAAI,KAAC,0DAA2B,UAAU,GAAG;AAC3C,UAAM,IAAI,MAAM,GAAG,WAAW,YAAY,IAAI,qCAAqC;AAAA,EACrF;AACA,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,SAAO,WAAW,kBAAkB,KAAK,QAAQ,QAAQ;AAAA,IACvD,aAAa,QAAQ;AAAA,IACrB,OAAO,QAAQ;AAAA,EACjB,CAAC;AACH;AAWA,eAAsB,qBAAqB,YAAyB,SAA0F;AAC5J,MAAI,KAAC,0DAA2B,UAAU,GAAG;AAC3C,UAAM,IAAI,MAAM,GAAG,WAAW,YAAY,IAAI,qCAAqC;AAAA,EACrF;AACA,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,SAAO,WAAW,aAAa,KAAK,QAAQ,QAAQ;AAAA,IAClD,MAAM,QAAQ;AAAA,IACd,aAAa,QAAQ;AAAA,IACrB,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;","names":["import_vitest","import_vitest","import_integrations_node_sdk","import_vitest"]}
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/testing/context.ts","../../src/testing/author.ts","../../src/testing/fetch.ts","../../src/testing/credentials.ts"],"sourcesContent":["import type { INodeContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport { assertNotRepointed, assertTtlInRange } from '../state-rules.js';\n\n/**\n * Drop-in replacement for the `createMockContext` helper that was, until this\n * package existed, copy-pasted byte-for-byte into every node repo's\n * `tests/helpers/context.ts`. Builds a full {@link INodeContext} with\n * `vi.fn()`-backed `logger`, `secrets.get`, `credentials.get` and `state` so a\n * node's `execute` can be unit-tested in isolation.\n *\n * The state mock is **stateful on purpose**: what the node writes, it reads\n * back. A node's interesting behaviour is precisely the second run — the one\n * that finds the mapping it created the first time — and a mock that forgets\n * would only ever exercise the create branch. It is the one place an author can\n * test writes at all: in the real product, author-time execution is read-only.\n *\n * It reads back *when the store would let it*, which is not the same for all\n * four roles (SDK 1.0.0, `specs/workflow-state.md`): a mapping and a claim take\n * effect immediately, a cursor and a digest are staged and adopted only once the\n * run completes. So `cursor.get` after `cursor.set` still answers what the last\n * completed run left — call {@link MockContext.completeRun} between two\n * `execute` calls to play the second run, and leave it uncalled to play the run\n * that failed and left the watermark where it was.\n */\n\nexport type MockLogger = {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n};\n\nexport type MockSecrets = {\n get: ReturnType<typeof vi.fn>;\n};\n\nexport type MockCredentials = {\n get: ReturnType<typeof vi.fn>;\n};\n\n/** Every state operation is a `vi.fn()`, so calls can be asserted on. */\nexport type MockState = {\n mapping: { get: ReturnType<typeof vi.fn>; put: ReturnType<typeof vi.fn> };\n cursor: { get: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };\n claim: ReturnType<typeof vi.fn>;\n digest: { unchanged: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };\n};\n\n/**\n * What the store already knows when the node starts — the \"this ran before\"\n * half of any sync test.\n */\nexport interface MockStateSeed {\n /** namespace -> { leftKey: rightKey }; readable from either side. */\n mappings?: Record<string, Record<string, string>>;\n /** namespace -> partitionKey ('' for the unpartitioned one) -> watermark. */\n cursors?: Record<string, Record<string, unknown>>;\n /** namespace -> keys already claimed, so `claim` returns false for them. */\n claims?: Record<string, string[]>;\n /** namespace -> { entityKey: digest }. */\n digests?: Record<string, Record<string, string>>;\n}\n\nexport type MockContext = INodeContext & {\n logger: MockLogger;\n secrets: MockSecrets;\n credentials: MockCredentials;\n state: MockState;\n /**\n * Adopts what this run staged — the cursors and digests it set — the way the\n * engine does when a run completes. Not part of {@link INodeContext}: it is\n * the harness standing in for the run's own ending, and a node can never call\n * it. A test that never calls it has played a run that did not complete.\n */\n completeRun: () => void;\n};\n\nexport interface CreateMockContextOptions {\n signal?: AbortSignal;\n /** Secret key -> value returned by `secrets.get`. Unknown keys fall back to a deterministic stub. */\n secrets?: Record<string, string>;\n /** When set, `secrets.get` rejects with this error instead of resolving. */\n secretsError?: Error;\n /** Credential instance id -> resolved access data returned by `credentials.get`. */\n credentials?: Record<string, Record<string, unknown>>;\n /** When set, `credentials.get` rejects with this error instead of resolving. */\n credentialsError?: Error;\n /** What the state store already holds when the node starts. */\n state?: MockStateSeed;\n /**\n * When set, every state call rejects with this error — the shape of the\n * engine refusing a namespace the workflow never declared.\n */\n stateError?: Error;\n}\n\nexport function createMockContext(options: CreateMockContextOptions = {}): MockContext {\n const signal = options.signal ?? new AbortController().signal;\n const { state, completeRun } = createMockState(options.state, options.stateError);\n\n const secretsGet = options.secretsError\n ? vi.fn(async () => {\n throw options.secretsError;\n })\n : vi.fn(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn(async () => {\n throw options.credentialsError;\n })\n : vi.fn(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n },\n secrets: {\n get: secretsGet,\n },\n credentials: {\n get: credentialsGet,\n },\n state,\n completeRun,\n };\n}\n\n/**\n * A tiny in-memory stand-in for the four state roles. Seeds are copied rather\n * than referenced, so a test that writes cannot leak into the next one.\n *\n * The write calls split the way the store does. A mapping and a claim land in\n * the committed maps at once; a cursor and a digest land in a staging map that\n * only `completeRun` folds in, so a read during the run answers what the last\n * completed one left. That is the whole reason there are four operations rather\n * than a generic get/set, and a mock that adopted everything immediately would\n * hide the case the rule exists for: the run that fails after advancing its\n * watermark.\n */\nfunction createMockState(seed: MockStateSeed = {}, error?: Error): { state: MockState; completeRun: () => void } {\n const mappings = new Map<string, Map<string, string>>();\n const cursors = new Map<string, Map<string, unknown>>();\n const claims = new Map<string, Set<string>>();\n const digests = new Map<string, Map<string, string>>();\n /** What this run has staged: adopted by `completeRun`, dropped otherwise. */\n const stagedCursors = new Map<string, Map<string, unknown>>();\n const stagedDigests = new Map<string, Map<string, string>>();\n\n for (const [namespace, pairs] of Object.entries(seed.mappings ?? {})) {\n mappings.set(namespace, new Map(Object.entries(pairs)));\n }\n for (const [namespace, partitions] of Object.entries(seed.cursors ?? {})) {\n cursors.set(namespace, new Map(Object.entries(partitions)));\n }\n for (const [namespace, keys] of Object.entries(seed.claims ?? {})) {\n claims.set(namespace, new Set(keys));\n }\n for (const [namespace, entries] of Object.entries(seed.digests ?? {})) {\n digests.set(namespace, new Map(Object.entries(entries)));\n }\n\n /** Wraps an operation so `stateError` short-circuits every one of them. */\n const op = <A extends unknown[], R>(fn: (...args: A) => R) =>\n vi.fn(async (...args: A): Promise<R> => {\n if (error) {\n throw error;\n }\n return fn(...args);\n });\n\n const state: MockState = {\n mapping: {\n get: op((namespace: string, key: string, side: 'left' | 'right' = 'left') => {\n const pairs = mappings.get(namespace);\n if (!pairs) {\n return null;\n }\n if (side === 'left') {\n return pairs.get(key) ?? null;\n }\n for (const [left, right] of pairs) {\n if (right === key) {\n return left;\n }\n }\n return null;\n }),\n put: op((namespace: string, left: string, right: string) => {\n const pairs = mappings.get(namespace) ?? new Map<string, string>();\n assertNotRepointed(namespace, pairs, left, right);\n pairs.set(left, right);\n mappings.set(namespace, pairs);\n }),\n },\n cursor: {\n // The committed watermark: what *this* run staged is deliberately not in\n // the answer, exactly as the real store describes it.\n get: op((namespace: string, partitionKey = '') => cursors.get(namespace)?.get(partitionKey)),\n set: op((namespace: string, value: unknown, partitionKey = '') => {\n const partitions = stagedCursors.get(namespace) ?? new Map<string, unknown>();\n partitions.set(partitionKey, value);\n stagedCursors.set(namespace, partitions);\n }),\n },\n // First caller wins, like the real claim — so a test can drive both the\n // fresh and the duplicate path without reconfiguring the mock. A claim is\n // never handed on here: a TTL is a wall-clock window, and no unit test\n // outlives the shortest one the store accepts.\n claim: op((namespace: string, key: string, opts?: { ttlSeconds?: number }) => {\n assertTtlInRange(opts?.ttlSeconds);\n const held = claims.get(namespace) ?? new Set<string>();\n if (held.has(key)) {\n return false;\n }\n held.add(key);\n claims.set(namespace, held);\n return true;\n }),\n digest: {\n unchanged: op((namespace: string, entityKey: string, digest: string) => digests.get(namespace)?.get(entityKey) === digest),\n set: op((namespace: string, entityKey: string, digest: string) => {\n const entries = stagedDigests.get(namespace) ?? new Map<string, string>();\n entries.set(entityKey, digest);\n stagedDigests.set(namespace, entries);\n }),\n },\n };\n\n const completeRun = (): void => {\n for (const [namespace, partitions] of stagedCursors) {\n const committed = cursors.get(namespace) ?? new Map<string, unknown>();\n for (const [partitionKey, value] of partitions) {\n committed.set(partitionKey, value);\n }\n cursors.set(namespace, committed);\n }\n for (const [namespace, entries] of stagedDigests) {\n const committed = digests.get(namespace) ?? new Map<string, string>();\n for (const [entityKey, digest] of entries) {\n committed.set(entityKey, digest);\n }\n digests.set(namespace, committed);\n }\n stagedCursors.clear();\n stagedDigests.clear();\n };\n\n return { state, completeRun };\n}\n","import type { INodeAuthorContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\n\n/**\n * Builds an {@link INodeAuthorContext} for unit-testing a node's *author-time*\n * resolvers (`loadOptions`, `resolveConfigSchema`, `resolveOutputs`). Until this\n * package existed, this factory was reinvented inline in each repo's resolver\n * tests. Mirrors {@link createMockContext}: `secrets.get` / `credentials.get`\n * are `vi.fn()`-backed and seedable.\n */\n\nexport type MockAuthorLogger = {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n};\n\nexport type MockAuthorContext = INodeAuthorContext & {\n logger: MockAuthorLogger;\n secrets: { get: ReturnType<typeof vi.fn> };\n credentials: { get: ReturnType<typeof vi.fn> };\n};\n\nexport interface CreateAuthorContextOptions {\n signal?: AbortSignal;\n /** Preferred locale for resolved labels. */\n locale?: string;\n secrets?: Record<string, string>;\n secretsError?: Error;\n credentials?: Record<string, Record<string, unknown>>;\n credentialsError?: Error;\n}\n\nexport function createAuthorContext(config: Record<string, unknown> = {}, options: CreateAuthorContextOptions = {}): MockAuthorContext {\n const signal = options.signal ?? new AbortController().signal;\n\n const secretsGet = options.secretsError\n ? vi.fn(async () => {\n throw options.secretsError;\n })\n : vi.fn(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn(async () => {\n throw options.credentialsError;\n })\n : vi.fn(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n },\n config,\n secrets: { get: secretsGet },\n credentials: { get: credentialsGet },\n locale: options.locale,\n };\n}\n","import { vi } from 'vitest';\n\n/**\n * Utilities for stubbing the global `fetch` so a credential's `resolve` /\n * `test` (which reach an OAuth token endpoint via the SDK's `postForm`) or a\n * node's `execute` (which uses `safeFetch` → global `fetch`) can be\n * unit-tested without touching the network. Builds real `Response` objects so\n * `res.ok` / `res.status` / `res.text()` / `res.json()` all behave exactly as\n * in production.\n */\n\nexport interface StubResponseInit {\n status?: number;\n headers?: Record<string, string>;\n /** JSON body — serialized and served as `application/json` unless `body` is set. */\n json?: unknown;\n /** Raw string body. Takes precedence over `json`. */\n body?: string;\n}\n\nexport interface StubbedRequest {\n url: string;\n method: string;\n init?: RequestInit;\n}\n\nexport type FetchHandler = (request: StubbedRequest) => StubResponseInit | Response | Promise<StubResponseInit | Response>;\n\n/** Builds a real `Response` from a {@link StubResponseInit}. */\nexport function buildResponse(init: StubResponseInit): Response {\n const headers = new Headers(init.headers ?? {});\n let body: string | undefined;\n if (init.body !== undefined) {\n body = init.body;\n } else if (init.json !== undefined) {\n body = JSON.stringify(init.json);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n return new Response(body, { status: init.status ?? 200, headers });\n}\n\nexport interface StubFetchResult {\n /** The `vi.fn()` installed as `globalThis.fetch` — assert calls on it. */\n fetchMock: ReturnType<typeof vi.fn>;\n /** Restores the previous `globalThis.fetch`. */\n restore(): void;\n}\n\n/**\n * Replaces `globalThis.fetch` with a `vi.fn()` driven by `handler`. Pass a\n * static {@link StubResponseInit} to answer every request identically, or a\n * {@link FetchHandler} to branch on url/method. Call `restore()` when done\n * (e.g. in `afterEach`).\n */\nexport function stubFetch(handler: FetchHandler | StubResponseInit): StubFetchResult {\n const previous = globalThis.fetch;\n const resolveInit: FetchHandler = typeof handler === 'function' ? handler : () => handler;\n\n const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();\n const out = await resolveInit({ url, method, init });\n return out instanceof Response ? out : buildResponse(out);\n });\n\n globalThis.fetch = fetchMock as unknown as typeof fetch;\n return {\n fetchMock,\n restore() {\n globalThis.fetch = previous;\n },\n };\n}\n\nexport interface FakeTokenEndpointOptions {\n /** Only answer requests to this exact URL; other requests 404. Omit to answer any URL. */\n tokenUrl?: string;\n accessToken?: string;\n tokenType?: string;\n /** Seconds until expiry (OAuth `expires_in`). Set `null` to omit the field. */\n expiresIn?: number | null;\n /** Included as `refresh_token` when set (e.g. to assert rotation). */\n refreshToken?: string;\n /** Extra fields merged into the token response body. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * A {@link FetchHandler} that emulates an OAuth token endpoint, returning\n * `{ access_token, token_type, expires_in, refresh_token? }`. Compose with\n * {@link stubFetch} to unit-test `oauth2-*` credentials' `resolve` / OAuth\n * `exchangeCode`.\n */\nexport function fakeTokenEndpoint(options: FakeTokenEndpointOptions = {}): FetchHandler {\n const { tokenUrl, accessToken = 'fake-access-token', tokenType = 'Bearer', expiresIn = 3600, refreshToken, extra } = options;\n\n return ({ url }) => {\n if (tokenUrl && url !== tokenUrl) {\n return { status: 404, json: { error: `no stub for ${url}` } };\n }\n const json: Record<string, unknown> = {\n access_token: accessToken,\n token_type: tokenType,\n ...(expiresIn !== null ? { expires_in: expiresIn } : {}),\n ...(refreshToken !== undefined ? { refresh_token: refreshToken } : {}),\n ...extra,\n };\n return { status: 200, json };\n };\n}\n","import type { ICredential, ICredentialContext, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';\nimport { isOAuthAuthorizeCredential } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\n\n/**\n * Harness for unit-testing a credential type's `test` / `resolve` / 3-legged\n * OAuth without the credentials broker or a real provider. Combine with\n * {@link stubFetch} / {@link fakeTokenEndpoint} to drive the token endpoint,\n * and inspect the returned `persistDurableCreds` spy to assert refresh-token\n * rotation.\n */\n\nexport type MockCredentialLogger = {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n};\n\nexport type MockCredentialContext = ICredentialContext & {\n logger: MockCredentialLogger;\n /** Spy wired to `ctx.persistDurableCreds`; assert `.toHaveBeenCalledWith(...)`. */\n persistDurableCreds: ReturnType<typeof vi.fn>;\n};\n\nexport interface CreateCredentialContextOptions {\n signal?: AbortSignal;\n}\n\nexport function createCredentialContext(options: CreateCredentialContextOptions = {}): MockCredentialContext {\n const signal = options.signal ?? new AbortController().signal;\n const persistDurableCreds = vi.fn(async (_durableCreds: Record<string, unknown>) => {});\n return {\n signal,\n logger: {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n },\n persistDurableCreds,\n };\n}\n\nexport interface RunCredentialTestOptions {\n config: Record<string, unknown>;\n signal?: AbortSignal;\n}\n\n/** Runs a credential's `test(ctx, config)` and returns its result. */\nexport async function runCredentialTest(credential: ICredential, options: RunCredentialTestOptions): Promise<ICredentialTestResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.test(ctx, options.config);\n}\n\nexport interface RunCredentialResolveOptions {\n config: Record<string, unknown>;\n /** System-managed long-lived secrets (e.g. an OAuth `refresh_token`). */\n durableCreds?: Record<string, unknown> | null;\n signal?: AbortSignal;\n}\n\nexport interface RunCredentialResolveResult {\n result: ICredentialResolveResult;\n /** Spy wired to `ctx.persistDurableCreds` — assert rotation happened. */\n persistDurableCreds: ReturnType<typeof vi.fn>;\n /** The context used, for further assertions (logger calls, etc.). */\n ctx: MockCredentialContext;\n}\n\n/** Runs a credential's `resolve(ctx, config, durableCreds)` and captures rotation. */\nexport async function runCredentialResolve(credential: ICredential, options: RunCredentialResolveOptions): Promise<RunCredentialResolveResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n const result = await credential.resolve(ctx, options.config, options.durableCreds ?? null);\n return { result, persistDurableCreds: ctx.persistDurableCreds, ctx };\n}\n\nexport interface RunOAuthAuthorizeUrlOptions {\n config: Record<string, unknown>;\n redirectUri: string;\n state: string;\n signal?: AbortSignal;\n}\n\n/** Runs `buildAuthorizeUrl` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthAuthorizeUrl(credential: ICredential, options: RunOAuthAuthorizeUrlOptions): Promise<{ authorizeUrl: string; codeVerifier?: string }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.buildAuthorizeUrl(ctx, options.config, {\n redirectUri: options.redirectUri,\n state: options.state,\n });\n}\n\nexport interface RunOAuthExchangeCodeOptions {\n config: Record<string, unknown>;\n code: string;\n redirectUri: string;\n codeVerifier?: string;\n signal?: AbortSignal;\n}\n\n/** Runs `exchangeCode` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthExchangeCode(credential: ICredential, options: RunOAuthExchangeCodeOptions): Promise<{ durableCreds: Record<string, unknown> }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.exchangeCode(ctx, options.config, {\n code: options.code,\n redirectUri: options.redirectUri,\n codeVerifier: options.codeVerifier,\n });\n}\n"],"mappings":";;;;;;AACA,SAAS,UAAU;AA+FZ,SAAS,kBAAkB,UAAoC,CAAC,GAAgB;AACrF,QAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,EAAE;AACvD,QAAM,EAAE,OAAO,YAAY,IAAI,gBAAgB,QAAQ,OAAO,QAAQ,UAAU;AAEhF,QAAM,aAAa,QAAQ,eACvB,GAAG,GAAG,YAAY;AAChB,UAAM,QAAQ;AAAA,EAChB,CAAC,IACD,GAAG,GAAG,OAAO,QAAgB;AAC3B,QAAI,QAAQ,WAAW,OAAO,QAAQ,SAAS;AAC7C,aAAO,QAAQ,QAAQ,GAAG;AAAA,IAC5B;AACA,WAAO,oBAAoB,GAAG;AAAA,EAChC,CAAC;AAEL,QAAM,iBAAiB,QAAQ,mBAC3B,GAAG,GAAG,YAAY;AAChB,UAAM,QAAQ;AAAA,EAChB,CAAC,IACD,GAAG,GAAG,OAAO,OAAe;AAC1B,QAAI,QAAQ,eAAe,MAAM,QAAQ,aAAa;AACpD,aAAO,QAAQ,YAAY,EAAE;AAAA,IAC/B;AACA,WAAO,CAAC;AAAA,EACV,CAAC;AAEL,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,MACN,MAAM,GAAG,GAAG;AAAA,MACZ,MAAM,GAAG,GAAG;AAAA,MACZ,OAAO,GAAG,GAAG;AAAA,IACf;AAAA,IACA,SAAS;AAAA,MACP,KAAK;AAAA,IACP;AAAA,IACA,aAAa;AAAA,MACX,KAAK;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAcA,SAAS,gBAAgB,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AQ,OAAO,CAAC;AAC9D,QAAM,SAAS,MAAM,WAAW,QAAQ,KAAK,QAAQ,QAAQ,QAAQ,gBAAgB,IAAI;AACzF,SAAO,EAAE,QAAQ,qBAAqB,IAAI,qBAAqB,IAAI;AACrE;AAUA,eAAsB,qBAAqB,YAAyB,SAAgG;AAClK,MAAI,CAAC,2BAA2B,UAAU,GAAG;AAC3C,UAAM,IAAI,MAAM,GAAG,WAAW,YAAY,IAAI,qCAAqC;AAAA,EACrF;AACA,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,SAAO,WAAW,kBAAkB,KAAK,QAAQ,QAAQ;AAAA,IACvD,aAAa,QAAQ;AAAA,IACrB,OAAO,QAAQ;AAAA,EACjB,CAAC;AACH;AAWA,eAAsB,qBAAqB,YAAyB,SAA0F;AAC5J,MAAI,CAAC,2BAA2B,UAAU,GAAG;AAC3C,UAAM,IAAI,MAAM,GAAG,WAAW,YAAY,IAAI,qCAAqC;AAAA,EACrF;AACA,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,SAAO,WAAW,aAAa,KAAK,QAAQ,QAAQ;AAAA,IAClD,MAAM,QAAQ;AAAA,IACd,aAAa,QAAQ;AAAA,IACrB,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;","names":["vi","vi","vi"]}
|
|
1
|
+
{"version":3,"sources":["../../src/testing/context.ts","../../src/testing/author.ts","../../src/testing/fetch.ts","../../src/testing/credentials.ts"],"sourcesContent":["import type { INodeContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\nimport { assertNotRepointed, assertTtlInRange } from '../state-rules.js';\n\n/**\n * Drop-in replacement for the `createMockContext` helper that was, until this\n * package existed, copy-pasted byte-for-byte into every node repo's\n * `tests/helpers/context.ts`. Builds a full {@link INodeContext} with\n * `vi.fn<AnyFn>()`-backed `logger`, `secrets.get`, `credentials.get` and `state` so a\n * node's `execute` can be unit-tested in isolation.\n *\n * The state mock is **stateful on purpose**: what the node writes, it reads\n * back. A node's interesting behaviour is precisely the second run — the one\n * that finds the mapping it created the first time — and a mock that forgets\n * would only ever exercise the create branch. It is the one place an author can\n * test writes at all: in the real product, author-time execution is read-only.\n *\n * It reads back *when the store would let it*, which is not the same for all\n * four roles (SDK 1.0.0, `specs/workflow-state.md`): a mapping and a claim take\n * effect immediately, a cursor and a digest are staged and adopted only once the\n * run completes. So `cursor.get` after `cursor.set` still answers what the last\n * completed run left — call {@link MockContext.completeRun} between two\n * `execute` calls to play the second run, and leave it uncalled to play the run\n * that failed and left the watermark where it was.\n */\n\nexport type MockLogger = {\n info: AnyMock;\n warn: AnyMock;\n error: AnyMock;\n};\n\nexport type MockSecrets = {\n get: AnyMock;\n};\n\nexport type MockCredentials = {\n get: AnyMock;\n};\n\n/** Every state operation is a `vi.fn<AnyFn>()`, so calls can be asserted on. */\nexport type MockState = {\n mapping: { get: AnyMock; put: AnyMock };\n cursor: { get: AnyMock; set: AnyMock };\n claim: AnyMock;\n digest: { unchanged: AnyMock; set: AnyMock };\n};\n\n/**\n * What the store already knows when the node starts — the \"this ran before\"\n * half of any sync test.\n */\nexport interface MockStateSeed {\n /** namespace -> { leftKey: rightKey }; readable from either side. */\n mappings?: Record<string, Record<string, string>>;\n /** namespace -> partitionKey ('' for the unpartitioned one) -> watermark. */\n cursors?: Record<string, Record<string, unknown>>;\n /** namespace -> keys already claimed, so `claim` returns false for them. */\n claims?: Record<string, string[]>;\n /** namespace -> { entityKey: digest }. */\n digests?: Record<string, Record<string, string>>;\n}\n\nexport type MockContext = INodeContext & {\n logger: MockLogger;\n secrets: MockSecrets;\n credentials: MockCredentials;\n state: MockState;\n /**\n * Adopts what this run staged — the cursors and digests it set — the way the\n * engine does when a run completes. Not part of {@link INodeContext}: it is\n * the harness standing in for the run's own ending, and a node can never call\n * it. A test that never calls it has played a run that did not complete.\n */\n completeRun: () => void;\n};\n\nexport interface CreateMockContextOptions {\n signal?: AbortSignal;\n /** Secret key -> value returned by `secrets.get`. Unknown keys fall back to a deterministic stub. */\n secrets?: Record<string, string>;\n /** When set, `secrets.get` rejects with this error instead of resolving. */\n secretsError?: Error;\n /** Credential instance id -> resolved access data returned by `credentials.get`. */\n credentials?: Record<string, Record<string, unknown>>;\n /** When set, `credentials.get` rejects with this error instead of resolving. */\n credentialsError?: Error;\n /** What the state store already holds when the node starts. */\n state?: MockStateSeed;\n /**\n * When set, every state call rejects with this error — the shape of the\n * engine refusing a namespace the workflow never declared.\n */\n stateError?: Error;\n}\n\nexport function createMockContext(options: CreateMockContextOptions = {}): MockContext {\n const signal = options.signal ?? new AbortController().signal;\n const { state, completeRun } = createMockState(options.state, options.stateError);\n\n const secretsGet = options.secretsError\n ? vi.fn<AnyFn>(async () => {\n throw options.secretsError;\n })\n : vi.fn<AnyFn>(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn<AnyFn>(async () => {\n throw options.credentialsError;\n })\n : vi.fn<AnyFn>(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn<AnyFn>(),\n warn: vi.fn<AnyFn>(),\n error: vi.fn<AnyFn>(),\n },\n secrets: {\n get: secretsGet,\n },\n credentials: {\n get: credentialsGet,\n },\n state,\n completeRun,\n };\n}\n\n/**\n * A tiny in-memory stand-in for the four state roles. Seeds are copied rather\n * than referenced, so a test that writes cannot leak into the next one.\n *\n * The write calls split the way the store does. A mapping and a claim land in\n * the committed maps at once; a cursor and a digest land in a staging map that\n * only `completeRun` folds in, so a read during the run answers what the last\n * completed one left. That is the whole reason there are four operations rather\n * than a generic get/set, and a mock that adopted everything immediately would\n * hide the case the rule exists for: the run that fails after advancing its\n * watermark.\n */\nfunction createMockState(seed: MockStateSeed = {}, error?: Error): { state: MockState; completeRun: () => void } {\n const mappings = new Map<string, Map<string, string>>();\n const cursors = new Map<string, Map<string, unknown>>();\n const claims = new Map<string, Set<string>>();\n const digests = new Map<string, Map<string, string>>();\n /** What this run has staged: adopted by `completeRun`, dropped otherwise. */\n const stagedCursors = new Map<string, Map<string, unknown>>();\n const stagedDigests = new Map<string, Map<string, string>>();\n\n for (const [namespace, pairs] of Object.entries(seed.mappings ?? {})) {\n mappings.set(namespace, new Map(Object.entries(pairs)));\n }\n for (const [namespace, partitions] of Object.entries(seed.cursors ?? {})) {\n cursors.set(namespace, new Map(Object.entries(partitions)));\n }\n for (const [namespace, keys] of Object.entries(seed.claims ?? {})) {\n claims.set(namespace, new Set(keys));\n }\n for (const [namespace, entries] of Object.entries(seed.digests ?? {})) {\n digests.set(namespace, new Map(Object.entries(entries)));\n }\n\n /** Wraps an operation so `stateError` short-circuits every one of them. */\n const op = <A extends unknown[], R>(fn: (...args: A) => R) =>\n vi.fn(async (...args: A): Promise<R> => {\n if (error) {\n throw error;\n }\n return fn(...args);\n });\n\n const state: MockState = {\n mapping: {\n get: op((namespace: string, key: string, side: 'left' | 'right' = 'left') => {\n const pairs = mappings.get(namespace);\n if (!pairs) {\n return null;\n }\n if (side === 'left') {\n return pairs.get(key) ?? null;\n }\n for (const [left, right] of pairs) {\n if (right === key) {\n return left;\n }\n }\n return null;\n }),\n put: op((namespace: string, left: string, right: string) => {\n const pairs = mappings.get(namespace) ?? new Map<string, string>();\n assertNotRepointed(namespace, pairs, left, right);\n pairs.set(left, right);\n mappings.set(namespace, pairs);\n }),\n },\n cursor: {\n // The committed watermark: what *this* run staged is deliberately not in\n // the answer, exactly as the real store describes it.\n get: op((namespace: string, partitionKey = '') => cursors.get(namespace)?.get(partitionKey)),\n set: op((namespace: string, value: unknown, partitionKey = '') => {\n const partitions = stagedCursors.get(namespace) ?? new Map<string, unknown>();\n partitions.set(partitionKey, value);\n stagedCursors.set(namespace, partitions);\n }),\n },\n // First caller wins, like the real claim — so a test can drive both the\n // fresh and the duplicate path without reconfiguring the mock. A claim is\n // never handed on here: a TTL is a wall-clock window, and no unit test\n // outlives the shortest one the store accepts.\n claim: op((namespace: string, key: string, opts?: { ttlSeconds?: number }) => {\n assertTtlInRange(opts?.ttlSeconds);\n const held = claims.get(namespace) ?? new Set<string>();\n if (held.has(key)) {\n return false;\n }\n held.add(key);\n claims.set(namespace, held);\n return true;\n }),\n digest: {\n unchanged: op((namespace: string, entityKey: string, digest: string) => digests.get(namespace)?.get(entityKey) === digest),\n set: op((namespace: string, entityKey: string, digest: string) => {\n const entries = stagedDigests.get(namespace) ?? new Map<string, string>();\n entries.set(entityKey, digest);\n stagedDigests.set(namespace, entries);\n }),\n },\n };\n\n const completeRun = (): void => {\n for (const [namespace, partitions] of stagedCursors) {\n const committed = cursors.get(namespace) ?? new Map<string, unknown>();\n for (const [partitionKey, value] of partitions) {\n committed.set(partitionKey, value);\n }\n cursors.set(namespace, committed);\n }\n for (const [namespace, entries] of stagedDigests) {\n const committed = digests.get(namespace) ?? new Map<string, string>();\n for (const [entityKey, digest] of entries) {\n committed.set(entityKey, digest);\n }\n digests.set(namespace, committed);\n }\n stagedCursors.clear();\n stagedDigests.clear();\n };\n\n return { state, completeRun };\n}\n","import type { INodeAuthorContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\n\n/**\n * Builds an {@link INodeAuthorContext} for unit-testing a node's *author-time*\n * resolvers (`loadOptions`, `resolveConfigSchema`, `resolveOutputs`). Until this\n * package existed, this factory was reinvented inline in each repo's resolver\n * tests. Mirrors {@link createMockContext}: `secrets.get` / `credentials.get`\n * are `vi.fn<AnyFn>()`-backed and seedable.\n */\n\nexport type MockAuthorLogger = {\n info: AnyMock;\n warn: AnyMock;\n error: AnyMock;\n};\n\nexport type MockAuthorContext = INodeAuthorContext & {\n logger: MockAuthorLogger;\n secrets: { get: AnyMock };\n credentials: { get: AnyMock };\n};\n\nexport interface CreateAuthorContextOptions {\n signal?: AbortSignal;\n /** Preferred locale for resolved labels. */\n locale?: string;\n secrets?: Record<string, string>;\n secretsError?: Error;\n credentials?: Record<string, Record<string, unknown>>;\n credentialsError?: Error;\n}\n\nexport function createAuthorContext(config: Record<string, unknown> = {}, options: CreateAuthorContextOptions = {}): MockAuthorContext {\n const signal = options.signal ?? new AbortController().signal;\n\n const secretsGet = options.secretsError\n ? vi.fn<AnyFn>(async () => {\n throw options.secretsError;\n })\n : vi.fn<AnyFn>(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn<AnyFn>(async () => {\n throw options.credentialsError;\n })\n : vi.fn<AnyFn>(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn<AnyFn>(),\n warn: vi.fn<AnyFn>(),\n error: vi.fn<AnyFn>(),\n },\n config,\n secrets: { get: secretsGet },\n credentials: { get: credentialsGet },\n locale: options.locale,\n };\n}\n","import { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\n\n/**\n * Utilities for stubbing the global `fetch` so a credential's `resolve` /\n * `test` (which reach an OAuth token endpoint via the SDK's `postForm`) or a\n * node's `execute` (which uses `safeFetch` → global `fetch`) can be\n * unit-tested without touching the network. Builds real `Response` objects so\n * `res.ok` / `res.status` / `res.text()` / `res.json()` all behave exactly as\n * in production.\n */\n\nexport interface StubResponseInit {\n status?: number;\n headers?: Record<string, string>;\n /** JSON body — serialized and served as `application/json` unless `body` is set. */\n json?: unknown;\n /** Raw string body. Takes precedence over `json`. */\n body?: string;\n}\n\nexport interface StubbedRequest {\n url: string;\n method: string;\n init?: RequestInit;\n}\n\nexport type FetchHandler = (request: StubbedRequest) => StubResponseInit | Response | Promise<StubResponseInit | Response>;\n\n/** Builds a real `Response` from a {@link StubResponseInit}. */\nexport function buildResponse(init: StubResponseInit): Response {\n const headers = new Headers(init.headers ?? {});\n let body: string | undefined;\n if (init.body !== undefined) {\n body = init.body;\n } else if (init.json !== undefined) {\n body = JSON.stringify(init.json);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n return new Response(body, { status: init.status ?? 200, headers });\n}\n\nexport interface StubFetchResult {\n /** The `vi.fn<AnyFn>()` installed as `globalThis.fetch` — assert calls on it. */\n fetchMock: AnyMock;\n /** Restores the previous `globalThis.fetch`. */\n restore(): void;\n}\n\n/**\n * Replaces `globalThis.fetch` with a `vi.fn<AnyFn>()` driven by `handler`. Pass a\n * static {@link StubResponseInit} to answer every request identically, or a\n * {@link FetchHandler} to branch on url/method. Call `restore()` when done\n * (e.g. in `afterEach`).\n */\nexport function stubFetch(handler: FetchHandler | StubResponseInit): StubFetchResult {\n const previous = globalThis.fetch;\n const resolveInit: FetchHandler = typeof handler === 'function' ? handler : () => handler;\n\n const fetchMock = vi.fn<AnyFn>(async (input: RequestInfo | URL, init?: RequestInit) => {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();\n const out = await resolveInit({ url, method, init });\n return out instanceof Response ? out : buildResponse(out);\n });\n\n globalThis.fetch = fetchMock as unknown as typeof fetch;\n return {\n fetchMock,\n restore() {\n globalThis.fetch = previous;\n },\n };\n}\n\nexport interface FakeTokenEndpointOptions {\n /** Only answer requests to this exact URL; other requests 404. Omit to answer any URL. */\n tokenUrl?: string;\n accessToken?: string;\n tokenType?: string;\n /** Seconds until expiry (OAuth `expires_in`). Set `null` to omit the field. */\n expiresIn?: number | null;\n /** Included as `refresh_token` when set (e.g. to assert rotation). */\n refreshToken?: string;\n /** Extra fields merged into the token response body. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * A {@link FetchHandler} that emulates an OAuth token endpoint, returning\n * `{ access_token, token_type, expires_in, refresh_token? }`. Compose with\n * {@link stubFetch} to unit-test `oauth2-*` credentials' `resolve` / OAuth\n * `exchangeCode`.\n */\nexport function fakeTokenEndpoint(options: FakeTokenEndpointOptions = {}): FetchHandler {\n const { tokenUrl, accessToken = 'fake-access-token', tokenType = 'Bearer', expiresIn = 3600, refreshToken, extra } = options;\n\n return ({ url }) => {\n if (tokenUrl && url !== tokenUrl) {\n return { status: 404, json: { error: `no stub for ${url}` } };\n }\n const json: Record<string, unknown> = {\n access_token: accessToken,\n token_type: tokenType,\n ...(expiresIn !== null ? { expires_in: expiresIn } : {}),\n ...(refreshToken !== undefined ? { refresh_token: refreshToken } : {}),\n ...extra,\n };\n return { status: 200, json };\n };\n}\n","import type { ICredential, ICredentialContext, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';\nimport { isOAuthAuthorizeCredential } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\n\n/**\n * Harness for unit-testing a credential type's `test` / `resolve` / 3-legged\n * OAuth without the credentials broker or a real provider. Combine with\n * {@link stubFetch} / {@link fakeTokenEndpoint} to drive the token endpoint,\n * and inspect the returned `persistDurableCreds` spy to assert refresh-token\n * rotation.\n */\n\nexport type MockCredentialLogger = {\n info: AnyMock;\n warn: AnyMock;\n error: AnyMock;\n};\n\nexport type MockCredentialContext = ICredentialContext & {\n logger: MockCredentialLogger;\n /** Spy wired to `ctx.persistDurableCreds`; assert `.toHaveBeenCalledWith(...)`. */\n persistDurableCreds: AnyMock;\n};\n\nexport interface CreateCredentialContextOptions {\n signal?: AbortSignal;\n}\n\nexport function createCredentialContext(options: CreateCredentialContextOptions = {}): MockCredentialContext {\n const signal = options.signal ?? new AbortController().signal;\n const persistDurableCreds = vi.fn<AnyFn>(async (_durableCreds: Record<string, unknown>) => {});\n return {\n signal,\n logger: {\n info: vi.fn<AnyFn>(),\n warn: vi.fn<AnyFn>(),\n error: vi.fn<AnyFn>(),\n },\n persistDurableCreds,\n };\n}\n\nexport interface RunCredentialTestOptions {\n config: Record<string, unknown>;\n signal?: AbortSignal;\n}\n\n/** Runs a credential's `test(ctx, config)` and returns its result. */\nexport async function runCredentialTest(credential: ICredential, options: RunCredentialTestOptions): Promise<ICredentialTestResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.test(ctx, options.config);\n}\n\nexport interface RunCredentialResolveOptions {\n config: Record<string, unknown>;\n /** System-managed long-lived secrets (e.g. an OAuth `refresh_token`). */\n durableCreds?: Record<string, unknown> | null;\n signal?: AbortSignal;\n}\n\nexport interface RunCredentialResolveResult {\n result: ICredentialResolveResult;\n /** Spy wired to `ctx.persistDurableCreds` — assert rotation happened. */\n persistDurableCreds: AnyMock;\n /** The context used, for further assertions (logger calls, etc.). */\n ctx: MockCredentialContext;\n}\n\n/** Runs a credential's `resolve(ctx, config, durableCreds)` and captures rotation. */\nexport async function runCredentialResolve(credential: ICredential, options: RunCredentialResolveOptions): Promise<RunCredentialResolveResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n const result = await credential.resolve(ctx, options.config, options.durableCreds ?? null);\n return { result, persistDurableCreds: ctx.persistDurableCreds, ctx };\n}\n\nexport interface RunOAuthAuthorizeUrlOptions {\n config: Record<string, unknown>;\n redirectUri: string;\n state: string;\n signal?: AbortSignal;\n}\n\n/** Runs `buildAuthorizeUrl` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthAuthorizeUrl(credential: ICredential, options: RunOAuthAuthorizeUrlOptions): Promise<{ authorizeUrl: string; codeVerifier?: string }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.buildAuthorizeUrl(ctx, options.config, {\n redirectUri: options.redirectUri,\n state: options.state,\n });\n}\n\nexport interface RunOAuthExchangeCodeOptions {\n config: Record<string, unknown>;\n code: string;\n redirectUri: string;\n codeVerifier?: string;\n signal?: AbortSignal;\n}\n\n/** Runs `exchangeCode` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthExchangeCode(credential: ICredential, options: RunOAuthExchangeCodeOptions): Promise<{ durableCreds: Record<string, unknown> }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.exchangeCode(ctx, options.config, {\n code: options.code,\n redirectUri: options.redirectUri,\n codeVerifier: options.codeVerifier,\n });\n}\n"],"mappings":";;;;;;AACA,SAAS,UAAU;AAgGZ,SAAS,kBAAkB,UAAoC,CAAC,GAAgB;AACrF,QAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,EAAE;AACvD,QAAM,EAAE,OAAO,YAAY,IAAI,gBAAgB,QAAQ,OAAO,QAAQ,UAAU;AAEhF,QAAM,aAAa,QAAQ,eACvB,GAAG,GAAU,YAAY;AACvB,UAAM,QAAQ;AAAA,EAChB,CAAC,IACD,GAAG,GAAU,OAAO,QAAgB;AAClC,QAAI,QAAQ,WAAW,OAAO,QAAQ,SAAS;AAC7C,aAAO,QAAQ,QAAQ,GAAG;AAAA,IAC5B;AACA,WAAO,oBAAoB,GAAG;AAAA,EAChC,CAAC;AAEL,QAAM,iBAAiB,QAAQ,mBAC3B,GAAG,GAAU,YAAY;AACvB,UAAM,QAAQ;AAAA,EAChB,CAAC,IACD,GAAG,GAAU,OAAO,OAAe;AACjC,QAAI,QAAQ,eAAe,MAAM,QAAQ,aAAa;AACpD,aAAO,QAAQ,YAAY,EAAE;AAAA,IAC/B;AACA,WAAO,CAAC;AAAA,EACV,CAAC;AAEL,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,MACN,MAAM,GAAG,GAAU;AAAA,MACnB,MAAM,GAAG,GAAU;AAAA,MACnB,OAAO,GAAG,GAAU;AAAA,IACtB;AAAA,IACA,SAAS;AAAA,MACP,KAAK;AAAA,IACP;AAAA,IACA,aAAa;AAAA,MACX,KAAK;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAc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,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,QAAM,SAAS,MAAM,WAAW,QAAQ,KAAK,QAAQ,QAAQ,QAAQ,gBAAgB,IAAI;AACzF,SAAO,EAAE,QAAQ,qBAAqB,IAAI,qBAAqB,IAAI;AACrE;AAUA,eAAsB,qBAAqB,YAAyB,SAAgG;AAClK,MAAI,CAAC,2BAA2B,UAAU,GAAG;AAC3C,UAAM,IAAI,MAAM,GAAG,WAAW,YAAY,IAAI,qCAAqC;AAAA,EACrF;AACA,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,SAAO,WAAW,kBAAkB,KAAK,QAAQ,QAAQ;AAAA,IACvD,aAAa,QAAQ;AAAA,IACrB,OAAO,QAAQ;AAAA,EACjB,CAAC;AACH;AAWA,eAAsB,qBAAqB,YAAyB,SAA0F;AAC5J,MAAI,CAAC,2BAA2B,UAAU,GAAG;AAC3C,UAAM,IAAI,MAAM,GAAG,WAAW,YAAY,IAAI,qCAAqC;AAAA,EACrF;AACA,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,SAAO,WAAW,aAAa,KAAK,QAAQ,QAAQ;AAAA,IAClD,MAAM,QAAQ;AAAA,IACd,aAAa,QAAQ;AAAA,IACrB,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;","names":["vi","vi","vi"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Mock } from 'vitest';
|
|
2
|
+
/**
|
|
3
|
+
* The type of every spy the harness hands out: a mock that takes any call and
|
|
4
|
+
* returns anything, so a test can seed it with whatever its node expects.
|
|
5
|
+
*
|
|
6
|
+
* Spelled out rather than written `ReturnType<typeof vi.fn>`, which meant this
|
|
7
|
+
* under Vitest 2 and means `Mock<Constructable | Procedure>` from Vitest 3 on —
|
|
8
|
+
* a type no logger or `secrets.get` signature accepts. `Mock<AnyFn>` reads the
|
|
9
|
+
* same under every Vitest from 2 on (PO-804).
|
|
10
|
+
*/
|
|
11
|
+
export type AnyFn = (...args: any[]) => any;
|
|
12
|
+
export type AnyMock = Mock<AnyFn>;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@revenexx/integrations-node-devkit",
|
|
3
|
-
"version": "0.8.
|
|
4
|
-
"description": "Local development kit for Revenexx integration node packages
|
|
3
|
+
"version": "0.8.3",
|
|
4
|
+
"description": "Local development kit for Revenexx integration node packages — a mock Integrations API for previewing nodes/credentials/templates in the Cockpit UI, plus a unit-testing harness. Dev/CI only, never bundled.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"revenexx",
|
|
7
7
|
"integrations",
|
|
@@ -64,11 +64,12 @@
|
|
|
64
64
|
"devDependencies": {
|
|
65
65
|
"@biomejs/biome": "^2.5.0",
|
|
66
66
|
"@changesets/cli": "^3.0.3",
|
|
67
|
-
"@revenexx/integrations-node-sdk": "
|
|
67
|
+
"@revenexx/integrations-node-sdk": "^2.0.0",
|
|
68
68
|
"@types/node": "^24.0.0",
|
|
69
69
|
"tsup": "^9.0.0",
|
|
70
70
|
"typescript": "^7.0.2",
|
|
71
|
-
"
|
|
71
|
+
"vite": "^8.3.5",
|
|
72
|
+
"vitest": "^5.0.5",
|
|
72
73
|
"yaml": "^2.9.0"
|
|
73
74
|
},
|
|
74
75
|
"peerDependencies": {
|
|
@@ -81,7 +82,7 @@
|
|
|
81
82
|
}
|
|
82
83
|
},
|
|
83
84
|
"engines": {
|
|
84
|
-
"node": ">=
|
|
85
|
+
"node": ">=22.19.0"
|
|
85
86
|
},
|
|
86
87
|
"publishConfig": {
|
|
87
88
|
"access": "public",
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"@dagrejs/dagre": "^3.0.0",
|
|
12
12
|
"@revenexx/studio": "^0.2.2",
|
|
13
|
-
"@revenexx/studio-integrations": "
|
|
13
|
+
"@revenexx/studio-integrations": "3.4.0",
|
|
14
14
|
"@revenexx/studio-shared": "^0.4.0",
|
|
15
15
|
"@revenexx/talkback-js": "^0.3.0",
|
|
16
16
|
"@solar-icons/nuxt": "^2.3.2",
|