Repository: Azure/azure-functions-durable-js
Pull request #451 (2023-02-01 20:29:32)

Add orchestration and entity context type declarations
Part of #416:

* Adds a `DurableOrchestrationContext` class declaration exported from the root of the package that the `DurableOrchestrationContext` class implements. This is the type of the `context.df` object in orchestrations.
* Converts `DurableEntityContext` type into an interface, and also exports it from the root of the package. This is the type of the `context.df` object in entity functions


Patch:
diff --git a/src/classes.ts b/src/classes.ts
index 0ba8cc3..c273707 100644
--- a/src/classes.ts
+++ b/src/classes.ts
@@ -6,7 +6,6 @@ export { Orchestrator } from "./orchestrator";
 export { Entity } from "./entity";
 
 export { DurableEntityBindingInfo } from "./durableentitybindinginfo";
-export { DurableEntityContext } from "./durableentitycontext";
 export { DurableOrchestrationBindingInfo } from "./durableorchestrationbindinginfo";
 export { DurableOrchestrationContext } from "./durableorchestrationcontext";
 
diff --git a/src/durableentitycontext.ts b/src/durableentitycontext.ts
deleted file mode 100644
index 19a8eda..0000000
--- a/src/durableentitycontext.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { EntityId } from "./classes";
-
-/**
- * Provides functionality for application code implementing an entity
- * operation.
- */
-export type DurableEntityContext<TState> = {
-    /**
-     * Gets the name of the currently executing entity.
-     */
-    readonly entityName: string;
-
-    /**
-     * Gets the key of the currently executing entity.
-     */
-    readonly entityKey: string;
-
-    /**
-     * Gets the id of the currently executing entity.
-     */
-    readonly entityId: EntityId;
-
-    /**
-     * Gets the name of the operation that was called.
-     *
-     * An operation invocation on an entity includes an operation name, which
-     * states what operation to perform, and optionally an operation input.
-     */
-    readonly operationName: string | undefined;
-
-    /**
-     * Whether this entity is freshly constructed, i.e. did not exist prior to
-     * this operation being called.
-     */
-    readonly isNewlyConstructed: boolean;
-
-    /**
-     * Gets the current state of this entity, for reading and/or writing.
-     *
-     * @param initializer Provides an initial value to use for the state,
-     * instead of TState's default.
-     * @returns The current state of this entity, or undefined if none has been set yet.
-     */
-    getState(initializer?: () => TState): TState | undefined;
-
-    /**
-     * Sets the current state of this entity.
-     *
-     * @param state The state of the entity.
-     */
-    setState(state: TState): void;
-
-    /**
-     * Gets the input for this operation.
-     *
-     * An operation invocation on an entity includes an operation name, which
-     * states what operation to perform, and optionally an operation input.
-     *
-     * @returns The operation input, or undefined if none.
-     */
-    getInput<TInput = TState>(): TInput | undefined;
-
-    /**
-     * Returns the given result to the caller of this operation.
-     *
-     * @param result The result to return.
-     */
-    return<TResult = TState>(result: TResult): void;
-
-    /**
-     * Deletes this entity after this operation completes.
-     */
-    destructOnExit(): void;
-
-    /**
-     * Signals an entity to perform an operation, without waiting for a
-     * response. Any result or exception is ignored (fire and forget).
-     *
-     * @param entity The target entity.
-     * @param operationName The name of the operation.
-     * @param operationInput The operation input.
-     */
-    signalEntity(entity: EntityId, operationName: string, operationInput?: unknown): void;
-};
diff --git a/src/durableorchestrationclient.ts b/src/durableorchestrationclient.ts
index 0eb88d0..c969397 100644
--- a/src/durableorchestrationclient.ts
+++ b/src/durableorchestrationclient.ts
@@ -21,7 +21,7 @@ import {
     PurgeHistoryResult,
     Utils,
 } from "./classes";
-import { StartNewOptions, DurableClientInput } from "./types";
+import { StartNewOptions, DurableClientInput, DurableClient } from "./types";
 import { WebhookUtils } from "./webhookutils";
 
 /** @hidden */
@@ -33,7 +33,7 @@ const URL = url.URL;
  *  calls this method.
  *
  */
-export function getClient(context: InvocationContext): DurableOrchestrationClient {
+export function getClient(context: InvocationContext): DurableClient {
     const foundInput: FunctionInput | undefined = context.options.extraInputs.find(
         isDurableClientInput
     );
@@ -109,11 +109,7 @@ function correctUrls(obj: { [key: string]: string }): { [key: string]: string }
  * Client for starting, querying, terminating and raising events to
  * orchestration instances.
  */
-export class DurableOrchestrationClient {
-    /**
-     * The name of the task hub configured on this orchestration client
-     * instance.
-     */
+export class DurableOrchestrationClient implements DurableClient {
     public readonly taskHubName: string;
     /** @hidden */
     public readonly uniqueWebhookOrigins: string[];
@@ -163,20 +159,14 @@ export class DurableOrchestrationClient {
         this.uniqueWebhookOrigins = this.extractUniqueWebhookOrigins(this.clientData);
     }
 
-    /**
-     * Creates an HTTP response that is useful for checking the status of the
-     * specified instance.
-     * @param request The HTTP request that triggered the current orchestration
-     *  instance.
-     * @param instanceId The ID of the orchestration instance to check.
-     * @returns An HTTP 202 response with a Location header and a payload
-     *  containing instance management URLs.
-     */
     public createCheckStatusResponse(
         request: HttpRequest | undefined,
         instanceId: string
     ): HttpResponse {
-        const httpManagementPayload = this.getClientResponseLinks(request, instanceId);
+        const httpManagementPayload: HttpManagementPayload = this.getClientResponseLinks(
+            request,
+            instanceId
+        );
 
         return new HttpResponse({
             status: 202,
@@ -189,23 +179,10 @@ export class DurableOrchestrationClient {
         });
     }
 
-    /**
-     * Creates an [[HttpManagementPayload]] object that contains instance
-     * management HTTP endpoints.
-     * @param instanceId The ID of the orchestration instance to check.
-     */
     public createHttpManagementPayload(instanceId: string): HttpManagementPayload {
         return this.getClientResponseLinks(undefined, instanceId);
     }
 
-    /**
-     * Gets the status of the specified orchestration instance.
-     * @param instanceId The ID of the orchestration instance to query.
-     * @param showHistory Boolean marker for including execution history in the
-     *  response.
-     * @param showHistoryOutput Boolean marker for including input and output
-     *  in the execution history response.
-     */
     public async getStatus(
         instanceId: string,
         showHistory?: boolean,
@@ -232,9 +209,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Gets the status of all orchestration instances.
-     */
     public async getStatusAll(): Promise<DurableOrchestrationStatus[]> {
         const response = await this.getStatusInternal({});
         switch (response.status) {
@@ -245,16 +219,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Gets the status of all orchestration instances that match the specified
-     * conditions.
-     * @param createdTimeFrom Return orchestration instances which were created
-     *  after this Date.
-     * @param createdTimeTo Return orchestration instances which were created
-     *  before this DateTime.
-     * @param runtimeStatus Return orchestration instances which match any of
-     *  the runtimeStatus values in this array.
-     */
     public async getStatusBy(
         createdTimeFrom: Date | undefined,
         createdTimeTo: Date | undefined,
@@ -275,10 +239,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Purge the history for a specific orchestration instance.
-     * @param instanceId The ID of the orchestration instance to purge.
-     */
     public async purgeInstanceHistory(instanceId: string): Promise<PurgeHistoryResult> {
         let requestUrl: string;
         if (this.clientData.rpcBaseUrl) {
@@ -302,15 +262,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Purge the orchestration history for instances that match the conditions.
-     * @param createdTimeFrom Start creation time for querying instances for
-     *  purging.
-     * @param createdTimeTo End creation time for querying instances for
-     *  purging.
-     * @param runtimeStatus List of runtime statuses for querying instances for
-     *  purging. Only Completed, Terminated or Failed will be processed.
-     */
     public async purgeInstanceHistoryBy(
         createdTimeFrom: Date,
         createdTimeTo?: Date,
@@ -379,26 +330,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Sends an event notification message to a waiting orchestration instance.
-     * @param instanceId The ID of the orchestration instance that will handle
-     *  the event.
-     * @param eventName The name of the event.
-     * @param eventData The JSON-serializable data associated with the event.
-     * @param taskHubName The TaskHubName of the orchestration that will handle
-     *  the event.
-     * @param connectionName The name of the connection string associated with
-     *  `taskHubName.`
-     * @returns A promise that resolves when the event notification message has
-     *  been enqueued.
-     *
-     * In order to handle the event, the target orchestration instance must be
-     * waiting for an event named `eventName` using
-     * [[waitForExternalEvent]].
-     *
-     * If the specified instance is not found or not running, this operation
-     * will have no effect.
-     */
     public async raiseEvent(
         instanceId: string,
         eventName: string,
@@ -455,17 +386,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Tries to read the current state of an entity. Returnes undefined if the
-     * entity does not exist, or if the JSON-serialized state of the entity is
-     * larger than 16KB.
-     * @param T The JSON-serializable type of the entity.
-     * @param entityId The target entity.
-     * @param taskHubName The TaskHubName of the target entity.
-     * @param connectionName The name of the connection string associated with
-     * [taskHubName].
-     * @returns A response containing the current state of the entity.
-     */
     public async readEntityState<T>(
         entityId: EntityId,
         taskHubName?: string,
@@ -517,14 +437,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Rewinds the specified failed orchestration instance with a reason.
-     * @param instanceId The ID of the orchestration instance to rewind.
-     * @param reason The reason for rewinding the orchestration instance.
-     * @returns A promise that resolves when the rewind message is enqueued.
-     *
-     * This feature is currently in preview.
-     */
     public async rewind(
         instanceId: string,
         reason: string,
@@ -574,14 +486,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Signals an entity to perform an operation.
-     * @param entityId The target entity.
-     * @param operationName The name of the operation.
-     * @param operationContent The content for the operation.
-     * @param taskHubName The TaskHubName of the target entity.
-     * @param connectionName The name of the connection string associated with [taskHubName].
-     */
     public async signalEntity(
         entityId: EntityId,
         operationName?: string,
@@ -640,16 +544,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Starts a new instance of the specified orchestrator function.
-     *
-     * If an orchestration instance with the specified ID already exists, the
-     * existing instance will be silently replaced by this new instance.
-     * @param orchestratorFunctionName The name of the orchestrator function to
-     *  start.
-     * @param options optional object to control the scheduled orchestrator (e.g provide input, instanceID)
-     * @returns The ID of the new orchestration instance.
-     */
     public async startNew(
         orchestratorFunctionName: string,
         options?: StartNewOptions
@@ -684,16 +578,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Terminates a running orchestration instance.
-     * @param instanceId The ID of the orchestration instance to terminate.
-     * @param reason The reason for terminating the orchestration instance.
-     * @returns A promise that resolves when the terminate message is enqueued.
-     *
-     * Terminating an orchestration instance has no effect on any in-flight
-     * activity function executions or sub-orchestrations that were started
-     * by the current orchestration instance.
-     */
     public async terminate(instanceId: string, reason: string): Promise<void> {
         const idPlaceholder = this.clientData.managementUrls.id;
         let requestUrl: string;
@@ -722,22 +606,6 @@ export class DurableOrchestrationClient {
         }
     }
 
-    /**
-     * Creates an HTTP response which either contains a payload of management
-     * URLs for a non-completed instance or contains the payload containing
-     * the output of the completed orchestration.
-     *
-     * If the orchestration does not complete within the specified timeout,
-     * then the HTTP response will be identical to that of
-     * [[createCheckStatusResponse]].
-     *
-     * @param request The HTTP request that triggered the current function.
-     * @param instanceId The unique ID of the instance to check.
-     * @param timeoutInMilliseconds Total allowed timeout for output from the
-     *  durable function. The default value is 10 seconds.
-     * @param retryIntervalInMilliseconds The timeout between checks for output
-     *  from the durable function. The default value is 1 second.
-     */
     public async waitForCompletionOrCreateCheckStatusResponse(
         request: HttpRequest,
         instanceId: string,
diff --git a/src/durableorchestrationcontext.ts b/src/durableorchestrationcontext.ts
index 9777bcb..424cfc4 100644
--- a/src/durableorchestrationcontext.ts
+++ b/src/durableorchestrationcontext.ts
@@ -31,13 +31,14 @@ import {
 import moment = require("moment");
 import { ReplaySchema } from "./replaySchema";
 import { CallHttpOptions, Task, TimerTask } from "./types";
+import * as types from "./types";
 import { SignalEntityAction } from "./actions/signalentityaction";
 
 /**
  * Parameter data for orchestration bindings that can be used to schedule
  * function-based activities.
  */
-export class DurableOrchestrationContext {
+export class DurableOrchestrationContext implements types.DurableOrchestrationContext {
     constructor(
         state: HistoryEvent[],
         instanceId: string,
@@ -80,47 +81,9 @@ export class DurableOrchestrationContext {
      */
     private readonly defaultHttpAsyncRequestSleepTimeMillseconds?: number;
 
-    /**
-     * The ID of the current orchestration instance.
-     *
-     * The instance ID is generated and fixed when the orchestrator function is
-     * scheduled. It can be either auto-generated, in which case it is
-     * formatted as a GUID, or it can be user-specified with any format.
-     */
     public readonly instanceId: string;
-
-    /**
-     * The ID of the parent orchestration of the current sub-orchestration
-     * instance. The value will be available only in sub-orchestrations.
-     *
-     * The parent instance ID is generated and fixed when the parent
-     * orchestrator function is scheduled. It can be either auto-generated, in
-     * which case it is formatted as a GUID, or it can be user-specified with
-     * any format.
-     */
     public readonly parentInstanceId: string | undefined;
-
-    /**
-     * Gets a value indicating whether the orchestrator function is currently
-     * replaying itself.
-     *
-     * This property is useful when there is logic that needs to run only when
-     * the orchestrator function is _not_ replaying. For example, certain types
-     * of application logging may become too noisy when duplicated as part of
-     * orchestrator function replay. The orchestrator code could check to see
-     * whether the function is being replayed and then issue the log statements
-     * when this value is `false`.
-     */
     public isReplaying: boolean;
-
-    /**
-     * Gets the current date/time in a way that is safe for use by orchestrator
-     * functions.
-     *
-     * This date/time value is derived from the orchestration history. It
-     * always returns the same value at specific points in the orchestrator
-     * function code, making it deterministic and safe for replay.
-     */
     public currentUtcDateTime: Date;
 
     /**
@@ -162,11 +125,6 @@ export class DurableOrchestrationContext {
         return tasks.every((x) => x instanceof DFTask);
     }
 
-    /**
-     * Just an entry point to reference the methods in [[ITaskMethods]].
-     * Methods to handle collections of pending actions represented by [[Task]]
-     * instances. For use in parallelization operations.
-     */
     public Task = {
         all: (tasks: Task[]): Task => {
             if (this.isDFTaskArray(tasks)) {
@@ -195,30 +153,12 @@ export class DurableOrchestrationContext {
         },
     };
 
-    /**
-     * Schedules an activity function named `name` for execution.
-     *
-     * @param name The name of the activity function to call.
-     * @param input The JSON-serializable input to pass to the activity
-     * function.
-     * @returns A Durable Task that completes when the called activity
-     * function completes or fails.
-     */
     public callActivity(name: string, input?: unknown): Task {
         const newAction = new CallActivityAction(name, input);
         const task = new AtomicTask(false, newAction);
         return task;
     }
 
-    /**
-     * Schedules an activity function named `name` for execution with
-     * retry options.
-     *
-     * @param name The name of the activity function to call.
-     * @param retryOptions The retry options for the activity function.
-     * @param input The JSON-serializable input to pass to the activity
-     * function.
-     */
     public callActivityWithRetry(name: string, retryOptions: RetryOptions, input?: unknown): Task {
         const newAction = new CallActivityWithRetryAction(name, retryOptions, input);
         const backingTask = new AtomicTask(false, newAction);
@@ -226,43 +166,16 @@ export class DurableOrchestrationContext {
         return task;
     }
 
-    /**
-     * Calls an operation on an entity, passing an argument, and waits for it
-     * to complete.
-     *
-     * @param entityId The target entity.
-     * @param operationName The name of the operation.
-     * @param operationInput The input for the operation.
-     */
     public callEntity(entityId: EntityId, operationName: string, operationInput?: unknown): Task {
         const newAction = new CallEntityAction(entityId, operationName, operationInput);
         const task = new AtomicTask(false, newAction);
         return task;
     }
-
-    /**
-     * Send a signal operation to a Durable Entity, passing an argument, without
-     * waiting for a response. A fire-and-forget operation.
-     *
-     * @param entityId ID of the target entity.
-     * @param operationName The name of the operation.
-     * @param operationInput (optional) input for the operation.
-     */
     public signalEntity(entityId: EntityId, operationName: string, operationInput?: unknown): void {
         const action = new SignalEntityAction(entityId, operationName, operationInput);
         this.taskOrchestratorExecutor.recordFireAndForgetAction(action);
     }
 
-    /**
-     * Schedules an orchestration function named `name` for execution.
-     *
-     * @param name The name of the orchestrator function to call.
-     * @param input The JSON-serializable input to pass to the orchestrator
-     * function.
-     * @param instanceId A unique ID to use for the sub-orchestration instance.
-     * If `instanceId` is not specified, the extension will generate an id in
-     * the format `<calling orchestrator instance ID>:<#>`
-     */
     public callSubOrchestrator(name: string, input?: unknown, instanceId?: string): Task {
         if (!name) {
             throw new Error(
@@ -275,16 +188,6 @@ export class DurableOrchestrationContext {
         return task;
     }
 
-    /**
-     * Schedules an orchestrator function named `name` for execution with retry
-     * options.
-     *
-     * @param name The name of the orchestrator function to call.
-     * @param retryOptions The retry options for the orchestrator function.
-     * @param input The JSON-serializable input to pass to the orchestrator
-     * function.
-     * @param instanceId A unique ID to use for the sub-orchestration instance.
-     */
     public callSubOrchestratorWithRetry(
         name: string,
         retryOptions: RetryOptions,
@@ -308,11 +211,6 @@ export class DurableOrchestrationContext {
         return task;
     }
 
-    /**
-     * Schedules a durable HTTP call to the specified endpoint.
-     *
-     * @param req The durable HTTP request to schedule.
-     */
     public callHttp(options: CallHttpOptions): Task {
         let content = options.body;
         if (content && typeof content !== "string") {
@@ -354,31 +252,12 @@ export class DurableOrchestrationContext {
         return new AtomicTask(false, newAction);
     }
 
-    /**
-     * Restarts the orchestration by clearing its history.
-     *
-     * @param The JSON-serializable data to re-initialize the instance with.
-     */
     public continueAsNew(input: unknown): void {
         const newAction = new ContinueAsNewAction(input);
         this.taskOrchestratorExecutor.addToActions(newAction);
         this.taskOrchestratorExecutor.willContinueAsNew = true;
     }
 
-    /**
-     * Creates a durable timer that expires at a specified time.
-     *
-     * All durable timers created using this method must either expire or be
-     * cancelled using [[TimerTask]].[[cancel]] before the orchestrator
-     * function completes. Otherwise, the underlying framework will keep the
-     * instance alive until the timer expires.
-     *
-     * Timers currently cannot be scheduled further than 7 days into the
-     * future.
-     *
-     * @param fireAt The time at which the timer should expire.
-     * @returns A TimerTask that completes when the durable timer expires.
-     */
     public createTimer(fireAt: Date): TimerTask {
         const timerAction = new CreateTimerAction(fireAt);
         const durationUntilFire = moment.duration(moment(fireAt).diff(this.currentUtcDateTime));
@@ -409,23 +288,10 @@ export class DurableOrchestrationContext {
         return new DFTimerTask(false, timerAction);
     }
 
-    /**
-     * Gets the input of the current orchestrator function as a deserialized
-     * value.
-     */
     public getInput<T>(): T {
         return this.input as T;
     }
 
-    /**
-     * Creates a new GUID that is safe for replay within an orchestration or
-     * operation.
-     *
-     * The default implementation of this method creates a name-based UUID
-     * using the algorithm from RFC 4122 §4.3. The name input used to generate
-     * this value is a combination of the orchestration instance ID and an
-     * internally managed sequence number.
-     */
     public newGuid(instanceId: string): string {
         const guidNameValue = `${instanceId}_${this.currentUtcDateTime.valueOf()}_${
             this.newGuidCounter
@@ -434,30 +300,10 @@ export class DurableOrchestrationContext {
         return GuidManager.createDeterministicGuid(GuidManager.UrlNamespaceValue, guidNameValue);
     }
 
-    /**
-     * Sets the JSON-serializable status of the current orchestrator function.
-     *
-     * The `customStatusObject` value is serialized to JSON and will be made
-     * available to the orchestration status query APIs. The serialized JSON
-     * value must not exceed 16 KB of UTF-16 encoded text.
-     *
-     * The serialized `customStatusObject` value will be made available to the
-     * aforementioned APIs after the next `yield` or `return` statement.
-     *
-     * @param customStatusObject The JSON-serializable value to use as the
-     * orchestrator function's custom status.
-     */
     public setCustomStatus(customStatusObject: unknown): void {
         this.customStatus = customStatusObject;
     }
 
-    /**
-     * Waits asynchronously for an event to be raised with the name `name` and
-     * returns the event data.
-     *
-     * External clients can raise events to a waiting orchestration instance
-     * using [[raiseEvent]].
-     */
     public waitForExternalEvent(name: string): Task {
         const newAction = new WaitForExternalEventAction(name, ExternalEventType.ExternalEvent);
         const task = new AtomicTask(name, newAction);
diff --git a/src/entity.ts b/src/entity.ts
index eadab11..af5eb9b 100644
--- a/src/entity.ts
+++ b/src/entity.ts
@@ -1,7 +1,6 @@
 import * as debug from "debug";
 import {
     DurableEntityBindingInfo,
-    DurableEntityContext,
     EntityId,
     EntityState,
     OperationResult,
@@ -10,7 +9,7 @@ import {
     Utils,
 } from "./classes";
 import { DurableEntityBindingInfoReqFields } from "./durableentitybindinginfo";
-import { EntityContext } from "./types";
+import { DurableEntityContext, EntityContext } from "./types";
 
 /** @hidden */
 // eslint-disable-next-line @typescript-eslint/no-unused-vars
diff --git a/src/taskorchestrationexecutor.ts b/src/taskorchestrationexecutor.ts
index 12c2355..8c9c6c9 100644
--- a/src/taskorchestrationexecutor.ts
+++ b/src/taskorchestrationexecutor.ts
@@ -1,6 +1,5 @@
 import {
     CallEntityAction,
-    DurableOrchestrationContext,
     EventRaisedEvent,
     EventSentEvent,
     HistoryEvent,
@@ -17,7 +16,7 @@ import { OrchestratorState } from "./orchestratorstate";
 import { TaskBase, NoOpTask, DFTask, CompoundTask, TaskState } from "./task";
 import { ReplaySchema } from "./replaySchema";
 import { Utils } from "./utils";
-import { OrchestrationContext } from "./types";
+import { DurableOrchestrationContext, OrchestrationContext } from "./types";
 
 /**
  * @hidden
diff --git a/src/types/durableClientTypes.ts b/src/types/durableClientTypes.ts
index ef38b6d..a5674e7 100644
--- a/src/types/durableClientTypes.ts
+++ b/src/types/durableClientTypes.ts
@@ -1,9 +1,226 @@
-import { FunctionInput } from "@azure/functions";
+import { FunctionInput, HttpRequest, HttpResponse } from "@azure/functions";
+import { EntityId, EntityStateResponse, OrchestrationClientInputData } from "../classes";
+import { DurableOrchestrationStatus } from "../durableorchestrationstatus";
+import { OrchestrationRuntimeStatus } from "../orchestrationruntimestatus";
 
 export interface DurableClientInput extends FunctionInput {
     type: "durableClient";
 }
 
+/**
+ * Client for starting, querying, terminating and raising events to
+ * orchestration and entity instances.
+ */
+export declare class DurableClient {
+    constructor(clientData: OrchestrationClientInputData);
+
+    /**
+     * The name of the task hub configured on this orchestration client
+     * instance.
+     */
+    readonly taskHubName: string;
+
+    /** @hidden */
+    public readonly uniqueWebhookOrigins: string[];
+
+    /**
+     * Creates an HTTP response that is useful for checking the status of the
+     * specified instance.
+     * @param request The HTTP request that triggered the current orchestration
+     *  instance.
+     * @param instanceId The ID of the orchestration instance to check.
+     * @returns An HTTP 202 response with a Location header and a payload
+     *  containing instance management URLs.
+     */
+    createCheckStatusResponse(request: HttpRequest | undefined, instanceId: string): HttpResponse;
+
+    /**
+     * Creates an [[HttpManagementPayload]] object that contains instance
+     * management HTTP endpoints.
+     * @param instanceId The ID of the orchestration instance to check.
+     */
+    createHttpManagementPayload(instanceId: string): HttpManagementPayload;
+
+    /**
+     * Gets the status of the specified orchestration instance.
+     * @param instanceId The ID of the orchestration instance to query.
+     * @param showHistory Boolean marker for including execution history in the
+     *  response.
+     * @param showHistoryOutput Boolean marker for including input and output
+     *  in the execution history response.
+     */
+    getStatus(
+        instanceId: string,
+        showHistory?: boolean,
+        showHistoryOutput?: boolean,
+        showInput?: boolean
+    ): Promise<DurableOrchestrationStatus>;
+
+    /**
+     * Gets the status of all orchestration instances.
+     */
+    getStatusAll(): Promise<DurableOrchestrationStatus[]>;
+
+    /**
+     * Gets the status of all orchestration instances that match the specified
+     * conditions.
+     * @param createdTimeFrom Return orchestration instances which were created
+     *  after this Date.
+     * @param createdTimeTo Return orchestration instances which were created
+     *  before this DateTime.
+     * @param runtimeStatus Return orchestration instances which match any of
+     *  the runtimeStatus values in this array.
+     */
+    getStatusBy(
+        createdTimeFrom: Date | undefined,
+        createdTimeTo: Date | undefined,
+        runtimeStatus: OrchestrationRuntimeStatus[]
+    ): Promise<DurableOrchestrationStatus[]>;
+
+    /**
+     * Purge the history for a specific orchestration instance.
+     * @param instanceId The ID of the orchestration instance to purge.
+     */
+    purgeInstanceHistory(instanceId: string): Promise<PurgeHistoryResult>;
+
+    /**
+     * Purge the orchestration history for instances that match the conditions.
+     * @param createdTimeFrom Start creation time for querying instances for
+     *  purging.
+     * @param createdTimeTo End creation time for querying instances for
+     *  purging.
+     * @param runtimeStatus List of runtime statuses for querying instances for
+     *  purging. Only Completed, Terminated or Failed will be processed.
+     */
+    purgeInstanceHistoryBy(
+        createdTimeFrom: Date,
+        createdTimeTo?: Date,
+        runtimeStatus?: OrchestrationRuntimeStatus[]
+    ): Promise<PurgeHistoryResult>;
+
+    /**
+     * Sends an event notification message to a waiting orchestration instance.
+     * @param instanceId The ID of the orchestration instance that will handle
+     *  the event.
+     * @param eventName The name of the event.
+     * @param eventData The JSON-serializable data associated with the event.
+     * @param taskHubName The TaskHubName of the orchestration that will handle
+     *  the event.
+     * @param connectionName The name of the connection string associated with
+     *  `taskHubName.`
+     * @returns A promise that resolves when the event notification message has
+     *  been enqueued.
+     *
+     * In order to handle the event, the target orchestration instance must be
+     * waiting for an event named `eventName` using
+     * [[waitForExternalEvent]].
+     *
+     * If the specified instance is not found or not running, this operation
+     * will have no effect.
+     */
+    raiseEvent(
+        instanceId: string,
+        eventName: string,
+        eventData: unknown,
+        taskHubName?: string,
+        connectionName?: string
+    ): Promise<void>;
+
+    /**
+     * Tries to read the current state of an entity. Returnes undefined if the
+     * entity does not exist, or if the JSON-serialized state of the entity is
+     * larger than 16KB.
+     * @param T The JSON-serializable type of the entity.
+     * @param entityId The target entity.
+     * @param taskHubName The TaskHubName of the target entity.
+     * @param connectionName The name of the connection string associated with
+     * [taskHubName].
+     * @returns A response containing the current state of the entity.
+     */
+    readEntityState<T>(
+        entityId: EntityId,
+        taskHubName?: string,
+        connectionName?: string
+    ): Promise<EntityStateResponse<T>>;
+
+    /**
+     * Rewinds the specified failed orchestration instance with a reason.
+     * @param instanceId The ID of the orchestration instance to rewind.
+     * @param reason The reason for rewinding the orchestration instance.
+     * @returns A promise that resolves when the rewind message is enqueued.
+     *
+     * This feature is currently in preview.
+     */
+    rewind(
+        instanceId: string,
+        reason: string,
+        taskHubName?: string,
+        connectionName?: string
+    ): Promise<void>;
+
+    /**
+     * Signals an entity to perform an operation.
+     * @param entityId The target entity.
+     * @param operationName The name of the operation.
+     * @param operationContent The content for the operation.
+     * @param taskHubName The TaskHubName of the target entity.
+     * @param connectionName The name of the connection string associated with [taskHubName].
+     */
+    signalEntity(
+        entityId: EntityId,
+        operationName?: string,
+        operationContent?: unknown,
+        taskHubName?: string,
+        connectionName?: string
+    ): Promise<void>;
+
+    /**
+     * Starts a new instance of the specified orchestrator function.
+     *
+     * If an orchestration instance with the specified ID already exists, the
+     * existing instance will be silently replaced by this new instance.
+     * @param orchestratorFunctionName The name of the orchestrator function to
+     *  start.
+     * @param options optional object to control the scheduled orchestrator (e.g provide input, instanceID)
+     * @returns The ID of the new orchestration instance.
+     */
+    startNew(orchestratorFunctionName: string, options?: StartNewOptions): Promise<string>;
+
+    /**
+     * Terminates a running orchestration instance.
+     * @param instanceId The ID of the orchestration instance to terminate.
+     * @param reason The reason for terminating the orchestration instance.
+     * @returns A promise that resolves when the terminate message is enqueued.
+     *
+     * Terminating an orchestration instance has no effect on any in-flight
+     * activity function executions or sub-orchestrations that were started
+     * by the current orchestration instance.
+     */
+    terminate(instanceId: string, reason: string): Promise<void>;
+
+    /**
+     * Creates an HTTP response which either contains a payload of management
+     * URLs for a non-completed instance or contains the payload containing
+     * the output of the completed orchestration.
+     *
+     * If the orchestration does not complete within the specified timeout,
+     * then the HTTP response will be identical to that of createCheckStatusResponse().
+     *
+     * @param request The HTTP request that triggered the current function.
+     * @param instanceId The unique ID of the instance to check.
+     * @param timeoutInMilliseconds Total allowed timeout for output from the
+     *  durable function. The default value is 10 seconds.
+     * @param retryIntervalInMilliseconds The timeout between checks for output
+     *  from the durable function. The default value is 1 second.
+     */
+    waitForCompletionOrCreateCheckStatusResponse(
+        request: HttpRequest,
+        instanceId: string,
+        timeoutInMilliseconds: number,
+        retryIntervalInMilliseconds: number
+    ): Promise<HttpResponse>;
+}
+
 /**
  * Options object provided as an optional second argument to the `client.startNew()` method
  */
diff --git a/src/types/entityTypes.ts b/src/types/entityTypes.ts
index d00369e..8806bbb 100644
--- a/src/types/entityTypes.ts
+++ b/src/types/entityTypes.ts
@@ -1,5 +1,4 @@
 import { FunctionOptions, FunctionTrigger, InvocationContext, LogHandler } from "@azure/functions";
-import { DurableEntityContext } from "../durableentitycontext";
 
 export type EntityHandler<T> = (context: EntityContext<T>) => void;
 
@@ -40,6 +39,85 @@ export declare class DummyEntityContext<T> extends InvocationContext implements
     df: DurableEntityContext<T>;
 }
 
+/**
+ * Provides functionality for application code implementing an entity operation.
+ * @param TState the JSON-serializable type of the Entity's state
+ */
+export interface DurableEntityContext<TState> {
+    /**
+     * Gets the name of the currently executing entity.
+     */
+    readonly entityName: string;
+    /**
+     * Gets the key of the currently executing entity.
+     */
+    readonly entityKey: string;
+    /**
+     * Gets the id of the currently executing entity.
+     */
+    readonly entityId: EntityId;
+    /**
+     * Gets the name of the operation that was called.
+     *
+     * An operation invocation on an entity includes an operation name, which
+     * states what operation to perform, and optionally an operation input.
+     */
+    readonly operationName: string | undefined;
+    /**
+     * Whether this entity is freshly constructed, i.e. did not exist prior to
+     * this operation being called.
+     */
+    readonly isNewlyConstructed: boolean;
+
+    /**
+     * Gets the current state of this entity, for reading and/or writing.
+     *
+     * @param initializer Provides an initial value to use for the state,
+     * instead of TState's default.
+     * @returns The current state of this entity, or undefined if none has been set yet.
+     */
+    getState(initializer?: () => TState): TState | undefined;
+
+    /**
+     * Sets the current state of this entity.
+     *
+     * @param state The state of the entity.
+     */
+    setState(state: TState): void;
+
+    /**
+     * Gets the input for this operation.
+     *
+     * An operation invocation on an entity includes an operation name, which
+     * states what operation to perform, and optionally an operation input.
+     *
+     * @returns The operation input, or undefined if none.
+     */
+    getInput<TInput = TState>(): TInput | undefined;
+
+    /**
+     * Returns the given result to the caller of this operation.
+     *
+     * @param result The result to return.
+     */
+    return<TResult = TState>(result: TResult): void;
+
+    /**
+     * Deletes this entity after this operation completes.
+     */
+    destructOnExit(): void;
+
+    /**
+     * Signals an entity to perform an operation, without waiting for a
+     * response. Any result or exception is ignored (fire and forget).
+     *
+     * @param entity The target entity.
+     * @param operationName The name of the operation.
+     * @param operationInput The operation input.
+     */
+    signalEntity(entity: EntityId, operationName: string, operationInput?: unknown): void;
+}
+
 /**
  * A unique identifier for an entity, consisting of entity class and entity key.
  */
diff --git a/src/types/orchestrationTypes.ts b/src/types/orchestrationTypes.ts
index ac07b70..4eaef71 100644
--- a/src/types/orchestrationTypes.ts
+++ b/src/types/orchestrationTypes.ts
@@ -1,6 +1,8 @@
 import { FunctionOptions, FunctionTrigger, InvocationContext, LogHandler } from "@azure/functions";
-import { TokenSource } from ".";
-import { DurableOrchestrationContext } from "../classes";
+import { Task, TimerTask, TokenSource } from ".";
+import { EntityId, HistoryEvent, RetryOptions } from "../classes";
+import { ReplaySchema } from "../replaySchema";
+import { TaskOrchestrationExecutor } from "../taskorchestrationexecutor";
 
 /**
  * Type of a Generator that can be registered as an orchestration
@@ -86,6 +88,241 @@ export interface CallHttpOptions {
     asynchronousPatternEnabled?: boolean;
 }
 
+/**
+ * Provides functionality for application code implementing an orchestration operation.
+ */
+export declare class DurableOrchestrationContext {
+    constructor(
+        state: HistoryEvent[],
+        instanceId: string,
+        currentUtcDateTime: Date,
+        isReplaying: boolean,
+        parentInstanceId: string | undefined,
+        longRunningTimerIntervalDuration: string | undefined,
+        maximumShortTimerDuration: string | undefined,
+        defaultHttpAsyncRequestSleepTimeMillseconds: number | undefined,
+        schemaVersion: ReplaySchema,
+        input: unknown,
+        taskOrchestratorExecutor: TaskOrchestrationExecutor
+    );
+
+    /**
+     * The ID of the current orchestration instance.
+     *
+     * The instance ID is generated and fixed when the orchestrator function is
+     * scheduled. It can be either auto-generated, in which case it is
+     * formatted as a GUID, or it can be user-specified with any format.
+     */
+    readonly instanceId: string;
+
+    /**
+     * The ID of the parent orchestration of the current sub-orchestration
+     * instance. The value will be available only in sub-orchestrations.
+     *
+     * The parent instance ID is generated and fixed when the parent
+     * orchestrator function is scheduled. It can be either auto-generated, in
+     * which case it is formatted as a GUID, or it can be user-specified with
+     * any format.
+     */
+    readonly parentInstanceId: string | undefined;
+
+    /**
+     * Gets a value indicating whether the orchestrator function is currently
+     * replaying itself.
+     *
+     * This property is useful when there is logic that needs to run only when
+     * the orchestrator function is _not_ replaying. For example, certain types
+     * of application logging may become too noisy when duplicated as part of
+     * orchestrator function replay. The orchestrator code could check to see
+     * whether the function is being replayed and then issue the log statements
+     * when this value is `false`.
+     */
+    isReplaying: boolean;
+
+    /**
+     * Gets the current date/time in a way that is safe for use by orchestrator
+     * functions.
+     *
+     * This date/time value is derived from the orchestration history. It
+     * always returns the same value at specific points in the orchestrator
+     * function code, making it deterministic and safe for replay.
+     */
+    currentUtcDateTime: Date;
+
+    /**
+     * Custom status for the orchestration
+     */
+    customStatus: unknown;
+
+    /**
+     * Entry point for methods to handle collections of
+     * pending actions represented by [[Task]] instances.
+     * For use in parallelization operations.
+     */
+    Task: {
+        /**
+         * Returns when _all_ the children Tasks have completed
+         * @param tasks the list of Tasks to wait on
+         * @returns a Task with the result of all of the awaited Tasks
+         */
+        all: (tasks: Task[]) => Task;
+        /**
+         * Returns when _any_ of the children Tasks have completed
+         * @param tasks the lists of Tasks to run
+         * @returns the first Task from tasks to complete
+         */
+        any: (tasks: Task[]) => Task;
+    };
+
+    /**
+     * Schedules an activity function named `name` for execution.
+     *
+     * @param name The name of the activity function to call.
+     * @param input The JSON-serializable input to pass to the activity
+     * function.
+     *
+     * @returns A Durable Task that completes when the called activity
+     * function completes or fails.
+     */
+    callActivity(name: string, input?: unknown): Task;
+
+    /**
+     * Schedules an activity function named `name` for execution with
+     * retry options.
+     *
+     * @param name The name of the activity function to call.
+     * @param retryOptions The retry options for the activity function.
+     * @param input The JSON-serializable input to pass to the activity
+     * function.
+     */
+    callActivityWithRetry(name: string, retryOptions: RetryOptions, input?: unknown): Task;
+
+    /**
+     * Calls an operation on an entity, passing an argument, and waits for it
+     * to complete.
+     *
+     * @param entityId The target entity.
+     * @param operationName The name of the operation.
+     * @param operationInput The input for the operation.
+     */
+    callEntity(entityId: EntityId, operationName: string, operationInput?: unknown): Task;
+
+    /**
+     * Send a signal operation to a Durable Entity, passing an argument, without
+     * waiting for a response. A fire-and-forget operation.
+     *
+     * @param entityId ID of the target entity.
+     * @param operationName The name of the operation.
+     * @param operationInput (optional) input for the operation.
+     */
+    signalEntity(entityId: EntityId, operationName: string, operationInput?: unknown): void;
+
+    /**
+     * Schedules an orchestration function named `name` for execution.
+     *
+     * @param name The name of the orchestrator function to call.
+     * @param input The JSON-serializable input to pass to the orchestrator
+     * function.
+     * @param instanceId A unique ID to use for the sub-orchestration instance.
+     * If `instanceId` is not specified, the extension will generate an id in
+     * the format `<calling orchestrator instance ID>:<#>`
+     */
+    callSubOrchestrator(name: string, input?: unknown, instanceId?: string): Task;
+
+    /**
+     * Schedules an orchestrator function named `name` for execution with retry
+     * options.
+     *
+     * @param name The name of the orchestrator function to call.
+     * @param retryOptions The retry options for the orchestrator function.
+     * @param input The JSON-serializable input to pass to the orchestrator
+     * function.
+     * @param instanceId A unique ID to use for the sub-orchestration instance.
+     */
+    callSubOrchestratorWithRetry(
+        name: string,
+        retryOptions: RetryOptions,
+        input?: unknown,
+        instanceId?: string
+    ): Task;
+
+    /**
+     * Schedules a durable HTTP call to the specified endpoint.
+     *
+     * @param options The HTTP options object
+     */
+    callHttp(options: CallHttpOptions): Task;
+
+    /**
+     * Restarts the orchestration by clearing its history.
+     *
+     * @param input The JSON-serializable data to re-initialize the instance with.
+     */
+    continueAsNew(input: unknown): void;
+
+    /**
+     * Creates a durable timer that expires at a specified time.
+     *
+     * All durable timers created using this method must either expire or be
+     * cancelled using `TimerTask.cancel()` before the orchestrator
+     * function completes. Otherwise, the underlying framework will keep the
+     * instance alive until the timer expires.
+     *
+     * @param fireAt The time at which the timer should expire.
+     * @returns A TimerTask that completes when the durable timer expires.
+     */
+    createTimer(fireAt: Date): TimerTask;
+
+    /**
+     * Gets the input of the current orchestrator function as a deserialized
+     * value.
+     *
+     * @param T return input as type `T`
+     */
+    getInput<T>(): T;
+
+    /**
+     * Creates a new GUID that is safe for replay within an orchestration or
+     * operation.
+     *
+     * The default implementation of this method creates a name-based UUID
+     * using the algorithm from RFC 4122 §4.3. The name input used to generate
+     * this value is a combination of the orchestration instance ID and an
+     * internally managed sequence number.
+     *
+     * @param input used to generate the unique GUID
+     */
+    newGuid(input: string): string;
+
+    /**
+     * Sets the JSON-serializable status of the current orchestrator function.
+     *
+     * The `customStatusObject` value is serialized to JSON and will be made
+     * available to the orchestration status query APIs. The serialized JSON
+     * value must not exceed 16 KB of UTF-16 encoded text.
+     *
+     * The serialized `customStatusObject` value will be made available to the
+     * aforementioned APIs after the next `yield` or `return` statement.
+     *
+     * @param customStatusObject The JSON-serializable value to use as the
+     * orchestrator function's custom status.
+     */
+    setCustomStatus(customStatusObject: unknown): void;
+
+    /**
+     * Waits asynchronously for an event to be raised with the name `name` and
+     * returns the event data.
+     *
+     * External clients can raise events to a waiting orchestration instance
+     * using `raiseEvent()`.
+     *
+     * @param name The name of the external event to wait for.
+     * @returns a Task that completes when an external event of
+     *  the specified name is received
+     */
+    waitForExternalEvent(name: string): Task;
+}
+
 /**
  * Represents the status of a durable orchestration instance.
  *


Test patch:
diff --git a/src/testingUtils.ts b/src/testingUtils.ts
index 88e1ff2..0a80247 100644
--- a/src/testingUtils.ts
+++ b/src/testingUtils.ts
@@ -8,8 +8,7 @@ import {
 } from "./classes";
 import { ReplaySchema } from "./replaySchema";
 import * as uuidv1 from "uuid/v1";
-import { DurableEntityContext } from "./durableentitycontext";
-import { EntityContext, OrchestrationContext } from "./types";
+import { DurableEntityContext, EntityContext, OrchestrationContext } from "./types";
 import * as types from "./types";
 
 export class DummyOrchestrationContext extends InvocationContext