All MicroEvals
You are a staff-level TypeScript engineer implementing the c...
Create MicroEval
Header image for You are a staff-level TypeScript engineer implementing the c...

You are a staff-level TypeScript engineer implementing the c...

Prompt

You are a staff-level TypeScript engineer implementing the core of a production shipping-quote service. Your solution will be evaluated for: * behavioral correctness * TypeScript type safety * asynchronous and cancellation correctness * architectural judgment * maintainability and extensibility * simplicity and resistance to overengineering * test quality Do not merely describe the solution. Produce a complete, runnable implementation. ## Environment * Node.js 24 LTS * TypeScript 7.x * ECMAScript modules * `module` and `moduleResolution`: `NodeNext` * Nodeโ€™s built-in `node:test` and `node:assert` * No third-party runtime dependencies * TypeScript may be the only development dependency The following commands must succeed: ```bash npm run typecheck npm test ``` Native TypeScript execution alone is not sufficient; `typecheck` must invoke the TypeScript compiler with `--noEmit`. ## Objective Implement a shipping-quote service with this public API: ```ts export interface QuoteService { search( rawInput: unknown, signal?: AbortSignal, ): Promise<QuoteSearchResult>; } export function createQuoteService( dependencies: QuoteServiceDependencies, ): QuoteService; ``` Define all other necessary types and interfaces. A quote provider must conform to: ```ts export interface QuoteProvider { readonly id: string; getQuotes( request: QuoteRequest, signal: AbortSignal, ): Promise<unknown>; } ``` Provider responses are deliberately typed as `unknown` because they cross an external-system boundary. ## Search input A valid request has this logical shape: ```ts { originPostalCode: string; destinationPostalCode: string; currency: "PHP" | "USD"; parcels: Array<{ weightGrams: number; lengthCm: number; widthCm: number; heightCm: number; }>; } ``` Rules: * Postal codes must be non-empty after trimming. * Normalize postal codes by trimming and converting them to uppercase. * There must be between 1 and 20 parcels. * All parcel measurements must be finite positive integers. * Reject unknown or malformed input without using unchecked property access. * Validation failures are expected outcomes, not unexpected exceptions. ## Provider response Each provider should return an array with this logical shape: ```ts Array<{ serviceCode: string; amountMinor: number; currency: string; estimatedDays: number; }> ``` Validate every provider response at runtime. A valid quote must have: * a non-empty `serviceCode` * a finite, non-negative integer `amountMinor` * the same currency requested by the caller * a finite positive integer `estimatedDays` A malformed provider response is a provider failure. It must not corrupt or invalidate valid results from other providers. ## Provider failures A provider may reject with any JavaScript value. Recognize the following structured failure when it is safely identifiable: ```ts { kind: "transient" | "permanent"; code: string; message: string; } ``` Requirements: * Retry a transient provider failure at most once. * Do not retry permanent failures. * Do not retry malformed provider responses. * Do not retry after caller cancellation. * Use an injected sleeper and randomness source so retry behavior is deterministic in tests. * Do not expose raw thrown values, stack traces, or sensitive provider details in the public result. ## Concurrency and timeouts * Query all configured providers. * Enforce a configurable maximum number of simultaneously executing provider calls. * Each provider attempt has an independent configurable timeout. * A timeout must cancel that provider attempt through an `AbortSignal`. * Caller cancellation must stop that caller promptly. * Clean up timers and abort listeners. * Do not leave rejected promises unobserved. * One failed or timed-out provider must not cancel unrelated providers. ## Aggregation * Return valid quotes even when some providers fail. * If every provider fails, return a typed failure result rather than throwing an expected operational error. * Deduplicate quotes by `(providerId, serviceCode)`. * When a provider returns duplicate service codes, retain the quote with the lowest `amountMinor`; use the lowest `estimatedDays` as the secondary choice. * Sort the final quotes deterministically by: 1. `amountMinor`, ascending 2. `estimatedDays`, ascending 3. `providerId`, lexicographically 4. `serviceCode`, lexicographically * Preserve enough structured failure information for callers to identify which providers failed and whether each failure was transient, permanent, malformed, or timed out. ## Cache and request coalescing Implement an in-memory TTL cache. Requirements: * Construct the cache key from the normalized request, independent of object-property insertion order. * Cache only a result that: * contains at least one valid quote; and * contains no provider failures. * Do not cache validation failures, cancellations, total failures, or partial results. * Concurrent equivalent searches must share one in-flight provider operation rather than issuing duplicate provider requests. * Cancelling one caller must not cancel shared work still required by another caller. * A cancelled caller must nevertheless stop awaiting the shared operation promptly. * Expired cache entries must not be returned. * Inject the clock so cache tests require no real waiting. * Do not use module-level mutable state. ## Design constraints The implementation should make adding another quote provider require no modification to the quote-service orchestration logic. Use abstractions only where they enforce a boundary, isolate a side effect, or remove meaningful duplication. Do not use: * `any` * `@ts-ignore` * `@ts-expect-error` * unchecked double assertions such as `value as unknown as T` * non-null assertions as a substitute for correct modeling * decorators * a dependency-injection container * global service locators * generic repository abstractions * `BaseService`, `BaseProvider`, or similar inheritance hierarchies * framework-style middleware pipelines * speculative abstractions for requirements that do not exist Expected operational failures should be represented explicitly. Unexpected programming failures may still throw. Use the strictest practical TypeScript compiler configuration, including options that catch unsafe indexed access and inaccurate optional-property handling. ## Required tests At minimum, include deterministic tests covering: 1. malformed search input 2. normalization and equivalent cache keys 3. malformed provider output 4. partial success when one provider fails 5. total provider failure 6. retry of a transient failure 7. no retry of a permanent failure 8. provider timeout 9. caller cancellation 10. deterministic quote ordering 11. duplicate quote resolution 12. maximum provider concurrency 13. cache hit and TTL expiration 14. coalescing of concurrent equivalent requests 15. cancellation of one coalesced caller without cancelling another Tests must verify observable behavior rather than private implementation details. ## Complexity budget * Maximum 8 production source files * Maximum 500 non-test lines of production TypeScript * Prefer ordinary functions and small explicit interfaces. * Classes are acceptable only where stateful identity or lifecycle makes them clearer. * Do not compress code merely to satisfy the line limit. * Do not omit necessary code. ## Output format Return: 1. A design note of at most 200 words explaining: * the major boundaries and invariants; * the cancellation/coalescing strategy; * one plausible design you deliberately rejected as unnecessary or unsafe. 2. A file tree. 3. Complete contents of every file, each under a heading containing its path. 4. No placeholders, ellipses, pseudocode, or statements such as โ€œthe remaining tests would be similar.โ€ 5. A final line containing the exact commands needed to install, type-check, and test the project. Do not provide a step-by-step internal reasoning transcript.

Drag to resize
Drag to resize