From 239a94fe98a9ce6bbd0e2f7ce1afffdd4d5aad9f Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 9 Nov 2026 17:31:22 +0000 Subject: [PATCH 1/2] feat(matchers): add anyOf and *OrNull matchers to combine matchers with OR Add `anyOf(...matchers)`, which applies several matchers to the same path and passes if at least one matches. It emits the `pact:matcher:combine: "OR"` integration JSON, so the pact file gets a rule list combined with OR (supported by the V3 and V4 specs) for bodies, headers and query parameters. The example is taken from the first matcher, and matchers nested in that example still apply to its children, so nullable objects work. The alternatives are emitted as single matchers without their own example or generator; nested OR groups are flattened. Also add `likeOrNull`, `stringOrNull`, `integerOrNull`, `decimalOrNull`, `numberOrNull`, `booleanOrNull`, `regexOrNull` and `uuidOrNull` as shorthand for `anyOf(x, nullValue())`. Requires a pact_ffi with pact-foundation/pact-reference#601. Co-Authored-By: Claude Opus 5.5 --- docs/matching.md | 66 +++++++++ src/orMatchers.integration.spec.ts | 154 +++++++++++++++++++++ src/v3/matchers.spec.ts | 215 +++++++++++++++++++++++++++++ src/v3/matchers.ts | 160 +++++++++++++++++++++ src/v3/types.ts | 35 ++++- 5 files changed, 628 insertions(+), 2 deletions(-) create mode 100644 src/orMatchers.integration.spec.ts diff --git a/docs/matching.md b/docs/matching.md index e146699a0..cad5e92c2 100644 --- a/docs/matching.md +++ b/docs/matching.md @@ -234,6 +234,9 @@ const animalBodyExpectation = { | `eachKeyMatches` | example: object, rules: Matcher[] | Object where the _keys_ must match the supplied matching rules and the values are ignored. | | `eachValueMatches` | example: object, rules: Matcher[] | Object where the _values_ must match the supplied matching rules and keys are ignored. | | `fromProviderState` | expression: string, exampleValue: string | Sets a type matcher and a provider state generator. See the section below. | +| `anyOf` | matchers... | Value that must match at least one of the given matchers (the matchers are combined with OR). The example is taken from the first matcher. See the section below. | +| `likeOrNull` | template | Value that must be null, or match the template by type (e.g. an optional object). Shorthand for `anyOf(like(template), nullValue())`. | +| `stringOrNull` | example?: string | Value that must be null, or a string. The `integerOrNull`, `decimalOrNull`, `numberOrNull`, `booleanOrNull`, `regexOrNull` and `uuidOrNull` matchers work the same way, taking the same parameters as the matcher they combine with `nullValue`. | #### Array contains matcher @@ -265,6 +268,69 @@ these can be used to match a hypermedia format like Siren, see [Example Pact + S } ``` +#### Combining matchers with OR + +> [!NOTE] +> Requires a version of the Pact FFI that supports `pact:matcher:combine` ([pact-reference#601](https://github.com/pact-foundation/pact-reference/pull/601)), which is +> included in `@pact-foundation/pact-core` TODO: version. With older versions the matchers are combined with AND, so the consumer test will fail. + +The `anyOf` matching function applies several matchers to the same value, and matching succeeds if at least one of +them matches. This is written to the pact file as a list of matching rules combined with `OR`, which is supported by the +V3 and V4 specifications. It can be used for bodies, headers and query parameters. + +The `*OrNull` functions (`likeOrNull`, `stringOrNull`, `integerOrNull`, `decimalOrNull`, `numberOrNull`, `booleanOrNull`, +`regexOrNull` and `uuidOrNull`) are shorthand for the most common case, a value that can also be `null`. + +```js +const { MatchersV3 } = require('@pact-foundation/pact'); +const { anyOf, integer, likeOrNull, nullValue, regex, string, stringOrNull, uuid } = MatchersV3; + +const body = { + // a string or null + name: anyOf(string('Fred'), nullValue()), // same as stringOrNull('Fred') + // an ID that is either a number or a UUID + id: anyOf(regex(/^\d+$/, '42'), uuid()), + // an optional object: either null, or an object whose `number` is an integer + address: likeOrNull({ + street: string('Main St'), + number: integer(42), + }), +}; +``` + +The `name` attribute is sent to the Pact FFI as: + +```json +{ + "pact:matcher:type": [{ "pact:matcher:type": "type" }, { "pact:matcher:type": "null" }], + "pact:matcher:combine": "OR", + "value": "Fred" +} +``` + +and written to the pact file as: + +```json +"$.name": { + "combine": "OR", + "matchers": [{ "match": "type" }, { "match": "null" }] +} +``` + +Things to be aware of: + +- **Only the example is exercised in the consumer test.** The example value is taken from the first matcher (e.g. `'Fred'` + above), so the consumer code is only tested against that value. The other alternatives (e.g. `null`) are only checked + when the provider is verified, so make sure your consumer code handles them, for example with separate interactions or + unit tests. Use OR with care. +- Order the matchers so that the one with the example you want to use comes first. +- Matchers nested in the example of the first matcher (like `integer(42)` in `address` above) still apply to the children + of the value when it is not null. +- Matchers that compare against the example, like `like`, can only describe the shape of that example. For instance, + `likeOrNull({...})` accepts an object of the same shape or null, but not an array. +- Each path can only have a single list of rules. Put all the alternatives in the one `anyOf` call, rather than wrapping + another matcher in the example. Nested `anyOf` calls are flattened into a single list. + #### Provider State Injected Values The `fromProviderState` matching function allows values to be generated based on values returned from the provider state callbacks. This should be used for the cases were database entries have auto-generated values and these values need to be used in the URLs or query parameters. diff --git a/src/orMatchers.integration.spec.ts b/src/orMatchers.integration.spec.ts new file mode 100644 index 000000000..5f451c1ac --- /dev/null +++ b/src/orMatchers.integration.spec.ts @@ -0,0 +1,154 @@ +import axios from 'axios'; + +import fs = require('node:fs'); +import path = require('node:path'); + +import { MatchersV3 } from './v3'; +import { PactV4 } from './v4'; + +const { anyOf, integer, likeOrNull, nullValue, regex, string, uuid } = + MatchersV3; + +// Requires a version of the Pact FFI that supports `pact:matcher:combine` +// (pact-foundation/pact-reference#601) +describe('Matchers combined with OR', () => { + const pactFilePath = path.resolve( + process.cwd(), + 'pacts', + 'or-matcher-consumer-or-matcher-provider.json', + ); + const description = 'a request to create a user with optional fields'; + const id = 'e2490de5-5bd3-43d5-b7c4-526e33f71304'; + + type Address = { street: string; number: unknown } | null; + type RequestOptions = { + name?: unknown; + address?: Address; + query?: string; + header?: string; + }; + + const executeRequest = ({ + name = 'Fred', + address = { street: 'Main St', number: 42 }, + query = '42', + header = '42', + }: RequestOptions = {}) => + new PactV4({ + consumer: 'or-matcher-consumer', + provider: 'or-matcher-provider', + }) + .addInteraction() + .uponReceiving(description) + .withRequest('POST', '/users', (builder) => { + builder + .query({ id: anyOf(regex(/^\d+$/, '42'), uuid(id)) }) + .headers({ 'x-request-id': anyOf(regex(/^\d+$/, '42'), uuid(id)) }) + .jsonBody({ + name: anyOf(string('Fred'), nullValue()), + address: likeOrNull({ + street: string('Main St'), + number: integer(42), + }), + }); + }) + .willRespondWith(201, (builder) => { + builder.jsonBody({ name: anyOf(string('Fred'), nullValue()) }); + }) + .executeTest(async (server) => { + const res = await axios.post( + `${server.url}/users`, + { name, address }, + { + params: { id: query }, + headers: { 'x-request-id': header }, + validateStatus: () => true, + }, + ); + return res; + }); + + beforeAll(() => { + if (fs.existsSync(pactFilePath)) { + fs.unlinkSync(pactFilePath); + } + }); + + it('matches the example values, and returns the example from the first matcher', async () => { + const res = await executeRequest(); + expect(res?.status).toEqual(201); + expect(res?.data).toEqual({ name: 'Fred' }); + }); + + it('matches the other alternatives', async () => { + const res = await executeRequest({ + name: null, + address: null, + query: id, + header: id, + }); + expect(res?.status).toEqual(201); + }); + + it('applies the matchers nested in the example of an optional object', async () => { + await expect( + executeRequest({ address: { street: 'Other St', number: 7 } }), + ).resolves.toBeDefined(); + await expect( + executeRequest({ address: { street: 'Main St', number: '42' } }), + ).rejects.toThrow(/Test failed/); + }); + + it('fails when the body value matches none of the alternatives', async () => { + await expect(executeRequest({ name: 123 })).rejects.toThrow(/Test failed/); + }); + + it('fails when a header matches none of the alternatives', async () => { + await expect(executeRequest({ header: 'abc' })).rejects.toThrow( + /Test failed/, + ); + }); + + it('fails when a query parameter matches none of the alternatives', async () => { + await expect(executeRequest({ query: 'abc' })).rejects.toThrow( + /Test failed/, + ); + }); + + it('writes the rules combined with OR to the pact file', () => { + const pact = JSON.parse(fs.readFileSync(pactFilePath, 'utf8')); + const interaction = pact.interactions.find( + (i: { description: string }) => i.description === description, + ); + const requestRules = interaction.request.matchingRules; + const orRegexOrUuid = { + combine: 'OR', + matchers: [ + { match: 'regex', regex: '^\\d+$' }, + { + match: 'regex', + regex: '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', + }, + ], + }; + + expect(requestRules.body['$.name']).toEqual({ + combine: 'OR', + matchers: [{ match: 'type' }, { match: 'null' }], + }); + expect(requestRules.body['$.address']).toEqual({ + combine: 'OR', + matchers: [{ match: 'type' }, { match: 'null' }], + }); + expect(requestRules.body['$.address.number']).toEqual({ + combine: 'AND', + matchers: [{ match: 'integer' }], + }); + expect(requestRules.header['x-request-id']).toEqual(orRegexOrUuid); + expect(requestRules.query.id).toEqual(orRegexOrUuid); + expect(interaction.response.matchingRules.body['$.name']).toEqual({ + combine: 'OR', + matchers: [{ match: 'type' }, { match: 'null' }], + }); + }); +}); diff --git a/src/v3/matchers.spec.ts b/src/v3/matchers.spec.ts index d02681444..0c3c05c4c 100644 --- a/src/v3/matchers.spec.ts +++ b/src/v3/matchers.spec.ts @@ -599,6 +599,221 @@ describe('V3 Matchers', () => { }); }); + describe('#anyOf', () => { + it('returns a JSON representation of matchers combined with OR', () => { + const result = MatchersV3.anyOf( + MatchersV3.string('Fred'), + MatchersV3.nullValue(), + ); + expect(result).toEqual({ + 'pact:matcher:type': [ + { 'pact:matcher:type': 'type' }, + { 'pact:matcher:type': 'null' }, + ], + 'pact:matcher:combine': 'OR', + value: 'Fred', + }); + }); + + it('keeps the attributes of each matcher, but not their examples', () => { + const result = MatchersV3.anyOf( + MatchersV3.regex(/^\d+$/, '42'), + MatchersV3.datetime("yyyy-MM-dd'T'HH:mm:ss", '2020-01-01T10:00:00'), + ); + expect(result).toEqual({ + 'pact:matcher:type': [ + { 'pact:matcher:type': 'regex', regex: '^\\d+$' }, + { + 'pact:matcher:type': 'timestamp', + format: "yyyy-MM-dd'T'HH:mm:ss", + }, + ], + 'pact:matcher:combine': 'OR', + value: '42', + }); + }); + + it('uses the example from the first matcher', () => { + expect( + MatchersV3.anyOf(MatchersV3.nullValue(), MatchersV3.string('Fred')) + .value, + ).toBeNull(); + expect( + MatchersV3.anyOf(MatchersV3.integer(1), MatchersV3.string('Fred')) + .value, + ).toEqual(1); + }); + + it('keeps matchers nested in the example of the first matcher', () => { + const result = MatchersV3.anyOf( + MatchersV3.like({ street: 'Main St', number: MatchersV3.integer(42) }), + MatchersV3.nullValue(), + ); + expect(result).toEqual({ + 'pact:matcher:type': [ + { 'pact:matcher:type': 'type' }, + { 'pact:matcher:type': 'null' }, + ], + 'pact:matcher:combine': 'OR', + value: { + street: 'Main St', + number: { 'pact:matcher:type': 'integer', value: 42 }, + }, + }); + expect(MatchersV3.reify(result)).toEqual({ + street: 'Main St', + number: 42, + }); + }); + + it('keeps the generator of the first matcher on the combined matcher', () => { + const result = MatchersV3.anyOf( + MatchersV3.fromProviderState('userId', 'abc'), + MatchersV3.nullValue(), + ); + expect(result).toEqual({ + 'pact:generator:type': 'ProviderState', + expression: 'userId', + 'pact:matcher:type': [ + { 'pact:matcher:type': 'type', expression: 'userId' }, + { 'pact:matcher:type': 'null' }, + ], + 'pact:matcher:combine': 'OR', + value: 'abc', + }); + }); + + it('drops the generators of the alternatives', () => { + const result = MatchersV3.anyOf( + MatchersV3.string('Fred'), + MatchersV3.integer(), + ); + expect(result).toEqual({ + 'pact:matcher:type': [ + { 'pact:matcher:type': 'type' }, + { 'pact:matcher:type': 'integer' }, + ], + 'pact:matcher:combine': 'OR', + value: 'Fred', + }); + }); + + it('flattens nested OR matchers into a single list', () => { + const result = MatchersV3.anyOf( + MatchersV3.anyOf(MatchersV3.integer(1), MatchersV3.decimal(1.5)), + MatchersV3.nullValue(), + ); + expect(result).toEqual({ + 'pact:matcher:type': [ + { 'pact:matcher:type': 'integer' }, + { 'pact:matcher:type': 'decimal' }, + { 'pact:matcher:type': 'null' }, + ], + 'pact:matcher:combine': 'OR', + value: 1, + }); + }); + + it('can be reified', () => { + expect( + MatchersV3.reify({ + name: MatchersV3.anyOf( + MatchersV3.string('Fred'), + MatchersV3.nullValue(), + ), + age: MatchersV3.anyOf(MatchersV3.nullValue(), MatchersV3.integer(1)), + }), + ).toEqual({ name: 'Fred', age: null }); + }); + + it('throws when no matchers are given', () => { + expect(() => MatchersV3.anyOf()).toThrow(/at least one matcher/); + }); + + it('throws when given a value that is not a matcher', () => { + expect(() => + // @ts-expect-error raw values are not matchers + MatchersV3.anyOf(MatchersV3.string('Fred'), 'Bob'), + ).toThrow(/argument 2 is not a matcher/); + }); + }); + + describe('*OrNull matchers', () => { + const nullAlternative = { 'pact:matcher:type': 'null' }; + + it.each([ + [ + 'likeOrNull', + MatchersV3.likeOrNull({ a: 1 }), + { 'pact:matcher:type': 'type' }, + { a: 1 }, + ], + [ + 'stringOrNull', + MatchersV3.stringOrNull('Fred'), + { 'pact:matcher:type': 'type' }, + 'Fred', + ], + [ + 'integerOrNull', + MatchersV3.integerOrNull(42), + { 'pact:matcher:type': 'integer' }, + 42, + ], + [ + 'decimalOrNull', + MatchersV3.decimalOrNull(4.2), + { 'pact:matcher:type': 'decimal' }, + 4.2, + ], + [ + 'numberOrNull', + MatchersV3.numberOrNull(42), + { 'pact:matcher:type': 'number' }, + 42, + ], + [ + 'booleanOrNull', + MatchersV3.booleanOrNull(false), + { 'pact:matcher:type': 'type' }, + false, + ], + [ + 'regexOrNull', + MatchersV3.regexOrNull('^\\d+$', '42'), + { 'pact:matcher:type': 'regex', regex: '^\\d+$' }, + '42', + ], + [ + 'uuidOrNull', + MatchersV3.uuidOrNull('e2490de5-5bd3-43d5-b7c4-526e33f71304'), + { + 'pact:matcher:type': 'regex', + regex: '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', + }, + 'e2490de5-5bd3-43d5-b7c4-526e33f71304', + ], + ])('%s combines the matcher with null', (_, result, matcher, example) => { + expect(result).toEqual({ + 'pact:matcher:type': [matcher, nullAlternative], + 'pact:matcher:combine': 'OR', + value: example, + }); + }); + + it('keeps the generator when no example is given', () => { + expect(MatchersV3.integerOrNull()).toEqual({ + 'pact:generator:type': 'RandomInt', + 'pact:matcher:type': [ + { 'pact:matcher:type': 'integer' }, + nullAlternative, + ], + 'pact:matcher:combine': 'OR', + value: 101, + }); + }); + }); + describe('#url', () => { it('returns a JSON representation of a regex matcher for the URL', () => { const result = MatchersV3.url2('http://localhost:8080', [ diff --git a/src/v3/matchers.ts b/src/v3/matchers.ts index b68f00399..21ea2af32 100644 --- a/src/v3/matchers.ts +++ b/src/v3/matchers.ts @@ -15,9 +15,11 @@ import { } from '../common/matcherFormats'; import type { ArrayContainsMatcher, + CombinedMatcher, DateTimeMatcher, HTTPResponseStatusClass, Matcher, + MatcherAlternative, MaxLikeMatcher, MinLikeMatcher, ProviderStateInjectedValue, @@ -506,6 +508,164 @@ export function nullValue(): Matcher { }; } +type AnyMatcher = Matcher | CombinedMatcher; + +/** The example type of a matcher, e.g. `string` for `Matcher` */ +type MatcherExample = + M extends CombinedMatcher + ? T + : M extends Matcher + ? T + : never; + +const isCombinedMatcher = (x: unknown): x is CombinedMatcher => + x != null && + Array.isArray((x as CombinedMatcher)['pact:matcher:type']); + +/** + * Converts a matcher into the list of single matchers used in an OR group. The example + * (`value`) and any generator are dropped, as only the example of the first matcher is used. + */ +const toAlternatives = ( + matcher: AnyMatcher, + index: number, +): MatcherAlternative[] => { + if ( + matcher == null || + typeof matcher !== 'object' || + matcher['pact:matcher:type'] === undefined + ) { + throw new Error( + `anyOf: argument ${index + 1} is not a matcher. Wrap example values in a matcher, e.g. equal(value)`, + ); + } + if (isCombinedMatcher(matcher)) { + if (matcher['pact:matcher:combine'].toUpperCase() !== 'OR') { + throw new Error( + `anyOf: argument ${index + 1} combines its matchers with ${matcher['pact:matcher:combine']}, which can not be nested in an OR`, + ); + } + return matcher['pact:matcher:type']; + } + const { + value: _value, + 'pact:generator:type': _generator, + ...alternative + } = matcher as Matcher & Record; + return [alternative]; +}; + +/** + * Value must match at least one of the given matchers (the matchers are combined with OR). + * + * The example used in the consumer test is taken from the first matcher, so order the + * matchers so that the one with the example you want comes first. Only that example is + * exercised by the consumer test; the other alternatives are only checked when verifying + * the provider. + * + * Matchers nested inside the first matcher's example (e.g. `like({ id: integer(1) })`) + * still apply to the children of the value. + * + * Requires a version of the Pact FFI that supports `pact:matcher:combine` + * (pact-foundation/pact-reference#601). + * + * @example + * anyOf(string('Fred'), nullValue()) + * anyOf(uuid(), regex(/^\d+$/, '42')) + * + * @param matchers The matchers to combine. At least one is required. + */ +export function anyOf[]>( + ...matchers: M +): CombinedMatcher> { + if (matchers.length === 0) { + throw new Error('anyOf: at least one matcher is required'); + } + const alternatives = matchers.flatMap(toAlternatives); + const [first] = matchers; + if (first.value === undefined) { + throw new Error( + `anyOf: the first matcher ('${JSON.stringify(first['pact:matcher:type'])}') has no example value`, + ); + } + + // Keep the generator of the first matcher (and its attributes, e.g. the provider + // state expression), as the example comes from it + const generator = + first['pact:generator:type'] !== undefined + ? (({ 'pact:matcher:type': _type, value: _value, ...rest }) => rest)( + first as Matcher & Record, + ) + : {}; + + return { + ...generator, + 'pact:matcher:type': alternatives, + 'pact:matcher:combine': 'OR', + value: first.value as MatcherExample, + }; +} + +/** + * Value must be either null, or match the given template by type. Use this for + * optional objects, e.g. `likeOrNull({ street: string('Main St'), number: integer(42) })` + * @param template Template to base the comparison on + */ +export const likeOrNull = (template: T): CombinedMatcher => + anyOf(like(template), nullValue()); + +/** + * Value must be either null, or a string + * @param str Example value + */ +export const stringOrNull = (str?: string): CombinedMatcher => + anyOf(string(str), nullValue()); + +/** + * Value must be either null, or an integer + * @param int Example value. If omitted a random value will be generated. + */ +export const integerOrNull = (int?: number): CombinedMatcher => + anyOf(integer(int), nullValue()); + +/** + * Value must be either null, or a decimal number + * @param num Example value. If omitted a random value will be generated. + */ +export const decimalOrNull = (num?: number): CombinedMatcher => + anyOf(decimal(num), nullValue()); + +/** + * Value must be either null, or a number + * @param num Example value. If omitted a random integer value will be generated. + */ +export const numberOrNull = (num?: number): CombinedMatcher => + anyOf(number(num), nullValue()); + +/** + * Value must be either null, or a boolean + * @param b Example value. Defaults to true if unsupplied + */ +export const booleanOrNull = (b?: boolean): CombinedMatcher => + anyOf(boolean(b), nullValue()); + +/** + * Value must be either null, or match the given regular expression + * @param pattern Regular Expression to match + * @param str Example value + */ +export const regexOrNull = ( + pattern: RegExp | string, + str: string, +): CombinedMatcher => anyOf(regex(pattern, str), nullValue()); + +/** + * Value must be either null, or a UUID + * @param example Example value. If omitted a random value will be generated. + */ +export const uuidOrNull = (example?: string): CombinedMatcher => + anyOf(uuid(example), nullValue()); + function stringFromRegex(r: RegExp): string { return new RandExp(r).gen(); } diff --git a/src/v3/types.ts b/src/v3/types.ts index 9ec49497b..4eea62abf 100644 --- a/src/v3/types.ts +++ b/src/v3/types.ts @@ -54,6 +54,28 @@ export interface RulesMatcher extends Matcher { rules: Matcher[]; } +/** + * Logic used to combine a list of matchers for the same path + */ +export type MatcherCombineLogic = 'AND' | 'OR'; + +/** + * A single matcher used as one of the alternatives in a {@link CombinedMatcher}. + * It carries the matcher type and its attributes (e.g. `regex`), but no example value. + */ +export type MatcherAlternative = Omit, 'value'> & + Record; + +/** + * Several matchers applied to the same path, combined with the given logic. + * Only the `value` is used as the example. + */ +export interface CombinedMatcher + extends Omit, 'pact:matcher:type'> { + 'pact:matcher:type': MatcherAlternative[]; + 'pact:matcher:combine': MatcherCombineLogic; +} + /** * Enum for HTTP response status classes used with the status code matcher. * These values correspond to the status code ranges defined in RFC 7231. @@ -146,14 +168,23 @@ export interface V3ProviderState { } export declare type TemplateHeaders = { - [header: string]: string | Matcher | (Matcher | string)[]; + [header: string]: + | string + | Matcher + | CombinedMatcher + | (Matcher | CombinedMatcher | string)[]; }; export type TemplateQuery = Record< string, | string | Matcher - | Array> + | CombinedMatcher + | Array< + | string + | Matcher + | CombinedMatcher + > >; export interface V3Interaction { From 85247fa4ef87abca2ac53d13dbd650763035e0c0 Mon Sep 17 00:00:00 2001 From: Yousaf Nabi Date: Mon, 9 Nov 2026 19:01:31 +0000 Subject: [PATCH 2/2] test: consume pact_ffi 0.5.13-or.1 via YOU54F/pact-js-core feat/or-matcher build (revert before merge) Adds a pact-core-rc job that builds @pact-foundation/pact-core's JS from the latest YOU54F/pact-js-core feat/or-matcher PR run and bundles that run's native prebuilds, which are compiled against the pact_ffi 0.5.13-or.1 prerelease from YOU54F/pact-reference. The test and test-alpine jobs overlay that dist onto the npm-installed pact-core, point PACT_PREBUILD_LOCATION at the prebuilds, and fail unless the loaded pact_ffi reports 0.5.13-or.1. Nothing is published to npm. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 83 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e07fd6175..f84a8e174 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -48,6 +48,63 @@ jobs: || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') + # TEMPORARY (revert before merge): builds @pact-foundation/pact-core from + # YOU54F/pact-js-core feat/or-matcher, whose CI prebuilds the native addon against the + # pact_ffi 0.5.13-or.1 prerelease from YOU54F/pact-reference, and hands the + # JS build plus those prebuilds to the test jobs. + pact-core-rc: + name: Fetch pact-core build (pact_ffi rc) + runs-on: ubuntu-latest + env: + PACT_CORE_REPO: YOU54F/pact-js-core + PACT_CORE_BRANCH: feat/or-matcher + GH_TOKEN: ${{ github.token }} + + steps: + - name: Find the latest pact-js-core run with prebuilds + id: run + run: | + run_id=$(gh run list --repo "$PACT_CORE_REPO" --branch "$PACT_CORE_BRANCH" \ + --workflow build-and-test.yml --event pull_request \ + --json databaseId,headSha -L 1 -q '.[0].databaseId') + sha=$(gh run view "$run_id" --repo "$PACT_CORE_REPO" --json headSha -q .headSha) + echo "Using $PACT_CORE_REPO run $run_id at $sha" + echo "id=$run_id" >> "$GITHUB_OUTPUT" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + + - name: Checkout pact-js-core + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ env.PACT_CORE_REPO }} + ref: ${{ steps.run.outputs.sha }} + path: pact-js-core + + - name: Setup Node.JS + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ env.STABLE_NODE_VERSION }} + + - name: Build pact-core JS + working-directory: pact-js-core + run: | + npm ci --ignore-scripts + npm run build + grep -n "PACT_FFI_VERSION =" src/ffi/index.ts + + - name: Assemble pact-core with prebuilds + run: | + gh run download "${{ steps.run.outputs.id }}" --repo "$PACT_CORE_REPO" -p 'artifact-*' -D artifacts + mkdir -p pact-core-rc + cp -R pact-js-core/dist pact-core-rc/dist + for f in artifacts/*/*.tar.gz; do tar -xzf "$f" -C pact-core-rc; done + find pact-core-rc/prebuilds -type f + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: pact-core-rc + path: pact-core-rc + if-no-files-found: error + lint: name: Lint runs-on: ubuntu-latest @@ -113,6 +170,7 @@ jobs: with Node ${{ matrix.node-version }} runs-on: ${{ matrix.os }} + needs: [pact-core-rc] strategy: fail-fast: false @@ -137,6 +195,19 @@ jobs: cache: npm - run: npm ci + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: pact-core-rc + path: pact-core-rc + - name: Use pact-core build with pact_ffi rc (revert before merge) + shell: bash + run: | + rm -rf node_modules/@pact-foundation/pact-core/dist + cp -R pact-core-rc/dist node_modules/@pact-foundation/pact-core/dist + echo "PACT_PREBUILD_LOCATION=$(node -p "require('path').resolve('pact-core-rc')")" >> "$GITHUB_ENV" + - name: Check the loaded pact_ffi version + shell: bash + run: node -e "const v=require('@pact-foundation/pact-core').getFfiLib('info').pactffiVersion(); console.log('pact_ffi', v); if (v !== '0.5.13-or.1') process.exit(1)" - run: npm test shell: bash @@ -161,6 +232,7 @@ jobs: with Node ${{ matrix.node-version }} runs-on: ubuntu-latest + needs: [pact-core-rc] container: image: node:${{ matrix.node-version }}-alpine @@ -174,6 +246,17 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: npm ci + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: pact-core-rc + path: pact-core-rc + - name: Use pact-core build with pact_ffi rc (revert before merge) + run: | + rm -rf node_modules/@pact-foundation/pact-core/dist + cp -R pact-core-rc/dist node_modules/@pact-foundation/pact-core/dist + echo "PACT_PREBUILD_LOCATION=$(node -p "require('path').resolve('pact-core-rc')")" >> "$GITHUB_ENV" + - name: Check the loaded pact_ffi version + run: node -e "const v=require('@pact-foundation/pact-core').getFfiLib('info').pactffiVersion(); console.log('pact_ffi', v); if (v !== '0.5.13-or.1') process.exit(1)" - run: npm test examples: