@specter-automation/test 1.0.108 → 1.0.109

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.
@@ -100,6 +100,11 @@ export declare class SpecterTransport {
100
100
  clientName?: string;
101
101
  private pendingRequests;
102
102
  private eventListeners;
103
+ recentEvents: Array<{
104
+ eventKey: string;
105
+ data: any;
106
+ timestamp: number;
107
+ }>;
103
108
  static getInstance(url?: string): SpecterTransport;
104
109
  get port(): string;
105
110
  get friendlyPortTag(): string;
@@ -116,6 +121,18 @@ export declare class SpecterTransport {
116
121
  * Cleans up an event listener.
117
122
  */
118
123
  removeEventListener(eventKey: string, callback: (data: any) => void): void;
124
+ /**
125
+ * Records an unsolicited event into the circular ring buffer.
126
+ */
127
+ recordRecentEvent(eventKey: string, data: any): void;
128
+ /**
129
+ * Returns recent events matching the eventKey, optionally filtered to events since a given timestamp.
130
+ */
131
+ getRecentEvents(eventKey?: string, sinceTimestamp?: number): Array<{
132
+ eventKey: string;
133
+ data: any;
134
+ timestamp: number;
135
+ }>;
119
136
  }
120
137
  export interface LoadMapOptions {
121
138
  gameMode?: string;
@@ -40,6 +40,8 @@ class SpecterTransport {
40
40
  // The Enterprise Fix: Routing responses to the correct Promise
41
41
  pendingRequests = new Map();
42
42
  eventListeners = new Map();
43
+ // Buffered recent events to eliminate race conditions between event arrival and listener attachment
44
+ recentEvents = [];
43
45
  static getInstance(url = 'ws://127.0.0.1:8080') {
44
46
  if (!SpecterTransport.instance) {
45
47
  SpecterTransport.instance = new SpecterTransport(url);
@@ -148,6 +150,8 @@ class SpecterTransport {
148
150
  this.currentMap = responseObj.data.map;
149
151
  }
150
152
  const eventKey = `${responseObj.locatorId}_${responseObj.eventName}`;
153
+ // Buffer recent events with timestamps to eliminate race conditions
154
+ this.recordRecentEvent(eventKey, responseObj.data);
151
155
  // If a test script is currently waiting for this event...
152
156
  if (this.eventListeners.has(eventKey)) {
153
157
  const callbacks = this.eventListeners.get(eventKey);
@@ -240,6 +244,27 @@ class SpecterTransport {
240
244
  }
241
245
  }
242
246
  }
247
+ /**
248
+ * Records an unsolicited event into the circular ring buffer.
249
+ */
250
+ recordRecentEvent(eventKey, data) {
251
+ this.recentEvents.push({ eventKey, data, timestamp: Date.now() });
252
+ if (this.recentEvents.length > 200) {
253
+ this.recentEvents.shift();
254
+ }
255
+ }
256
+ /**
257
+ * Returns recent events matching the eventKey, optionally filtered to events since a given timestamp.
258
+ */
259
+ getRecentEvents(eventKey, sinceTimestamp) {
260
+ return this.recentEvents.filter(e => {
261
+ if (eventKey && e.eventKey !== eventKey)
262
+ return false;
263
+ if (sinceTimestamp !== undefined && e.timestamp < sinceTimestamp)
264
+ return false;
265
+ return true;
266
+ });
267
+ }
243
268
  }
244
269
  exports.SpecterTransport = SpecterTransport;
245
270
  class SpecterWorld {
@@ -1,5 +1,4 @@
1
1
  import { SpecterLocator, ActorLocator } from '../core/locators';
2
- import { SpecterTimelineEvent } from '../core/specter-client';
3
2
  declare global {
4
3
  namespace PlaywrightTest {
5
4
  interface Matchers<R, T> {
@@ -45,6 +44,8 @@ export interface GasMatchers {
45
44
  effectCauser?: string | ActorLocator;
46
45
  gameplayEffect?: string;
47
46
  ability?: string;
47
+ timeout?: number;
48
+ tolerance?: number;
48
49
  }, triggerAction?: () => Promise<void>): Promise<void>;
49
50
  toHaveGameplayTag(tag: string): Promise<void>;
50
51
  toHaveGameplayEffect(effectClassPath: string): Promise<void>;
@@ -80,16 +81,20 @@ export declare const gasExpect: import("playwright/test").Expect<{
80
81
  effectCauser?: string | ActorLocator;
81
82
  gameplayEffect?: string;
82
83
  ability?: string;
84
+ timeout?: number;
85
+ tolerance?: number;
83
86
  }, triggerAction?: () => Promise<void>): Promise<{
84
87
  pass: boolean;
85
88
  message: () => string;
86
- actual: SpecterTimelineEvent | undefined;
89
+ actual: any;
87
90
  expected: {
88
91
  delta?: number;
89
92
  instigator?: string | ActorLocator;
90
93
  effectCauser?: string | ActorLocator;
91
94
  gameplayEffect?: string;
92
95
  ability?: string;
96
+ timeout?: number;
97
+ tolerance?: number;
93
98
  };
94
99
  }>;
95
100
  toHaveGameplayTag(this: import("playwright/test").ExpectMatcherState, locator: ActorLocator, tag: string): Promise<{
@@ -162,6 +162,9 @@ exports.gasExpect = test_1.expect.extend({
162
162
  const assertionName = 'toHaveAttributeChange';
163
163
  const isNot = this.isNot;
164
164
  const prefix = isNot ? 'not.toHaveAttributeChange' : 'toHaveAttributeChange';
165
+ const timeout = expectedChange.timeout ?? 10000;
166
+ const tolerance = expectedChange.tolerance ?? 0.01;
167
+ const startTime = Date.now();
165
168
  // Format expectations for description
166
169
  const expectedParts = [];
167
170
  if (expectedChange.delta !== undefined)
@@ -181,97 +184,228 @@ exports.gasExpect = test_1.expect.extend({
181
184
  const stepName = `${prefix}('${attributeSet}', '${attributeName}', { ${expectedParts.join(', ')} }) @ ${locator.toString()}`;
182
185
  return await test_1.default.step(stepName, async () => {
183
186
  const transport = locator.transport;
184
- const timeout = 10000;
185
- // Trigger C++ tracking of this attribute by reading its value once
186
- await locator.getAttributeValue(attributeSet, attributeName);
187
- // Resolve target expected names for locators
188
- let expectedInstigatorName;
189
- if (expectedChange.instigator) {
190
- if (typeof expectedChange.instigator === 'string') {
191
- expectedInstigatorName = expectedChange.instigator;
192
- }
193
- else {
194
- expectedInstigatorName = await expectedChange.instigator.getObjectName();
187
+ let lastEvent;
188
+ let lastFailedReasons = [];
189
+ let initialValue;
190
+ // Synchronously register live listener immediately to capture all events during setup & action
191
+ const capturedEvents = [];
192
+ let onLiveEvent = null;
193
+ const liveListener = (event) => {
194
+ capturedEvents.push(event);
195
+ if (onLiveEvent) {
196
+ onLiveEvent(event);
195
197
  }
198
+ };
199
+ if (transport && typeof transport.registerEventListener === 'function') {
200
+ transport.registerEventListener('GLOBAL_timeline-event', liveListener);
196
201
  }
197
- let expectedEffectCauserName;
198
- if (expectedChange.effectCauser) {
199
- if (typeof expectedChange.effectCauser === 'string') {
200
- expectedEffectCauserName = expectedChange.effectCauser;
202
+ try {
203
+ // In parallel: resolve initial value and locator names
204
+ const [resolvedInitialVal, expectedInstigatorName, expectedEffectCauserName] = await Promise.all([
205
+ locator.getAttributeValue(attributeSet, attributeName).catch(() => undefined),
206
+ expectedChange.instigator
207
+ ? (typeof expectedChange.instigator === 'string' ? Promise.resolve(expectedChange.instigator) : expectedChange.instigator.getObjectName().catch(() => undefined))
208
+ : Promise.resolve(undefined),
209
+ expectedChange.effectCauser
210
+ ? (typeof expectedChange.effectCauser === 'string' ? Promise.resolve(expectedChange.effectCauser) : expectedChange.effectCauser.getObjectName().catch(() => undefined))
211
+ : Promise.resolve(undefined),
212
+ ]);
213
+ initialValue = resolvedInitialVal;
214
+ // Evaluates whether an event matches all expected criteria
215
+ const evaluateEvent = (event) => {
216
+ if (event.eventType !== specter_client_1.SpecterEventType.GameplayAttribute && event.eventType !== 'GameplayAttribute') {
217
+ return false;
218
+ }
219
+ if (event.eventName !== attributeName && !event.eventName?.includes(attributeName)) {
220
+ return false;
221
+ }
222
+ lastEvent = event;
223
+ lastFailedReasons = [];
224
+ let isMatch = true;
225
+ // 1. Delta check
226
+ if (expectedChange.delta !== undefined) {
227
+ const oldVal = parseFloat(event.oldValue);
228
+ const newVal = parseFloat(event.newValue);
229
+ const actualDelta = newVal - oldVal;
230
+ const expDelta = expectedChange.delta;
231
+ // Check signed delta match, or magnitude match (e.g. damage written as positive vs negative)
232
+ const deltaMatch = Math.abs(actualDelta - expDelta) <= tolerance ||
233
+ Math.abs(Math.abs(actualDelta) - Math.abs(expDelta)) <= tolerance;
234
+ if (!deltaMatch) {
235
+ isMatch = false;
236
+ lastFailedReasons.push(`delta (expected: ${expDelta}, actual: ${actualDelta})`);
237
+ }
238
+ }
239
+ // 2. Instigator check
240
+ if (expectedInstigatorName !== undefined) {
241
+ const inst = (event.instigator || '').trim();
242
+ if (!inst || (!inst.includes(expectedInstigatorName) && !expectedInstigatorName.includes(inst))) {
243
+ isMatch = false;
244
+ lastFailedReasons.push(`instigator (expected to include: '${expectedInstigatorName}', actual: '${event.instigator}')`);
245
+ }
246
+ }
247
+ // 3. Effect Causer check
248
+ if (expectedEffectCauserName !== undefined) {
249
+ const causer = (event.effectCauser || '').trim();
250
+ if (!causer || (!causer.includes(expectedEffectCauserName) && !expectedEffectCauserName.includes(causer))) {
251
+ isMatch = false;
252
+ lastFailedReasons.push(`effectCauser (expected to include: '${expectedEffectCauserName}', actual: '${event.effectCauser}')`);
253
+ }
254
+ }
255
+ // 4. Gameplay Effect check
256
+ if (expectedChange.gameplayEffect !== undefined) {
257
+ if (!event.gameplayEffect || (!event.gameplayEffect.includes(expectedChange.gameplayEffect) && !expectedChange.gameplayEffect.includes(event.gameplayEffect))) {
258
+ isMatch = false;
259
+ lastFailedReasons.push(`gameplayEffect (expected to include: '${expectedChange.gameplayEffect}', actual: '${event.gameplayEffect}')`);
260
+ }
261
+ }
262
+ // 5. Ability check
263
+ if (expectedChange.ability !== undefined) {
264
+ if (!event.ability || (!event.ability.includes(expectedChange.ability) && !expectedChange.ability.includes(event.ability))) {
265
+ isMatch = false;
266
+ lastFailedReasons.push(`ability (expected to include: '${expectedChange.ability}', actual: '${event.ability}')`);
267
+ }
268
+ }
269
+ return isMatch;
270
+ };
271
+ // --- 1. TRY ONCE IMMEDIATELY ---
272
+ // A. Check events captured in real-time during setup
273
+ for (const ev of capturedEvents) {
274
+ if (evaluateEvent(ev)) {
275
+ return {
276
+ pass: !isNot,
277
+ message: () => 'passed',
278
+ actual: ev,
279
+ expected: expectedChange
280
+ };
281
+ }
201
282
  }
202
- else {
203
- expectedEffectCauserName = await expectedChange.effectCauser.getObjectName();
283
+ // B. Check transport recent events ring buffer (events from just before or during call)
284
+ if (transport && typeof transport.getRecentEvents === 'function') {
285
+ const recent = transport.getRecentEvents('GLOBAL_timeline-event', startTime - 3000);
286
+ for (const item of recent) {
287
+ if (evaluateEvent(item.data)) {
288
+ return {
289
+ pass: !isNot,
290
+ message: () => 'passed',
291
+ actual: item.data,
292
+ expected: expectedChange
293
+ };
294
+ }
295
+ }
204
296
  }
205
- }
206
- let matchEvent;
207
- let lastEvent;
208
- let lastFailedReasons = [];
209
- try {
210
- // Wait for the timeline event matching the criteria
211
- const matchPromise = new Promise((resolve, reject) => {
212
- let timeoutId;
213
- const listener = (event) => {
214
- if (event.eventType === specter_client_1.SpecterEventType.GameplayAttribute &&
215
- (event.eventName === attributeName || event.eventName.includes(attributeName))) {
216
- lastEvent = event;
217
- lastFailedReasons = [];
218
- let isMatch = true;
219
- // 1. Delta check
220
- if (expectedChange.delta !== undefined) {
221
- const oldVal = parseFloat(event.oldValue);
222
- const newVal = parseFloat(event.newValue);
223
- const actualDelta = newVal - oldVal;
224
- // Use close comparison for floats (e.g. within 0.01 tolerance)
225
- if (Math.abs(actualDelta - expectedChange.delta) > 0.01) {
226
- isMatch = false;
227
- lastFailedReasons.push(`delta (expected: ${expectedChange.delta}, actual: ${actualDelta})`);
228
- }
229
- }
230
- // 2. Instigator check
231
- if (expectedInstigatorName !== undefined) {
232
- if (event.instigator !== expectedInstigatorName && !event.instigator?.includes(expectedInstigatorName)) {
233
- isMatch = false;
234
- lastFailedReasons.push(`instigator (expected to include: '${expectedInstigatorName}', actual: '${event.instigator}')`);
235
- }
236
- }
237
- // 3. Effect Causer check
238
- if (expectedEffectCauserName !== undefined) {
239
- if (event.effectCauser !== expectedEffectCauserName && !event.effectCauser?.includes(expectedEffectCauserName)) {
240
- isMatch = false;
241
- lastFailedReasons.push(`effectCauser (expected to include: '${expectedEffectCauserName}', actual: '${event.effectCauser}')`);
242
- }
243
- }
244
- // 4. Gameplay Effect check
245
- if (expectedChange.gameplayEffect !== undefined) {
246
- if (event.gameplayEffect !== expectedChange.gameplayEffect && !event.gameplayEffect?.includes(expectedChange.gameplayEffect)) {
247
- isMatch = false;
248
- lastFailedReasons.push(`gameplayEffect (expected to include: '${expectedChange.gameplayEffect}', actual: '${event.gameplayEffect}')`);
249
- }
297
+ // --- 2. EXECUTE TRIGGER ACTION IF PROVIDED ---
298
+ if (triggerAction) {
299
+ await triggerAction();
300
+ // Re-check captured events immediately after trigger action completes
301
+ for (const ev of capturedEvents) {
302
+ if (evaluateEvent(ev)) {
303
+ return {
304
+ pass: !isNot,
305
+ message: () => 'passed',
306
+ actual: ev,
307
+ expected: expectedChange
308
+ };
309
+ }
310
+ }
311
+ }
312
+ // --- 3. HANDLE DELTA: 0 (assertion that value has not changed) ---
313
+ if (expectedChange.delta === 0) {
314
+ const observationMs = Math.min(timeout, 500);
315
+ await new Promise(r => setTimeout(r, observationMs));
316
+ // Verify whether any conflicting attribute change events arrived
317
+ const conflictingEvent = capturedEvents.find(ev => (ev.eventType === specter_client_1.SpecterEventType.GameplayAttribute || ev.eventType === 'GameplayAttribute') &&
318
+ (ev.eventName === attributeName || ev.eventName?.includes(attributeName)) &&
319
+ parseFloat(ev.oldValue) !== parseFloat(ev.newValue));
320
+ if (!conflictingEvent) {
321
+ const currentVal = await locator.getAttributeValue(attributeSet, attributeName).catch(() => initialValue);
322
+ if (initialValue !== undefined && currentVal !== undefined) {
323
+ const delta = currentVal - initialValue;
324
+ if (Math.abs(delta) <= tolerance) {
325
+ return {
326
+ pass: !isNot,
327
+ message: () => 'passed',
328
+ actual: { delta, value: currentVal },
329
+ expected: expectedChange
330
+ };
250
331
  }
251
- // 5. Ability check
252
- if (expectedChange.ability !== undefined) {
253
- if (event.ability !== expectedChange.ability && !event.ability?.includes(expectedChange.ability)) {
254
- isMatch = false;
255
- lastFailedReasons.push(`ability (expected to include: '${expectedChange.ability}', actual: '${event.ability}')`);
332
+ }
333
+ else if (currentVal !== undefined) {
334
+ return {
335
+ pass: !isNot,
336
+ message: () => 'passed',
337
+ actual: { delta: 0, value: currentVal },
338
+ expected: expectedChange
339
+ };
340
+ }
341
+ }
342
+ }
343
+ // --- 4. LISTEN FOR ATTRIBUTE CHANGE EVENT WITH POLLING FALLBACK ---
344
+ const matchEvent = await new Promise((resolve, reject) => {
345
+ let timeoutId;
346
+ let pollIntervalId;
347
+ let isResolved = false;
348
+ const cleanup = () => {
349
+ if (isResolved)
350
+ return;
351
+ isResolved = true;
352
+ clearTimeout(timeoutId);
353
+ clearInterval(pollIntervalId);
354
+ };
355
+ onLiveEvent = (event) => {
356
+ if (isResolved)
357
+ return;
358
+ if (evaluateEvent(event)) {
359
+ cleanup();
360
+ resolve(event);
361
+ }
362
+ };
363
+ // Check any events that arrived right as onLiveEvent was wired
364
+ for (const ev of capturedEvents) {
365
+ if (evaluateEvent(ev)) {
366
+ cleanup();
367
+ resolve(ev);
368
+ return;
369
+ }
370
+ }
371
+ // Parallel polling fallback
372
+ pollIntervalId = setInterval(async () => {
373
+ if (isResolved)
374
+ return;
375
+ try {
376
+ const currentVal = await locator.getAttributeValue(attributeSet, attributeName);
377
+ if (isResolved)
378
+ return;
379
+ if (currentVal !== undefined && initialValue !== undefined && expectedChange.delta !== undefined) {
380
+ const actualDelta = currentVal - initialValue;
381
+ const expDelta = expectedChange.delta;
382
+ const deltaMatch = Math.abs(actualDelta - expDelta) <= tolerance ||
383
+ Math.abs(Math.abs(actualDelta) - Math.abs(expDelta)) <= tolerance;
384
+ if (deltaMatch) {
385
+ // If no specific instigator/causer was demanded, or if we saw an event matching them:
386
+ if (!expectedInstigatorName && !expectedEffectCauserName && !expectedChange.gameplayEffect && !expectedChange.ability) {
387
+ cleanup();
388
+ resolve(lastEvent || {
389
+ timestamp: Date.now(),
390
+ eventName: attributeName,
391
+ eventType: specter_client_1.SpecterEventType.GameplayAttribute,
392
+ oldValue: String(initialValue),
393
+ newValue: String(currentVal),
394
+ description: `Attribute ${attributeName} changed by ${actualDelta}`,
395
+ });
396
+ }
256
397
  }
257
398
  }
258
- if (isMatch) {
259
- clearTimeout(timeoutId);
260
- transport.removeEventListener('GLOBAL_timeline-event', listener);
261
- resolve(event);
262
- }
263
399
  }
264
- };
400
+ catch {
401
+ // Transient poll errors are suppressed during wait
402
+ }
403
+ }, 100);
265
404
  timeoutId = setTimeout(() => {
266
- transport.removeEventListener('GLOBAL_timeline-event', listener);
405
+ cleanup();
267
406
  reject(new Error(`Timed out after ${timeout}ms waiting for attribute change event on '${attributeName}'`));
268
407
  }, timeout);
269
- transport.registerEventListener('GLOBAL_timeline-event', listener);
270
408
  });
271
- if (triggerAction) {
272
- await triggerAction();
273
- }
274
- matchEvent = await matchPromise;
275
409
  return {
276
410
  pass: !isNot,
277
411
  message: () => 'passed',
@@ -280,7 +414,7 @@ exports.gasExpect = test_1.expect.extend({
280
414
  };
281
415
  }
282
416
  catch (e) {
283
- if (!e.message.includes('Timed out')) {
417
+ if (!e.message?.includes('Timed out')) {
284
418
  throw e;
285
419
  }
286
420
  let failureDetails = `Last checked event: ${lastEvent ? JSON.stringify(lastEvent, null, 2) : 'None received'}`;
@@ -297,6 +431,11 @@ exports.gasExpect = test_1.expect.extend({
297
431
  expected: expectedChange
298
432
  };
299
433
  }
434
+ finally {
435
+ if (transport && typeof transport.removeEventListener === 'function') {
436
+ transport.removeEventListener('GLOBAL_timeline-event', liveListener);
437
+ }
438
+ }
300
439
  });
301
440
  },
302
441
  async toHaveGameplayTag(locator, tag) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@specter-automation/test",
3
- "version": "1.0.108",
3
+ "version": "1.0.109",
4
4
  "description": "Playwright integration for Unreal Engine automation via Specter",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",