{
  "version": 3,
  "sources": ["../../../../services/src/runtime/typescript/ServiceDebugging.ts", "../../../../services/src/runtime/typescript/ServiceChannel.ts", "../../../../services/src/runtime/typescript/assertNever.ts", "../../../../services/src/runtime/typescript/ServiceErrors.ts", "../../../../services/src/runtime/typescript/internal.ts", "../../../../services/src/runtime/typescript/streams/private.ts", "../../../../services/src/runtime/typescript/ServiceManager.ts", "../../../../services/src/runtime/typescript/channels/LocalChannel.ts", "../../../../services/src/runtime/typescript/channels/PostMessageChannel.ts", "../../../../services/src/runtime/typescript/private.ts", "../../../../services/src/runtime/typescript/streams/ServiceEventEmitter.ts"],
  "sourcesContent": ["import { type Logger, getLogger } from \"@framerjs/shared\"\nimport type { ServiceManager } from \"./ServiceManager.ts\"\n\nexport namespace ServiceDebugging {\n\t/** Services come with a default fallback logger. Please don\u2019t use it; instead, re-assign it so logs go into a proper channel. */\n\t// biome-ignore lint/style/useConst: Re-assigned by the runtime (e.g., in src/app/vekter/src/environment/index.ts)\n\texport let log: Logger = getLogger(\"\uD83D\uDCA9 fallback-logger-please-reassign:services\")\n}\n\n/**\n * @private Infrastructure that should never be used outside the Framer Services package implementation.\n */\nexport namespace ServiceDebugging {\n\t/** @private Only for tests. Enables or disables testing mode. */\n\t// biome-ignore lint/style/useConst: <explanation>\n\texport let _isTesting = false\n\tlet _testingServiceManager: ServiceManager | undefined\n\n\t/** @private Only for tests. Temporarily changes the value of ServiceManager.shared(). */\n\texport async function _testWithShared<T>(manager: ServiceManager, fn: () => Promise<T>) {\n\t\tif (!ServiceDebugging._isTesting) {\n\t\t\tthrow new Error(\"ServiceManager.isTesting must be true to use testWithShared()\")\n\t\t}\n\t\tif (_testingServiceManager) throw new Error(\"ServiceManager.testWithShared() may not be nested\")\n\n\t\ttry {\n\t\t\t_testingServiceManager = manager\n\t\t\treturn await fn()\n\t\t\t// eslint-disable-next-line no-useless-catch\n\t\t} finally {\n\t\t\t_testingServiceManager = undefined\n\t\t}\n\t}\n\n\t/** @private For ServiceManager */\n\texport function _sharedServiceManagerIfTesting(): ServiceManager | undefined {\n\t\tif (ServiceDebugging._isTesting) {\n\t\t\tif (!_testingServiceManager) {\n\t\t\t\tthrow new Error(\"ServiceManager.shared() may not be used while testing. Use testWithShared() for explicitness.\")\n\t\t\t} else {\n\t\t\t\treturn _testingServiceManager\n\t\t\t}\n\t\t}\n\n\t\t// Just use the standard shared logic if not testing\n\t\treturn undefined\n\t}\n}\n", "// \u267B\uFE0F\n// IMPORTANT: Take care to apply changes to all supported languages\n// when modifying code or documentation in the services runtime.\n\n/**\n * Channels implement the cross-process transport of the service messages that underlie service communication.\n */\nexport interface ServiceChannel {\n\t/** Optionally indicates whether the channel can be used at all. Must be accurate for the lifetime of the channel. */\n\treadonly disabled?: boolean\n\t/** Sends a message to the other end of the channel. */\n\tpostMessage(message: ServiceChannel.Message): void\n\t/** Adds a listener for any message arriving at this end of the channel. */\n\taddMessageListener(_: (message: ServiceChannel.Message) => void): void\n\t/** Removes a listener. */\n\tremoveMessageListener(_: (message: ServiceChannel.Message) => void): void\n}\n\nexport namespace ServiceChannel {\n\t/** Marks oneway method requests. */\n\texport const onewayRequestId = \"oneway\"\n\t/** Marks oneway stream value responses. */\n\texport const onewayStreamResponseIdPrefix = \"#oneway:\"\n\n\t/**\n\t * Implementations only need to be able to (de)serialize the `Message` type. The `body` of messages is considered\n\t * opaque in that the channel should not need to be (or even able to be) aware of the type of the data.\n\t */\n\texport interface Message {\n\t\ttype: MessageType\n\t\tid: string | typeof onewayRequestId\n\t\tserviceId: string // FIXME: rename to service?\n\t\tmethod: string\n\t\tstream?: string\n\t\tbody?: MessageBody\n\t}\n\n\texport enum MessageType {\n\t\tRequest = \"request\",\n\t\tResponse = \"response\",\n\t\tError = \"error\",\n\t}\n\n\texport function isMessage(obj: any): obj is Message {\n\t\tif (typeof obj !== \"object\") return false\n\t\treturn (\n\t\t\tobj.type === ServiceChannel.MessageType.Request ||\n\t\t\tobj.type === ServiceChannel.MessageType.Response ||\n\t\t\tobj.type === ServiceChannel.MessageType.Error\n\t\t)\n\t}\n\n\t/** Message bodies are currently only JSON, but could be a serialized protobuf format. */\n\ttype Primitive = string | number | boolean\n\texport interface MessageBody {\n\t\treadonly [key: string]:\n\t\t\t| Uint8Array\n\t\t\t| Primitive\n\t\t\t| readonly Primitive[]\n\t\t\t| MessageBody\n\t\t\t| readonly MessageBody[]\n\t\t\t| undefined\n\t\t\t| null\n\t}\n}\n", "export function assertNever(x: never, error?: unknown): never {\n\tif (error instanceof Error) throw error\n\tif (error !== undefined) throw new Error(String(error))\n\tthrow new Error(\"Unexpected object: \" + x)\n}\n", "import type { ServiceChannel } from \"./ServiceChannel.ts\"\nimport { ServiceDebugging } from \"./ServiceDebugging.ts\"\nimport { assertNever } from \"./assertNever.ts\"\n\n// \u267B\uFE0F\n// IMPORTANT: Take care to apply changes to all supported languages\n// when modifying code or documentation in the services runtime.\n\n/**\n * Service runtime or service implementation errors.\n */\nexport class ServiceError extends Error {\n\toverride readonly name: string = \"ServiceError.UnknownError\"\n\tcode: number = 0\n\tstatus: number = 0\n\tskipSentry: boolean = false\n}\n\nexport namespace ServiceError {\n\texport const enum Code {\n\t\tserviceNotFound = 404,\n\t\tserviceNotCompatible = 426,\n\t\tserviceGone = 410,\n\t\timplementation = 500,\n\t\ttimedOut = 504,\n\t\tbadRequest = 400,\n\t\tbadResponse = 422,\n\t}\n\n\texport class ServiceNotFound extends ServiceError {\n\t\t// Service was probably not registered, or using the wrong channel\n\t\toverride readonly code = Code.serviceNotFound\n\t\toverride readonly name = \"ServiceError.ServiceNotFound\"\n\t}\n\n\texport class ServiceNotCompatible extends ServiceError {\n\t\t// Service interface is different on either end of the channel\n\t\toverride readonly code = Code.serviceNotCompatible\n\t\toverride readonly name = \"ServiceError.ServiceNotCompatible\"\n\t}\n\n\texport class ServiceGone extends ServiceError {\n\t\t// Service was unregistered\n\t\toverride readonly code = Code.serviceGone\n\t\toverride readonly name = \"ServiceError.ServiceGone\"\n\n\t\t// As we don\u2019t (no longer) use services over channels that might\n\t\t// reconnect, this error will happen during an unclean shutdown, and we\n\t\t// can ignore it\n\t\toverride skipSentry = true\n\t}\n\n\texport class Implementation extends ServiceError {\n\t\toverride readonly code = Code.implementation\n\t\toverride readonly name = \"ServiceError.Implementation\"\n\t}\n\n\texport class TimedOut extends ServiceError {\n\t\toverride readonly code = Code.timedOut\n\t\toverride readonly name = \"ServiceError.TimedOut\"\n\t}\n\n\texport class BadRequest extends ServiceError {\n\t\toverride readonly code: Code = Code.badRequest\n\t\toverride readonly name: string = \"ServiceError.BadRequest\"\n\t}\n\n\texport class BadResponse extends ServiceError {\n\t\toverride readonly code: Code = Code.badResponse\n\t\toverride readonly name: string = \"ServiceError.BadResponse\"\n\n\t\treadonly response: ServiceChannel.Message | undefined\n\n\t\tconstructor(message?: string, response?: ServiceChannel.Message | undefined) {\n\t\t\tsuper(message)\n\n\t\t\tthis.response = response\n\t\t}\n\t}\n\n\texport function reconstructErrorResponse(error: ServiceChannel.MessageBody | undefined): ServiceError {\n\t\tif (!error) return new BadResponse()\n\n\t\tlet message: string | undefined\n\t\tif (hasMessage(error)) {\n\t\t\tmessage = error.message\n\t\t}\n\n\t\tconst reconstructedError = errorFromCode(error.code, message)\n\t\tif (hasCode(error)) {\n\t\t\treconstructedError.code = error.code\n\t\t}\n\t\tif (hasStack(error)) {\n\t\t\treconstructedError.stack = error.stack\n\t\t}\n\t\tif (hasSkipSentry(error)) {\n\t\t\treconstructedError.skipSentry = error.skipSentry\n\t\t}\n\t\tif (hasStatus(error)) {\n\t\t\treconstructedError.status = error.status\n\t\t}\n\n\t\treturn reconstructedError\n\t}\n\n\tfunction errorFromCode(code: unknown, message?: string): ServiceError {\n\t\ttry {\n\t\t\t// Cast to ServiceError.Code to get exhaustiveness checking, but could be anything\n\t\t\tconst maybeCode = code as ServiceError.Code\n\t\t\tswitch (maybeCode) {\n\t\t\t\tcase ServiceError.Code.serviceNotFound:\n\t\t\t\t\treturn new ServiceNotFound(message)\n\t\t\t\tcase ServiceError.Code.serviceNotCompatible:\n\t\t\t\t\treturn new ServiceNotCompatible(message)\n\t\t\t\tcase ServiceError.Code.serviceGone:\n\t\t\t\t\treturn new ServiceGone(message)\n\t\t\t\tcase ServiceError.Code.implementation:\n\t\t\t\t\treturn new Implementation(message)\n\t\t\t\tcase ServiceError.Code.timedOut:\n\t\t\t\t\treturn new TimedOut(message)\n\t\t\t\tcase ServiceError.Code.badRequest:\n\t\t\t\t\treturn new BadRequest(message)\n\t\t\t\tcase ServiceError.Code.badResponse:\n\t\t\t\t\treturn new BadResponse(message)\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(maybeCode)\n\t\t\t}\n\t\t} catch {\n\t\t\t// Something other than a service specific error code\n\t\t\treturn new ServiceError(message)\n\t\t}\n\t}\n\n\texport function toMessageBody(error: unknown): {\n\t\tcode?: number\n\t\tmessage?: string\n\t\tstack?: string\n\t\tskipSentry?: boolean\n\t\tstatus?: number\n\t} {\n\t\tif (error instanceof ServiceError) {\n\t\t\treturn { code: error.code, message: error.message, stack: error.stack, skipSentry: error.skipSentry }\n\t\t}\n\n\t\tlet message: string | undefined\n\t\tlet stack: string | undefined\n\t\tlet skipSentry: boolean | undefined\n\t\tlet code: number | undefined\n\t\tlet status: number | undefined\n\t\tif (typeof error === \"string\") {\n\t\t\tmessage = error\n\t\t} else if (hasMessage(error)) {\n\t\t\tmessage = error.message\n\t\t}\n\t\tif (hasStack(error)) {\n\t\t\tstack = error.stack\n\t\t}\n\t\tif (hasSkipSentry(error)) {\n\t\t\tskipSentry = error.skipSentry\n\t\t}\n\t\tif (hasCode(error)) {\n\t\t\tcode = error.code\n\t\t}\n\t\tif (hasStatus(error)) {\n\t\t\tstatus = error.status\n\t\t}\n\n\t\treturn { code, message, stack, skipSentry, status }\n\t}\n}\n\nfunction hasMessage<T>(error: T): error is T & { message: string } {\n\treturn typeof error === \"object\" && error && \"message\" in error && typeof error.message === \"string\"\n}\n\nfunction hasStack<T>(error: T): error is T & { stack: string } {\n\treturn typeof error === \"object\" && error && \"stack\" in error && typeof error.stack === \"string\"\n}\n\nfunction hasSkipSentry<T>(error: T): error is T & { skipSentry: boolean } {\n\treturn typeof error === \"object\" && error && \"skipSentry\" in error && typeof error.skipSentry === \"boolean\"\n}\n\nfunction hasCode<T>(error: T): error is T & { code: number } {\n\treturn typeof error === \"object\" && error && \"code\" in error && typeof error.code === \"number\"\n}\n\nfunction hasStatus<T>(error: T): error is T & { status: number } {\n\treturn typeof error === \"object\" && error && \"status\" in error && typeof error.status === \"number\"\n}\n\nexport function handleServiceError(error: unknown): undefined {\n\tServiceDebugging.log.error(error)\n}\n", "/**\n * @private Infrastructure that should never be used outside the Framer Services package implementation.\n */\nexport namespace ServiceRuntimeInternal {\n\t// Capture Math.random in case some other code swaps it out\n\tconst randomNumber = Math.random\n\n\t/** Returns a good enough unique string to identify request/response pairs across services */\n\texport function generateUniqueId(): string {\n\t\treturn `${randomNumber()}`\n\t}\n\n\t/** Promise with resolve() and reject() functions that can be called given just a reference to the promise. */\n\texport type ResolvablePromise<T> = Promise<T> & { resolve: (result: T) => void; reject: (error: any) => void }\n\n\texport function newResolvablePromise<T>(): ResolvablePromise<T> {\n\t\tlet promiseResolve: any\n\t\tlet promiseReject: any\n\t\tconst promise: any = new Promise((resolve, reject) => {\n\t\t\tpromiseResolve = resolve\n\t\t\tpromiseReject = reject\n\t\t})\n\t\tpromise.resolve = promiseResolve\n\t\tpromise.reject = promiseReject\n\t\treturn promise\n\t}\n}\n", "import type {\n\tServiceMessageHelper,\n\tServiceStream,\n\tServiceStreamCallback,\n\tServiceStreamOptions,\n} from \"../ServiceDefinition.ts\"\nimport { ServiceError } from \"../ServiceErrors.ts\"\nimport { ServiceRuntimeInternal } from \"../internal.ts\"\n\n/**\n * @private Infrastructure that should never be used outside the Framer Services package implementation.\n */\nexport namespace ServiceStreamsPrivate {\n\texport function isServiceStreamOptions(body: unknown): body is ServiceStreamOptions {\n\t\tif (!body) {\n\t\t\treturn false\n\t\t}\n\n\t\tswitch ((body as ServiceStreamOptions).replay) {\n\t\t\tcase \"latest\":\n\t\t\tcase undefined:\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\treturn false\n\t\t}\n\n\t\treturn true\n\t}\n\n\texport class StreamReader<T extends object> implements ServiceStream<T> {\n\t\tprivate oneway: boolean\n\t\tprivate onewayCallback: ((result: unknown) => void) | undefined\n\n\t\tprivate iterator: AsyncIterator<T> | undefined\n\n\t\tprivate cancelled = false\n\t\t// To support cancellation while waiting for a next reply, we also race to wait on a promise\n\t\t// that can be resolved or rejected via these two methods.\n\t\tprivate resolveCancelPromise: (() => void) | undefined\n\t\tprivate rejectCancelPromise: ((reason: any) => void) | undefined\n\n\t\tconstructor(\n\t\t\tprivate readonly method: string,\n\t\t\tprivate readonly options: ServiceStreamOptions | undefined,\n\t\t\tprivate readonly helper: ServiceMessageHelper,\n\t\t) {\n\t\t\tthis.oneway = options?.oneway ?? false\n\t\t}\n\n\t\t[Symbol.asyncIterator](): AsyncIterator<T> {\n\t\t\tif (this.oneway) {\n\t\t\t\tthrow new ServiceError.BadRequest(\n\t\t\t\t\t\"Cannot read a oneway stream through an AsyncIterator. Use read() with a void callback instead.\",\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.iterator = this.newIterator()\n\t\t\treturn this.iterator\n\t\t}\n\n\t\tasync read(callback: ServiceStreamCallback<T>): Promise<void> {\n\t\t\tthis.iterator = this.newIterator()\n\t\t\tif (this.oneway) {\n\t\t\t\tthis.onewayCallback = (result: unknown): void => {\n\t\t\t\t\tif (!isIteratorResult<T>(result)) {\n\t\t\t\t\t\tthrow new ServiceError.BadResponse(\"StreamReader.onewayCallback received an invalid iterator result\")\n\t\t\t\t\t}\n\t\t\t\t\tif (result.done) return\n\t\t\t\t\tconst promiseOrVoid = callback(result.value)\n\t\t\t\t\tif (promiseOrVoid) {\n\t\t\t\t\t\tthrow new ServiceError.BadRequest(\"ServiceStream callbacks cannot be async if oneway = true.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line no-constant-condition\n\t\t\twhile (true) {\n\t\t\t\tconst result = await this.iterator.next()\n\t\t\t\tif (result.done) return\n\t\t\t\tawait callback(result.value)\n\t\t\t}\n\t\t}\n\n\t\tasync cancel(): Promise<void> {\n\t\t\tthis.cancelled = true\n\t\t\tawait this.iterator?.return?.()\n\t\t}\n\n\t\tprivate newIterator(): AsyncIterator<T> {\n\t\t\tif (this.iterator) {\n\t\t\t\tthrow new ServiceError.BadRequest(\n\t\t\t\t\t\"ServiceStream instances can only be read once. If multiple AsyncIterators or read() calls are required, create a new stream for each by calling the associated service method. To broadcast events with an observer pattern, consider using a client-specific EventEmitter or similar.\",\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// The stream id will let the Router on the other end remember the corresponding iterator\n\t\t\tconst id = ServiceRuntimeInternal.generateUniqueId()\n\n\t\t\t// Contrary to what the types say, value = undefined is valid when done = true\n\t\t\tconst doneResult: IteratorResult<T> = { done: true, value: undefined as unknown as T }\n\n\t\t\t// Validate and handle next responses\n\t\t\tconst validateNextResult = async (result: unknown) => {\n\t\t\t\tif (!isIteratorResult<T>(result)) {\n\t\t\t\t\tthrow new ServiceError.BadResponse(\"StreamReader.next received an invalid iterator result for next()\")\n\t\t\t\t}\n\t\t\t\treturn result\n\t\t\t}\n\n\t\t\tconst requestNextAndVerify = async (): Promise<IteratorResult<T>> => {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await this.helper(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmethod: this.method,\n\t\t\t\t\t\t\targument: this.options,\n\t\t\t\t\t\t\tstream: { id, method: \"next\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\t// One way streams don't iterate via next requests, instead they call this\n\t\t\t\t\t\t// callback until finally they return a done result.\n\t\t\t\t\t\tthis.onewayCallback,\n\t\t\t\t\t)\n\t\t\t\t\treturn await validateNextResult(result)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.cancelled = true\n\t\t\t\t\tthrow error\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Setup a new promise that can return or throw to cancel a next request. Note we\n\t\t\t// explicily create a new promise, or we risk creating a long chain of promise reaction\n\t\t\t// objects (a v8 internal object).\n\t\t\tconst cancelNextRequest = async (): Promise<IteratorResult<T>> => {\n\t\t\t\tif (this.cancelled) return doneResult\n\t\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\t\tthis.resolveCancelPromise = resolve\n\t\t\t\t\tthis.rejectCancelPromise = reject\n\t\t\t\t})\n\t\t\t\treturn doneResult\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tnext: async (): Promise<IteratorResult<T>> => {\n\t\t\t\t\tif (this.cancelled) return doneResult\n\t\t\t\t\t// We return the race between the next remote method call or a call to cancel.\n\t\t\t\t\treturn Promise.race([requestNextAndVerify(), cancelNextRequest()])\n\t\t\t\t},\n\t\t\t\treturn: async (): Promise<IteratorResult<T>> => {\n\t\t\t\t\t// We want `next` to resolve with doneResult, and `return` to be sent to the service side\n\t\t\t\t\tthis.cancelled = true\n\t\t\t\t\tthis.resolveCancelPromise?.()\n\t\t\t\t\tvoid this.helper({\n\t\t\t\t\t\tmethod: this.method,\n\t\t\t\t\t\tstream: { id, method: \"return\" },\n\t\t\t\t\t})\n\n\t\t\t\t\t// The caller of `return` also gets a resolved doneResult\n\t\t\t\t\treturn doneResult\n\t\t\t\t},\n\t\t\t\tthrow: async (error?: any): Promise<IteratorResult<T>> => {\n\t\t\t\t\t// We want `next` to reject with `error`, and `return` to be sent to the service side\n\t\t\t\t\tthis.cancelled = true\n\t\t\t\t\tthis.rejectCancelPromise?.(error)\n\t\t\t\t\tvoid this.helper({\n\t\t\t\t\t\tmethod: this.method,\n\t\t\t\t\t\tstream: { id, method: \"return\" },\n\t\t\t\t\t})\n\n\t\t\t\t\t// The caller of `throw` gets a resolved doneResult instead\n\t\t\t\t\treturn doneResult\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction isIteratorResult<T>(result: any): result is IteratorResult<T> {\n\tif (!result) return false\n\treturn result.done === true || (result.done === false && result.value !== undefined)\n}\n\n/** Callback for stream values, optionally preventing standard behavior by returning { ignore: true }. */\nexport type ServiceStreamValueInterceptor<T> = (value: T) => { ignore: boolean }\n", "// \u267B\uFE0F\n// IMPORTANT: Take care to apply changes to all supported languages\n// when modifying code or documentation in the services runtime.\n\nimport type { Logger } from \"@framerjs/shared\"\nimport { ServiceChannel } from \"./ServiceChannel.ts\"\nimport { ServiceDebugging } from \"./ServiceDebugging.ts\"\nimport type { Service, ServiceMethodRequest, ServiceStream } from \"./ServiceDefinition.ts\"\nimport { ServiceError } from \"./ServiceErrors.ts\"\nimport { assertNever } from \"./assertNever.ts\"\nimport { ServiceRuntimeInternal } from \"./internal.ts\"\nimport { ServiceStreamsPrivate } from \"./streams/private.ts\"\n\n/**\n * Manages a cluster of channels and services and sets up service communication. Use the auto-generated Service objects\n * to register implementations and get proxies to cross-process services. Most clients will set up a single shared object\n * with multiple channels.\n */\nexport class ServiceManager {\n\tconstructor(private readonly log?: Logger) {}\n\n\t/**\n\t * Creates a new proxy for a given service. Since the presence of the service isn't checked, errors may occur when\n\t * actually calling methods on the proxy.\n\t *\n\t * @param service The auto-generated definition object for the wanted service\n\t * @param channel Where the service is assumed to live. Calling this method implicitly registers the channel.\n\t */\n\texpectWithoutDiscovery = <T>(service: Service<T>, channel: ServiceChannel): T => {\n\t\treturn this.addRouter(channel).expectWithoutDiscovery(service)\n\t}\n\n\t/**\n\t * Waits for the presence of the service, with a configurable timeout. Returns a proxy on success, or rejects with\n\t * a service error (e.g. the request timed out, service wasn't).\n\t *\n\t * const service = await SomeService.on(someChannel).discover({ timeout: 1000 })\n\t * await service.someMethod()\n\t *\n\t * @param service The auto-generated definition object for the wanted service\n\t * @param channel Where the service is assumed to live. Calling this method implicitly registers the channel.\n\t * @param options.timeout Number of milliseconds to wait for the service's presence. Default = 30000\n\t */\n\tdiscover = async <T>(\n\t\tservice: Service<T>,\n\t\tchannel: ServiceChannel,\n\t\toptions: { timeout?: number } = {},\n\t): Promise<T> => {\n\t\treturn this.addRouter(channel).discover(service, options)\n\t}\n\n\t/**\n\t * Adds an implementation for a specific service, exposing it on `channel`.\n\t * Implicitly registers the channel. Returns an unregister function.\n\t */\n\tregister<T>(implementation: ImplementationOptions<T>): () => void\n\n\t/**\n\t * Adds a channel to start using it for service discovery. Returns an unregister function.\n\t */\n\tregister(channel: ChannelOptions): () => void\n\n\tregister<T>(what: ChannelOptions | ImplementationOptions<T>): () => void {\n\t\tfunction isImplementation(obj: ChannelOptions | ImplementationOptions<T>): obj is ImplementationOptions<T> {\n\t\t\treturn (\n\t\t\t\t\"service\" in obj && \"implementation\" in obj && obj.service !== undefined && obj.implementation !== undefined\n\t\t\t)\n\t\t}\n\n\t\tif (isImplementation(what)) {\n\t\t\tthis.addRouter(what.channel).registerImplementation(what.implementation, what.service)\n\t\t\treturn () => void this.unregister(what.implementation)\n\t\t} else {\n\t\t\tthis.addRouter(what.channel)\n\t\t\treturn () => void this.unregister(what.channel)\n\t\t}\n\t}\n\n\t/** Removes a registered implementation or channel. */\n\tunregister = async (what: unknown): Promise<void> => {\n\t\tconst routersForChannel: Router[] = []\n\t\tfor (const router of this.routers) {\n\t\t\tif (router.channel === what) {\n\t\t\t\troutersForChannel.push(router)\n\t\t\t}\n\t\t}\n\n\t\tif (routersForChannel.length > 0) {\n\t\t\t// Channel and its service implementations\n\t\t\tfor (const router of routersForChannel) {\n\t\t\t\tawait router.unregisterAllImplementations()\n\t\t\t\tthis.routers.delete(router)\n\t\t\t\trouter.destroy()\n\t\t\t}\n\t\t} else {\n\t\t\t// Service implementation, or random value that will be ignored\n\t\t\tfor (const router of this.routers) {\n\t\t\t\tawait router.unregisterImplementation(what)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate readonly routers = new Set<Router>()\n\n\tprivate addRouter = (channel: ServiceChannel): Router => {\n\t\tfor (const existing of this.routers) {\n\t\t\tif (existing.channel === channel) {\n\t\t\t\treturn existing\n\t\t\t}\n\t\t}\n\n\t\tconst router = new Router(channel, this.log)\n\t\tthis.routers.add(router)\n\t\treturn router\n\t}\n\n\t/** @private Only for tests. */\n\ttestable = {\n\t\tonlyRouter: (): Router => {\n\t\t\tif (this.routers.size !== 1) {\n\t\t\t\tthrow new Error(`onlyRouter called on a ServiceManager with ${this.routers.size} routers, expected 1`)\n\t\t\t}\n\t\t\treturn this.routers.values().next().value as Router\n\t\t},\n\t}\n}\n\nexport namespace ServiceManager {\n\tlet sharedServiceManager: ServiceManager\n\n\t/**\n\t * Shared service manager for TypeScript clients that only have one area of responsibility within the runtime,\n\t * exposed as the generated `SomeService.on(channel)` convenience API. If your current script runtime only has\n\t * a single domain of responsibility (e.g. Vekter representing a single document), use the convenience instead\n\t * of constructing your own service managers.\n\t */\n\texport function shared(): ServiceManager {\n\t\tsharedServiceManager = sharedServiceManager ?? new ServiceManager()\n\t\treturn ServiceDebugging._sharedServiceManagerIfTesting() ?? sharedServiceManager\n\t}\n}\n\ntype ChannelOptions = {\n\tchannel: ServiceChannel\n}\n\ntype ImplementationOptions<T> = {\n\tservice: Service<T>\n\tchannel: ServiceChannel\n\timplementation: T\n}\n\nclass Router {\n\tconstructor(\n\t\tpublic readonly channel: ServiceChannel,\n\t\tprivate readonly customLogger?: Logger,\n\t) {\n\t\tchannel.addMessageListener(this.onMessage)\n\t}\n\n\tprivate get log() {\n\t\treturn this.customLogger ?? ServiceDebugging.log\n\t}\n\n\tdestroy() {\n\t\tthis.channel.removeMessageListener(this.onMessage)\n\t}\n\n\tprivate onMessage = (message: ServiceChannel.Message): void => {\n\t\ttry {\n\t\t\t// For now, just assume we're in a wonderful world where a type check implies a complete and valid message\n\t\t\tif (message.type === ServiceChannel.MessageType.Request) {\n\t\t\t\tif (message.id === ServiceChannel.onewayRequestId) {\n\t\t\t\t\tvoid this.onOnewayRequest(message)\n\t\t\t\t} else {\n\t\t\t\t\tvoid this.onRequest(message)\n\t\t\t\t}\n\t\t\t} else if (message.type === ServiceChannel.MessageType.Response) {\n\t\t\t\tif (message.method === Discovery.method) {\n\t\t\t\t\tthis.onDiscoveryResponse(message)\n\t\t\t\t} else {\n\t\t\t\t\tthis.onResponse(message)\n\t\t\t\t}\n\t\t\t} else if (message.type === ServiceChannel.MessageType.Error) {\n\t\t\t\tvoid this.onErrorResponse(message)\n\t\t\t} else {\n\t\t\t\tassertNever(message.type, new Error(`Unknown message: ${JSON.stringify(message)}`))\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.log.reportError(error, { message })\n\t\t}\n\t}\n\n\t// Discovery\n\n\tprivate latestDiscoveryInfo?: Discovery.Info\n\tprivate waitingDiscoveryMap: {\n\t\t[serviceId in string]?: ServiceRuntimeInternal.ResolvablePromise<void>[]\n\t} = {}\n\n\tprivate async waitForDiscoveryInfo(maxWaitTime: number, maxRetries: number = 0): Promise<Discovery.Info> {\n\t\t// No need to discover if we already have info. The other end of the channel makes sure that any updates get\n\t\t// actively pushed using broadcastDiscoveryInfo (e.g. when a service registers)\n\t\tif (this.latestDiscoveryInfo) {\n\t\t\treturn this.latestDiscoveryInfo\n\t\t}\n\n\t\tconst requestTimeout = maxWaitTime / (maxRetries + 1)\n\n\t\t// Explicitly request discovery info\n\t\tlet retries = 0\n\t\twhile (retries <= maxRetries) {\n\t\t\ttry {\n\t\t\t\tawait this.postRequest(Discovery.serviceId, { method: Discovery.method }, requestTimeout)\n\t\t\t\tbreak\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof ServiceError.TimedOut)) throw error\n\n\t\t\t\tif (!this.isWaitingForDiscovery()) {\n\t\t\t\t\t// if discovery has happened since we started waiting we don't need to retry\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tretries++\n\t\t\t}\n\t\t}\n\n\t\tif (!this.latestDiscoveryInfo) {\n\t\t\tthrow new ServiceError.ServiceNotFound()\n\t\t}\n\n\t\treturn this.latestDiscoveryInfo\n\t}\n\n\tprivate isWaitingForDiscovery() {\n\t\treturn Object.values(this.waitingDiscoveryMap).some(p => p && p.length > 0)\n\t}\n\n\tprivate async waitForDiscoveredService<T>(service: Service<T>, timeout: number): Promise<void> {\n\t\t// Will be resolved when any discovery response contains the expected service, but waits indefinitely otherwise\n\t\tconst promise = ServiceRuntimeInternal.newResolvablePromise<void>()\n\t\tconst promises = this.waitingDiscoveryMap[service.id] || []\n\t\tconst isDiscovering = this.isWaitingForDiscovery()\n\t\tthis.waitingDiscoveryMap[service.id] = promises\n\t\tpromises.push(promise)\n\n\t\t// Make sure there's at least one attempt to get discovery info, but ignore its success/failure\n\t\tif (!isDiscovering) {\n\t\t\tthis.waitForDiscoveryInfo(timeout, 2).catch(() => {})\n\t\t}\n\t\tthis.reflectDiscoveredServices()\n\n\t\treturn promise\n\t}\n\n\tprivate reflectDiscoveredServices = () => {\n\t\t// Only resolve requests for services that were actually discovered. New ones may appear later.\n\t\tlet discoveredServiceIds = this.latestDiscoveryInfo ? Object.keys(this.latestDiscoveryInfo.services) : []\n\n\t\t// For disabled channels we'd be waiting forever for no reason, so reject all requests\n\t\tlet discoveryError: Error | undefined\n\t\tif (this.channel.disabled) {\n\t\t\tdiscoveredServiceIds = Object.keys(this.waitingDiscoveryMap)\n\t\t\tdiscoveryError = new ServiceError.ServiceNotFound()\n\t\t}\n\n\t\tfor (const serviceId of discoveredServiceIds) {\n\t\t\tconst promises = this.waitingDiscoveryMap[serviceId]\n\t\t\tif (promises) {\n\t\t\t\tthis.waitingDiscoveryMap[serviceId] = []\n\t\t\t\tpromises.forEach(promise => (discoveryError ? promise.reject(discoveryError) : promise.resolve()))\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate onDiscoveryResponse = (response: ServiceChannel.Message) => {\n\t\tif (Discovery.isValidInfo(response.body)) {\n\t\t\tthis.latestDiscoveryInfo = response.body\n\t\t\tthis.reflectDiscoveredServices()\n\t\t\tthis.log.trace(\"\u2198\uFE0F Discovered services\", response.body)\n\t\t} else {\n\t\t\tthrow new ServiceError.BadResponse(\"Invalid discovery response\", response)\n\t\t}\n\n\t\t// Also do standard response handling if it's an explicit discovery request\n\t\tif (response.id !== Discovery.broadcastMessageId) {\n\t\t\tthis.onResponse(response)\n\t\t}\n\t}\n\n\tprivate broadcastDiscoveryInfo = (requestId?: string) => {\n\t\tconst services: { [key: string]: Discovery.ServiceInfo } = {}\n\t\tfor (const [key, implementedService] of Object.entries(this.implementedServices)) {\n\t\t\tconst service = implementedService.service\n\t\t\tservices[key] = { fingerprint: service.fingerprint }\n\t\t}\n\n\t\tconst discoveryInfo: Discovery.Info = { services }\n\n\t\ttry {\n\t\t\tthis.channel.postMessage({\n\t\t\t\ttype: ServiceChannel.MessageType.Response,\n\t\t\t\tid: requestId || Discovery.broadcastMessageId,\n\t\t\t\tserviceId: Discovery.serviceId,\n\t\t\t\tmethod: Discovery.method,\n\t\t\t\tbody: discoveryInfo,\n\t\t\t})\n\t\t} catch {\n\t\t\t// postMessage can fail (e.g. when generating a \"dehydrated\" version of the host page). Since this broadcast happens automatically and not as part of explicitly calling a service method, suppress errors here. If discovery fails, the actual services will fail as well.\n\t\t}\n\t}\n\n\t// Outgoing messages\n\n\tprivate onewayPromise = Promise.resolve(undefined)\n\n\texpectWithoutDiscovery = <T>(service: Service<T>): T => {\n\t\tthis.log.trace(\"\u260E\uFE0F expectWithoutDiscovery\", service.id)\n\n\t\treturn service.newOutgoingWrapper(async (request, onStreamValue) => {\n\t\t\tif (request.oneway) {\n\t\t\t\tthis.postOnewayRequest(service.id, request)\n\n\t\t\t\t// Note: this promise is ignored by the wrapper and service interface\n\t\t\t\treturn this.onewayPromise\n\t\t\t}\n\n\t\t\t// Discover services if needed\n\t\t\tawait this.waitForDiscoveryInfo(1000)\n\n\t\t\tthis.throwErrorIfBadService(service)\n\t\t\treturn this.postRequest(service.id, request, undefined, onStreamValue)\n\t\t})\n\t}\n\n\tdiscover = async <T>(service: Service<T>, { timeout = 30000 }: { timeout?: number } = {}): Promise<T> => {\n\t\tthis.log.trace(\"\u260E\uFE0F discover\", service.id)\n\n\t\tconst promises = [this.waitForDiscoveredService(service, timeout)]\n\t\tif (timeout !== Infinity) {\n\t\t\t// Timeout if it doesn't appear fast enough\n\t\t\tpromises.push(\n\t\t\t\tdelay(timeout).then(() => {\n\t\t\t\t\t// Distinguish between timeout waiting for discovery and waiting for a service to appear\n\t\t\t\t\tthrow this.latestDiscoveryInfo\n\t\t\t\t\t\t? new ServiceError.ServiceNotFound(service.id)\n\t\t\t\t\t\t: new ServiceError.TimedOut(service.id)\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\n\t\t// Discover services if needed and wait until this specific one appears\n\t\tawait Promise.race(promises)\n\t\tthis.throwErrorIfBadService(service)\n\t\treturn this.expectWithoutDiscovery(service)\n\t}\n\n\tprivate throwErrorIfBadService = <T>(service: Service<T>) => {\n\t\tconst discoveryInfo = this.latestDiscoveryInfo\n\n\t\t// Fail if the other end of the channel doesn't declare the needed service\n\t\tconst serviceInfo = discoveryInfo && discoveryInfo ? discoveryInfo.services[service.id] : undefined\n\t\tif (!serviceInfo) {\n\t\t\tthis.log.warn(\"\u260E\uFE0F Couldn't find service\", service.id, discoveryInfo)\n\t\t\tthrow new ServiceError.ServiceNotFound(service.id)\n\t\t}\n\n\t\t// Fail if the versions don't match\n\t\tif (serviceInfo.fingerprint !== service.fingerprint) {\n\t\t\tthis.log.warn(\n\t\t\t\t`\u260E\uFE0F Couldn't find service with required version fingerprint. Make sure both endpoints are using the same version of the Services package.`,\n\t\t\t\tdiscoveryInfo,\n\t\t\t)\n\t\t\tthrow new ServiceError.ServiceNotCompatible(service.id)\n\t\t}\n\t}\n\n\tprivate postOnewayRequest = (serviceId: string, request: ServiceMethodRequest): void => {\n\t\tthis.channel.postMessage({\n\t\t\ttype: ServiceChannel.MessageType.Request,\n\t\t\tid: ServiceChannel.onewayRequestId,\n\t\t\tserviceId,\n\t\t\tmethod: request.method,\n\t\t\tbody: request.argument,\n\t\t})\n\t}\n\n\tprivate postRequest = (\n\t\tserviceId: string,\n\t\trequest: ServiceMethodRequest,\n\t\ttimeout?: number,\n\t\tonStreamValue?: (body: ServiceChannel.MessageBody) => void,\n\t): Promise<ServiceChannel.MessageBody | undefined> => {\n\t\tthis.log.trace(\"\u2197\uFE0F\", serviceId, request)\n\n\t\tconst canPostMessage = !(this.channel.disabled ?? false)\n\t\tif (!canPostMessage) {\n\t\t\treturn Promise.reject(new ServiceError.ServiceNotFound(serviceId))\n\t\t}\n\n\t\t// Send the request with a good enough unique string to identify the request/response pair across services\n\t\tconst message: ServiceChannel.Message = {\n\t\t\ttype: ServiceChannel.MessageType.Request,\n\t\t\tid: ServiceRuntimeInternal.generateUniqueId(),\n\t\t\tserviceId,\n\t\t\tmethod: request.method,\n\t\t\tstream: StreamOperation.toMessage(request.stream),\n\t\t\tbody: request.argument,\n\t\t}\n\n\t\tconst responsePromise = ServiceRuntimeInternal.newResolvablePromise<ServiceChannel.Message | undefined>()\n\t\tthis.waitingRequestsMap[message.id] = { result: responsePromise, onStreamValue }\n\t\tthis.channel.postMessage(message)\n\n\t\tconst promises: Promise<ServiceChannel.Message | undefined>[] = [responsePromise]\n\t\tif (typeof timeout === \"number\") {\n\t\t\tpromises.push(\n\t\t\t\tdelay(timeout).then(() => {\n\t\t\t\t\tthrow new ServiceError.TimedOut()\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\n\t\t// Get the regular result, then optionally validate it\n\t\treturn Promise.race(promises)\n\t\t\t.then(response => response?.body)\n\t\t\t.catch(error => {\n\t\t\t\tdelete this.waitingRequestsMap[message.id]\n\t\t\t\tthrow error\n\t\t\t})\n\t}\n\n\tprivate readonly waitingRequestsMap: {\n\t\t[requestId in string]?: {\n\t\t\t// The final response value for the request\n\t\t\tresult: ServiceRuntimeInternal.ResolvablePromise<ServiceChannel.Message | undefined>\n\t\t\t// Optionally, zero or more additional values before the final result finishes the request\n\t\t\tonStreamValue: ((_: ServiceChannel.MessageBody) => void) | undefined\n\t\t}\n\t} = {}\n\n\tprivate onResponse = (response: ServiceChannel.Message) => {\n\t\tlet id = response.id\n\n\t\tconst isOnewayStreamResponse = id.startsWith(ServiceChannel.onewayStreamResponseIdPrefix)\n\t\tif (isOnewayStreamResponse) {\n\t\t\tid = id.substr(ServiceChannel.onewayStreamResponseIdPrefix.length)\n\t\t}\n\n\t\tconst request = this.waitingRequestsMap[id]\n\n\t\tif (isOnewayStreamResponse) {\n\t\t\t// If the response is oneway, it only goes through the special cased handler and is otherwise ignored\n\t\t\tif (request && response.body) {\n\t\t\t\trequest.onStreamValue?.(response.body)\n\t\t\t}\n\t\t} else {\n\t\t\t// Regular responses do finalize the request\n\t\t\tif (!request) return this.log.warn(\"\u260E\uFE0F onResponse: couldn't find request\", response)\n\t\t\tdelete this.waitingRequestsMap[id]\n\t\t\trequest.result.resolve(response)\n\t\t}\n\t}\n\n\tprivate onErrorResponse = (response: ServiceChannel.Message, customError?: ServiceError) => {\n\t\tconst request = this.waitingRequestsMap[response.id]\n\t\tif (!request) return this.log.warn(\"\u260E\uFE0F onErrorResponse: couldn't find request\", response)\n\n\t\tdelete this.waitingRequestsMap[response.id]\n\n\t\tconst error = customError || ServiceError.reconstructErrorResponse(response.body)\n\t\trequest.result.reject(error)\n\t}\n\n\t// Incoming messages\n\n\tprivate readonly implementedServices: {\n\t\t[id: string]: {\n\t\t\tservice: Service<unknown>\n\t\t\trawImplementation: unknown // For reference only\n\t\t\timplementation: unknown // For actual method calls (sanitized copy of rawImplementation)\n\t\t}\n\t} = {}\n\n\tprivate readonly unregisteredServices = new Set<string>()\n\n\tregisterImplementation = <T>(rawImplementation: T, service: Service<T>): void => {\n\t\tthis.log.trace(\"\u260E\uFE0F registerImplementation\", service.id, rawImplementation)\n\n\t\t// Only expose known methods, bound to the implementation object so they can be called as is\n\t\tconst implementation = {} as T\n\t\tfor (const key in service.methods) {\n\t\t\tconst name = key as keyof T\n\n\t\t\tconst method = rawImplementation[name]\n\t\t\tif (typeof method !== \"function\") {\n\t\t\t\tthrow new ServiceError.Implementation(\n\t\t\t\t\t`Implementation for ${service.id} doesn't correctly implement ${name as string}()`,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\timplementation[name] = method.bind(rawImplementation)\n\t\t}\n\n\t\tthis.unregisteredServices.delete(service.id)\n\t\tthis.implementedServices[service.id] = {\n\t\t\tservice,\n\t\t\trawImplementation,\n\t\t\timplementation: Object.freeze(implementation),\n\t\t}\n\t\tthis.broadcastDiscoveryInfo()\n\t}\n\n\tunregisterImplementation = async (rawImplementation: unknown): Promise<void> => {\n\t\tconst shouldUnregisterAll = rawImplementation === this.unregisterAllToken\n\t\tif (!shouldUnregisterAll) this.log.trace(\"\u260E\uFE0F unregisterImplementation\", rawImplementation)\n\n\t\t// ServiceManager unregisters the implementation on all routers, regardless of whether it was registered at all\n\t\tlet didChangeServices = false\n\t\tconst streamsToCancel: { id: string; error: ServiceError }[] = []\n\t\tfor (const [serviceId, implementedService] of Object.entries(this.implementedServices)) {\n\t\t\tif (!shouldUnregisterAll && implementedService.rawImplementation !== rawImplementation) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Delete the service\n\t\t\tthis.unregisteredServices.add(serviceId)\n\t\t\tdelete this.implementedServices[serviceId]\n\t\t\tdidChangeServices = true\n\n\t\t\t// Find associated streams\n\t\t\tfor (const [streamId, stream] of Object.entries(this.requestedStreamsMap)) {\n\t\t\t\tif (stream?.serviceId === serviceId) {\n\t\t\t\t\tstreamsToCancel.push({ id: streamId, error: new ServiceError.ServiceGone(serviceId) })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tawait this.cancelStreams(streamsToCancel)\n\n\t\tif (didChangeServices) {\n\t\t\tthis.broadcastDiscoveryInfo()\n\t\t}\n\t}\n\n\tprivate unregisterAllToken = {}\n\tunregisterAllImplementations = async (): Promise<void> => {\n\t\tthis.log.debug(\"\u260E\uFE0F unregisterAllImplementations\")\n\t\tawait this.unregisterImplementation(this.unregisterAllToken)\n\t}\n\n\tprivate readonly requestedStreamsMap: {\n\t\t[id in string]?: {\n\t\t\titerator: AsyncIterator<unknown>\n\t\t\tserviceId: string\n\t\t}\n\t} = {}\n\n\tprivate cancelStreams = async (streams: readonly { id: string; error: ServiceError }[]): Promise<void> => {\n\t\tconst cancelPromises: Promise<IteratorResult<unknown>>[] = []\n\t\tfor (const { id, error } of streams) {\n\t\t\tconst stream = this.requestedStreamsMap[id]\n\t\t\tdelete this.requestedStreamsMap[id]\n\n\t\t\t// Stop the iteration\n\t\t\tif (stream?.iterator.throw) {\n\t\t\t\tcancelPromises.push(stream.iterator.throw(error))\n\t\t\t}\n\t\t}\n\n\t\tawait Promise.all(cancelPromises)\n\t}\n\n\tprivate onRequest = async (request: ServiceChannel.Message): Promise<void> => {\n\t\t// Explicit discovery requests\n\t\tif (request.method === Discovery.method) {\n\t\t\tthis.broadcastDiscoveryInfo(request.id)\n\t\t\treturn\n\t\t}\n\n\t\t// Service requests\n\t\tlet resultType: ServiceChannel.MessageType = ServiceChannel.MessageType.Response\n\t\tlet resultBody: ServiceChannel.MessageBody | unknown\n\t\tlet resultIsExpectedError = false\n\t\ttry {\n\t\t\tconst implementedService = this.implementedServices[request.serviceId]\n\t\t\tconst implementation = implementedService?.implementation\n\t\t\tif (!implementation) {\n\t\t\t\tif (this.unregisteredServices.has(request.serviceId)) {\n\t\t\t\t\tthrow new ServiceError.ServiceGone(request.serviceId)\n\t\t\t\t} else {\n\t\t\t\t\tthrow new ServiceError.BadRequest()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.log.trace(\"\u2198\uFE0F\", request.serviceId, request)\n\n\t\t\t// Note: `implementation` is the sanitized implementation that is known to only have function fields\n\t\t\tconst method: (_: unknown) => unknown = (implementation as any)[request.method]\n\n\t\t\tif (!request.stream) {\n\t\t\t\t// Regular method call\n\t\t\t\tresultBody = await method(request.body)\n\t\t\t} else {\n\t\t\t\t// Stream operation, a.k.a. a method called on a consumer-side ServiceStream that needs to be\n\t\t\t\t// applied to a corresponding async iterator provided by the service implementation\n\t\t\t\tconst { id: streamId, method: iteratorMethod } = StreamOperation.fromMessage(request.stream)\n\n\t\t\t\t// See if there's already an iterator running for this stream id\n\t\t\t\tlet stream = this.requestedStreamsMap[streamId]\n\n\t\t\t\tif (iteratorMethod === \"next\") {\n\t\t\t\t\t// If not, start a new one\n\t\t\t\t\tif (!stream) {\n\t\t\t\t\t\tconst iteratorOptions = ServiceStreamsPrivate.isServiceStreamOptions(request.body)\n\t\t\t\t\t\t\t? request.body\n\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\tconst iteratorStream = (await method(iteratorOptions)) as ServiceStream<any>\n\t\t\t\t\t\tconst iterator = (iteratorStream[Symbol.asyncIterator] as Function)(\n\t\t\t\t\t\t\t// Note: this oneway callback is only recognized by ServiceEventEmitter streams, so generic\n\t\t\t\t\t\t\t// AsyncIterators simply fall back to the standard request/response flow.\n\t\t\t\t\t\t\titeratorOptions?.oneway\n\t\t\t\t\t\t\t\t? (value: unknown) => {\n\t\t\t\t\t\t\t\t\t\t// Send the value as a special type of response that doesn't count as the final result\n\t\t\t\t\t\t\t\t\t\tthis.channel.postMessage({\n\t\t\t\t\t\t\t\t\t\t\ttype: ServiceChannel.MessageType.Response,\n\t\t\t\t\t\t\t\t\t\t\tid: ServiceChannel.onewayStreamResponseIdPrefix + request.id,\n\t\t\t\t\t\t\t\t\t\t\tserviceId: request.serviceId,\n\t\t\t\t\t\t\t\t\t\t\tmethod: request.method,\n\t\t\t\t\t\t\t\t\t\t\tbody: { done: false, value: value as any },\n\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\t// Don't let this value trigger the normal iteration logic\n\t\t\t\t\t\t\t\t\t\treturn { ignore: true }\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\tstream = {\n\t\t\t\t\t\t\titerator,\n\t\t\t\t\t\t\tserviceId: implementedService.service.id,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.requestedStreamsMap[streamId] = stream\n\t\t\t\t\t}\n\n\t\t\t\t\t// Get the next iteration\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst iteratorResult = await stream.iterator.next()\n\t\t\t\t\t\tresultBody = { done: iteratorResult.done, value: iteratorResult.value }\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t// Expect an error while waiting for a value, if the service providing the stream has unregistered\n\t\t\t\t\t\tresultIsExpectedError = error instanceof ServiceError.ServiceGone\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t} else if (iteratorMethod === \"return\") {\n\t\t\t\t\t// Remove the stream, if it's still running\n\t\t\t\t\tdelete this.requestedStreamsMap[streamId]\n\n\t\t\t\t\t// Forward the stream cancellation to the iterator\n\t\t\t\t\tconst iteratorReturn = stream?.iterator.return\n\t\t\t\t\tif (iteratorReturn) {\n\t\t\t\t\t\tawait iteratorReturn()\n\t\t\t\t\t}\n\n\t\t\t\t\t// Respond with success regardless of whether anything was actually removed\n\t\t\t\t\tresultBody = { done: true, value: undefined }\n\t\t\t\t} else {\n\t\t\t\t\tthrow new ServiceError.BadRequest(\"Stream operations other than next() and return() are not yet supported\")\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tresultType = ServiceChannel.MessageType.Error\n\t\t\tresultBody = ServiceError.toMessageBody(error)\n\t\t\tif (!resultIsExpectedError) {\n\t\t\t\tthis.log.warn(\"\u260E\uFE0F onRequest: error\", request, error)\n\t\t\t}\n\t\t} finally {\n\t\t\t// Note: the result type currently isn't verified or validated in any way\n\t\t\tthis.channel.postMessage({\n\t\t\t\ttype: resultType,\n\t\t\t\tid: request.id,\n\t\t\t\tserviceId: request.serviceId,\n\t\t\t\tmethod: request.method,\n\t\t\t\tbody: resultBody as ServiceChannel.MessageBody | undefined, // Note: this may be untrue\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate onOnewayRequest = (request: ServiceChannel.Message): void => {\n\t\ttry {\n\t\t\tconst implementedService = this.implementedServices[request.serviceId]\n\t\t\tconst implementation = implementedService?.implementation\n\t\t\tif (!implementation) {\n\t\t\t\tif (this.unregisteredServices.has(request.serviceId)) {\n\t\t\t\t\tthrow new ServiceError.ServiceGone(request.serviceId)\n\t\t\t\t} else {\n\t\t\t\t\tthrow new ServiceError.BadRequest()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.log.trace(\"\u2198\uFE0F\", request.serviceId, request)\n\n\t\t\t// Regular method call without waiting and without an expected response\n\t\t\tconst method: (_: unknown) => unknown = (implementation as any)[request.method]\n\t\t\tmethod(request.body)\n\t\t} catch (error) {\n\t\t\tthis.log.warn(\"\u260E\uFE0F onOnewayRequest: error\", request, error)\n\t\t}\n\t}\n\n\t/** @private Only for tests. */\n\ttestable = {\n\t\twaitingRequestsMap: () => this.waitingRequestsMap,\n\t}\n}\n\nnamespace Discovery {\n\texport const serviceId = \"\"\n\texport const method = \"#discover\"\n\texport const broadcastMessageId = \"\"\n\n\texport type Info = {} & {\n\t\treadonly services: { [name: string]: ServiceInfo }\n\t}\n\n\texport type ServiceInfo = {} & {\n\t\treadonly fingerprint: string\n\t}\n\n\texport function isValidInfo(body: unknown): body is Info {\n\t\tif (body && typeof body === \"object\" && \"services\" in body && typeof body.services === \"object\") return true\n\t\treturn false\n\t}\n}\n\nnamespace StreamOperation {\n\t// FIXME: this type needs to be associated with ServiceMessageHelper\n\ttype Operation = {\n\t\tid: string\n\t\tmethod: Exclude<ServiceMethodRequest[\"stream\"], undefined>[\"method\"]\n\t}\n\n\ttype MessageOperation = Exclude<ServiceChannel.Message[\"stream\"], undefined>\n\tconst returnPrefix = \"#return:\"\n\tconst throwPrefix = \"#throw:\"\n\n\texport function fromMessage(operation: MessageOperation): Operation {\n\t\tif (operation.startsWith(returnPrefix)) {\n\t\t\treturn { id: operation.substr(returnPrefix.length), method: \"return\" }\n\t\t} else if (operation.startsWith(throwPrefix)) {\n\t\t\treturn { id: operation.substr(throwPrefix.length), method: \"throw\" }\n\t\t} else {\n\t\t\treturn { id: operation, method: \"next\" }\n\t\t}\n\t}\n\n\texport function toMessage(stream: Operation | undefined): MessageOperation | undefined {\n\t\tif (!stream) return undefined\n\t\tswitch (stream.method) {\n\t\t\tcase \"next\":\n\t\t\t\treturn stream.id // Having just a stream identifier implicitly means calling next()\n\t\t\tcase \"return\":\n\t\t\t\treturn returnPrefix + stream.id\n\t\t\tcase \"throw\":\n\t\t\t\treturn throwPrefix + stream.id\n\t\t\tdefault:\n\t\t\t\treturn undefined\n\t\t}\n\t}\n}\n\nfunction delay(ms: number) {\n\treturn new Promise(resolve => {\n\t\tsetTimeout(resolve, ms)\n\t})\n}\n", "/**\n * TypeScript only channel that only forwards messages locally to listeners to the same channel object.\n * It is of not much use than to replace a current Service implementation with a local JS object\n */\n\nimport type { ServiceChannel } from \"../ServiceChannel.ts\"\nimport { ServiceDebugging } from \"../ServiceDebugging.ts\"\n\nexport class LocalChannel implements ServiceChannel {\n\tprivate get log() {\n\t\t// Running .extend() every time .log() is called because 1) it\u2019s ~free (everything is memoized) and\n\t\t// 2) we don\u2019t want to cache possibly outdated fallback `ServiceDebugging.log`\n\t\treturn ServiceDebugging.log.extend(\"LocalChannel\")\n\t}\n\n\tpostMessage(message: ServiceChannel.Message): void {\n\t\tthis.log.trace(\"\u2197\uFE0E\", message)\n\t\tthis.listeners.forEach(listener => listener(message))\n\t}\n\taddMessageListener(callback: (message: ServiceChannel.Message) => void): void {\n\t\tthis.listeners.add(callback)\n\t}\n\tremoveMessageListener(callback: (message: ServiceChannel.Message) => void): void {\n\t\tthis.listeners.delete(callback)\n\t}\n\tprivate readonly listeners: Set<(message: ServiceChannel.Message) => void> = new Set()\n}\n\nexport const localChannel = new LocalChannel()\n", "// \u267B\uFE0F\n// IMPORTANT: Take care to sync changes with the Swift counterpart.\n\nimport { ServiceChannel } from \"../ServiceChannel.ts\"\nimport { ServiceDebugging } from \"../ServiceDebugging.ts\"\nimport type { MessageEvent, Window } from \"../environment.ts\"\n\n// \u2757\uFE0F\n// The Services package needs to work in any TypeScript environment. Reference DOM types without importing or depending\n// on them so that the package compiles, but fails or skips functionality when used in a non-DOM environment.\ndeclare const window: never\nconst windowIfExists = typeof window === \"undefined\" ? undefined : (window as Window)\n\n// Magic constant to allow the channels below to be constructed before the app can configure them\nconst __originInitializeLater = \"data:origin-not-initialized\"\n\n/**\n * Channel that communicates with another `PostMessageChannel`, either using a `postMessage` entry point (e.g.\n * an iframe or parent frame), with PlaywrightPageChannel, WebContentsChannel, or PostMessageChannel on the Swift side.\n */\nexport class PostMessageChannel implements ServiceChannel {\n\tprivate get log() {\n\t\t// Running .extend() every time .log() is called because 1) it\u2019s ~free (everything is memoized) and\n\t\t// 2) we don\u2019t want to cache possibly outdated fallback `ServiceDebugging.log`\n\t\treturn ServiceDebugging.log.extend(\"PostMessageChannel\")\n\t}\n\n\tstatic get toParentFrame() {\n\t\tisConstructingParentFrameChannel = true\n\t\tparentFrameChannel =\n\t\t\tparentFrameChannel ??\n\t\t\tnew PostMessageChannel(PostMessageChannel.targetRepresentingParentFrame, __originInitializeLater)\n\t\tisConstructingParentFrameChannel = false\n\t\treturn parentFrameChannel\n\t}\n\n\t// Fallback for frames that don't have a window.parent: detect an external controller (Swift, Electron or Playwright)\n\tprivate static targetRepresentingParentFrame = (() => {\n\t\tconst messageHandlerKey = \"__targetRepresentingParentFrame\"\n\n\t\t// Find a magical proxy to the controller, which must be set up before any other script runs.\n\t\t// Note that this is \"secure\" because any actor that can assign something to the window global\n\t\t// already has access to the entire runtime anyway.\n\t\tconst messageHandler =\n\t\t\t(windowIfExists as any)?.[messageHandlerKey] ??\n\t\t\t(windowIfExists as any)?.[\"webkit\"]?.messageHandlers?.[messageHandlerKey]\n\n\t\treturn {\n\t\t\tdisabled: !messageHandler,\n\t\t\tpostMessage: (...args: any[]) => {\n\t\t\t\tif (!windowIfExists) {\n\t\t\t\t\tthrow new Error(\"PostMessageChannel requires a DOM environment\")\n\t\t\t\t} else if (!messageHandler) {\n\t\t\t\t\tthrow new Error(`Can't find window.parent or ${messageHandlerKey} message handler`)\n\t\t\t\t}\n\t\t\t\tmessageHandler.postMessage(...args)\n\t\t\t},\n\t\t}\n\t})()\n\n\tconstructor(\n\t\tprivate readonly target: { postMessage: Window[\"postMessage\"] },\n\t\ttargetOrigin: string,\n\t) {\n\t\t// When targeting the parent frame, either use the actual parent or the messageHandler set up by Swift, Playwright, or Electron.\n\t\tconst targetRepresentingParentFrame = PostMessageChannel.targetRepresentingParentFrame\n\t\tif (target === (windowIfExists ? windowIfExists.parent : undefined) || target === targetRepresentingParentFrame) {\n\t\t\tif (!isConstructingParentFrameChannel || parentFrameChannel !== undefined) {\n\t\t\t\tthrow new Error(\"PostMessageChannel.toParentFrame must be used instead of initializing with window.parent.\")\n\t\t\t} else if (!windowIfExists) {\n\t\t\t\t// Running in a test environment\n\t\t\t\tthis.target = {\n\t\t\t\t\tpostMessage: (...args: any[]) => {\n\t\t\t\t\t\tthis.log.debug(\"postMessage to parent channel not running in a DOM environment: \", args)\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t} else if (windowIfExists.parent !== windowIfExists) {\n\t\t\t\t// Use the actual parent if it exists\n\t\t\t\tthis.target = windowIfExists.parent\n\t\t\t} else {\n\t\t\t\t// Use the messageHandler set up by Swift, Playwright, or Electron.\n\t\t\t\tthis.target = targetRepresentingParentFrame\n\t\t\t\tthis.disabled = targetRepresentingParentFrame.disabled\n\t\t\t}\n\t\t}\n\n\t\tif (targetOrigin !== __originInitializeLater) {\n\t\t\tthis.initializeTrustedOrigin(targetOrigin)\n\t\t}\n\t}\n\n\tprivate trustedOrigin = __originInitializeLater\n\tinitializeTrustedOrigin(origin: string) {\n\t\tif (this.trustedOrigin !== __originInitializeLater) {\n\t\t\tif (this === parentFrameChannel && origin === this.trustedOrigin) {\n\t\t\t\t// Allow setting the same origin twice, but only on channelToParentFrame. This exception only exists\n\t\t\t\t// to make it easier to initialize both channelToParentFrame and channelToOpenerFrame, which falls\n\t\t\t\t// back to channelToParentFrame if there's no window opener.\n\t\t\t} else {\n\t\t\t\tthrow new Error(`PostMessageChannel can only be initialized with a trusted origin once`)\n\t\t\t}\n\t\t}\n\n\t\tif (origin === \"*\") {\n\t\t\t// FIXME: continue, but this should probably not be allowed on production\n\t\t} else if (!origin.includes(\"://\")) {\n\t\t\tthrow new Error(\n\t\t\t\t`PostMessageChannel can only be initialized with a concrete origin (https://...); received ${origin}`,\n\t\t\t)\n\t\t}\n\n\t\tthis.trustedOrigin = origin\n\t}\n\n\treadonly disabled?: boolean\n\n\tpostMessage(message: ServiceChannel.Message): void {\n\t\tthis.log.trace(\"\u2197\uFE0E\", message)\n\n\t\t// Note: if the origin hasn't been initialized, just let the browser fail with the default empty string\n\t\tthis.target.postMessage(message, this.trustedOrigin)\n\t}\n\n\tpostMessageRaw(message: unknown): void {\n\t\t// Note: if the origin hasn't been initialized, just let the browser fail with the default empty string\n\t\tthis.target.postMessage(message, this.trustedOrigin)\n\t}\n\n\taddMessageListener(callback: (message: ServiceChannel.Message) => void): void {\n\t\tif (this.listeners.size === 0) {\n\t\t\t// Note: message events sent by `target` arrive on `window`\n\t\t\twindowIfExists?.addEventListener(\"message\", this.onMessageEvent, false)\n\t\t}\n\n\t\tthis.listeners.add(callback)\n\t}\n\n\tremoveMessageListener(callback: (message: ServiceChannel.Message) => void): void {\n\t\tthis.listeners.delete(callback)\n\n\t\tif (this.listeners.size === 0) {\n\t\t\twindowIfExists?.removeEventListener(\"message\", this.onMessageEvent, false)\n\t\t}\n\t}\n\n\tprivate readonly listeners: Set<(message: ServiceChannel.Message) => void> = new Set()\n\n\tprivate onMessageEvent = (event: MessageEvent) => {\n\t\tthis.log.trace(event.data, event.origin)\n\n\t\t// Ignore events that don't come from the postMessage target\n\t\tlet isTrustedSource = false\n\t\tif (event.source !== this.target) {\n\t\t\tif (\n\t\t\t\t// But, if the \"parent frame\" is actually an external controller\n\t\t\t\tthis === parentFrameChannel &&\n\t\t\t\t// ...which produces a local postMessage (see PostMessageChannel.swift, PlaywrightPageChannel.ts, WebContentsChannel.ts)\n\t\t\t\tevent.source === windowIfExists &&\n\t\t\t\t// ...marking the event with this special attribute\n\t\t\t\t(event.data as any)?.__sourceRepresentsParentFrame\n\t\t\t) {\n\t\t\t\t// ...then we need to handle it regardless of origin\n\t\t\t\tisTrustedSource = true\n\t\t\t} else {\n\t\t\t\t// ...if not, ignore\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t// Ignore events with an unexpected origin. Note we should only perform this check after the source has been\n\t\t// verified, otherwise we'd be throwing errors for random incoming messages not intended for this channel.\n\t\tif (!isTrustedSource && event.origin !== this.trustedOrigin) {\n\t\t\tif (this.trustedOrigin === \"*\") {\n\t\t\t\t// FIXME: continue, but this should probably not be allowed on production\n\t\t\t} else {\n\t\t\t\tif (this.trustedOrigin) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`PostMessageChannel received a message with origin ${event.origin}, expected ${this.trustedOrigin}`,\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`PostMessageChannel received a message with origin ${event.origin}, but has not been configured with initializeTrustedOrigin`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Ignore externally handled events\n\t\tif (this.interceptor?.handleRawEvent(event)) {\n\t\t\treturn\n\t\t}\n\n\t\t// Ignore things that are certainly not service messages\n\t\tconst message = event.data\n\t\tif (!ServiceChannel.isMessage(message)) {\n\t\t\treturn\n\t\t}\n\n\t\t// Notify\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener(message)\n\t\t}\n\t}\n\n\t/**\n\t * Registers the callback as a filter for incoming messages from the opener frame. Useful when\n\t * handling postMessage events manually as well as using services on the opener.\n\t */\n\tstatic interceptMessageEventsFromOpenerFrame(interceptor?: (_: MessageEvent) => boolean) {\n\t\tchannelToOpenerFrame.setInterceptor(interceptor)\n\t}\n\n\tprivate interceptor?: {\n\t\thandleRawEvent: (_: MessageEvent) => boolean\n\t\tunusedMessageListenerOnlyForCounting: (_: ServiceChannel.Message) => void\n\t}\n\n\tprivate setInterceptor(callback?: (_: MessageEvent) => boolean) {\n\t\tif (this.interceptor) {\n\t\t\tthis.removeMessageListener(this.interceptor.unusedMessageListenerOnlyForCounting)\n\t\t}\n\n\t\tthis.interceptor = callback\n\t\t\t? {\n\t\t\t\t\thandleRawEvent: callback,\n\t\t\t\t\tunusedMessageListenerOnlyForCounting: () => {},\n\t\t\t\t}\n\t\t\t: undefined\n\n\t\tif (this.interceptor) {\n\t\t\tthis.addMessageListener(this.interceptor.unusedMessageListenerOnlyForCounting)\n\t\t}\n\t}\n}\n\n// Special channel to the parent frame\nlet isConstructingParentFrameChannel = false\nlet parentFrameChannel: PostMessageChannel | undefined\n\n/**\n * The channel to either the parent frame, or a Playwright, Electron or Swift controller.\n * Should be used in favor of PostMessageChannel.toParentFrame.\n */\nexport const channelToParentFrame: PostMessageChannel = PostMessageChannel.toParentFrame\n\n/**\n * The channel to window.opener. Defaults to channelToParentFrame if there's no\n * opener, or if the opener is the current window.\n */\nexport const channelToOpenerFrame: PostMessageChannel =\n\twindowIfExists &&\n\twindowIfExists.opener &&\n\twindowIfExists !== windowIfExists.opener &&\n\twindowIfExists.parent === windowIfExists\n\t\t? new PostMessageChannel(windowIfExists.opener, __originInitializeLater)\n\t\t: channelToParentFrame\n", "import type { ServiceChannel } from \"./ServiceChannel.ts\"\nimport type { ServiceMessageHelper, ServiceStream, ServiceStreamOptions, oneway } from \"./ServiceDefinition.ts\"\nimport { ServiceStreamsPrivate } from \"./streams/private.ts\"\n\nexport namespace ServiceRuntimePrivate {\n\texport function onewayMethodTemplate(\n\t\tmethod: string,\n\t\tacceptsArgument: boolean,\n\t\thelper: ServiceMessageHelper,\n\t\targument?: ServiceChannel.MessageBody,\n\t): oneway {\n\t\tvoid helper({\n\t\t\tmethod,\n\t\t\targument: acceptsArgument ? argument : undefined,\n\t\t\toneway: true,\n\t\t})\n\t}\n\n\texport async function voidMethodTemplate(\n\t\tmethod: string,\n\t\tacceptsArgument: boolean,\n\t\thelper: ServiceMessageHelper,\n\t\targument?: ServiceChannel.MessageBody,\n\t): Promise<void> {\n\t\tawait helper({\n\t\t\tmethod,\n\t\t\targument: acceptsArgument ? argument : undefined,\n\t\t})\n\t}\n\n\texport async function valueMethodTemplate<T extends object>(\n\t\tmethod: string,\n\t\tacceptsArgument: boolean,\n\t\thelper: ServiceMessageHelper,\n\t\targument?: ServiceChannel.MessageBody,\n\t): Promise<T> {\n\t\tconst result = await helper({\n\t\t\tmethod,\n\t\t\targument: acceptsArgument ? argument : undefined,\n\t\t})\n\t\treturn result as T\n\t}\n\n\texport function streamMethodTemplate<T extends object>(\n\t\tmethod: string,\n\t\thelper: ServiceMessageHelper,\n\t\toptions?: ServiceStreamOptions,\n\t): ServiceStream<T> {\n\t\treturn new ServiceStreamsPrivate.StreamReader(method, options, helper)\n\t}\n}\n", "import { ServiceDebugging } from \"../ServiceDebugging.ts\"\nimport type { ServiceStream, ServiceStreamCallback, ServiceStreamOptions } from \"../ServiceDefinition.ts\"\nimport { ServiceError } from \"../ServiceErrors.ts\"\nimport { ServiceRuntimeInternal } from \"../internal.ts\"\nimport type { ServiceStreamValueInterceptor } from \"./private.ts\"\n\n/**\n * ServiceEventEmitter is a stream implementation for a (potentially infinite) sequence of events\n * not associated with any particular task or service message. It supports any number of attached\n * AsyncIterators, with no guarantee as to which event will appear in the first iteration. Use for\n * publish/subscribe or state observing behavior.\n */\nexport class ServiceEventEmitter<T extends object> {\n\tprivate hook: ((event: T) => void) | undefined = undefined\n\n\t/** When calling .emit(), the hook will also be called, if installed. This can ease upgrading\n\t * from old RPC to new RPC. */\n\tsetHook(hook: (event: T) => void) {\n\t\tthis.hook = hook\n\t}\n\n\t/**\n\t * Callback that's invoked when a new stream is created.\n\t * Optionally returns a custom \"latest\" value for the new stream.\n\t */\n\tonNewStream?: (options?: ServiceStreamOptions) => { latest: T } | undefined\n\n\t/**\n\t * Returns a new ServiceStream that reads the events emitted by this ServiceEventEmitter.\n\t */\n\treadonly newStream = (options?: ServiceStreamOptions): ServiceStream<T> => {\n\t\tconst id = ServiceRuntimeInternal.generateUniqueId()\n\n\t\treturn new ServiceStreamIterator(\n\t\t\t// Individual stream\n\t\t\t(update, done) => {\n\t\t\t\tthis.iterators.push({ id, update, done })\n\n\t\t\t\t// Invoke the callback, optionally returning extra info\n\t\t\t\tconst callbackReturnValue = this.onNewStream?.(options)\n\n\t\t\t\t// Some streams may want an initial value instead of waiting for a new emit\n\t\t\t\tif (options?.replay === \"latest\") {\n\t\t\t\t\tconst latestValue = callbackReturnValue?.latest ?? this.latestValue\n\t\t\t\t\tif (latestValue) {\n\t\t\t\t\t\tupdate(latestValue)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Since value replay is opt-in for service definitions, enforce correct implementation\n\t\t\t\t\t\tthrow new ServiceError.Implementation(\n\t\t\t\t\t\t\t`ServiceEventEmitter needs a \"latest\" value, but nothing has been emitted or returned by the onNewStream callback`,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t} else if (callbackReturnValue) {\n\t\t\t\t\t// Make sure the callback doesn't calculate things unnecessarily\n\t\t\t\t\tthrow new ServiceError.Implementation(\n\t\t\t\t\t\t`ServiceEventEmitter received a \"latest\" value from the onNewStream callback for a stream that didn't need it`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t},\n\t\t\t// Ended iteration (either from client or server side)\n\t\t\t() => {\n\t\t\t\tconst i = this.iterators.findIndex(iterator => iterator.id === id)\n\t\t\t\tif (i >= 0) {\n\t\t\t\t\tthis.iterators.splice(i, 1)\n\t\t\t\t} else {\n\t\t\t\t\tthrow new ServiceError.BadRequest(`ServiceEventEmitter couldn't find cancelled iterator with id: ${id}`)\n\t\t\t\t}\n\t\t\t},\n\t\t)\n\t}\n\n\tprivate readonly iterators: {\n\t\tid: string\n\t\tupdate: (value: T) => void\n\t\tdone: () => void\n\t}[] = []\n\tprivate latestValue?: T\n\n\treadonly emit = (value: T) => {\n\t\tthis.hook?.(value)\n\n\t\tthis.latestValue = value\n\t\tfor (const iterator of this.iterators) {\n\t\t\titerator.update(value)\n\t\t}\n\t}\n\n\treadonly latest = () => {\n\t\treturn this.latestValue\n\t}\n\n\treadonly hasStreams = () => {\n\t\treturn this.iterators.length > 0\n\t}\n}\n\n/**\n * ServiceStreamIterator is a stream implementation for a finite sequence of updates or data packets, sent as a result\n * of one specific service message. It can be iterated only once. Use for one-off task status updates or data transfer.\n */\nclass ServiceStreamIterator<T extends object> implements ServiceStream<T> {\n\tprivate readonly log = ServiceDebugging.log.extend(\"ServiceStreamIterator\")\n\n\tprivate hasAsyncIterator = false\n\tprivate updatesBeforeAsyncIterator: T[] = []\n\tprivate onUpdate?: ServiceStreamValueInterceptor<T>\n\n\tconstructor(\n\t\ttask: (update: (value: T) => void, done: () => void) => void,\n\t\tprivate readonly onIteratorEnd?: () => void,\n\t) {\n\t\tthis.promises = [ServiceRuntimeInternal.newResolvablePromise()]\n\t\ttask(this.update, this.update)\n\t}\n\n\t// Note: the implementation of Router.onRequest implicitly knows about the callback argument\n\t[Symbol.asyncIterator](onUpdate?: ServiceStreamValueInterceptor<T>): AsyncIterator<T> {\n\t\tif (this.hasAsyncIterator) {\n\t\t\tthrow new Error(\"ServiceStreamIterator.asyncIterator() may only be called once\")\n\t\t}\n\t\tthis.onUpdate = onUpdate\n\t\tthis.hasAsyncIterator = true\n\t\tthis.updatesBeforeAsyncIterator.forEach(this.update)\n\t\tthis.updatesBeforeAsyncIterator = []\n\t\treturn this\n\t}\n\n\tprivate readonly doneResult: IteratorResult<T> = { done: true, value: undefined as unknown as T }\n\tprivate readonly promises: ServiceRuntimeInternal.ResolvablePromise<IteratorResult<T>>[] = []\n\tprivate returnedNextPromise: ServiceRuntimeInternal.ResolvablePromise<IteratorResult<T>> | undefined\n\n\tprivate readonly update = (value?: T | ServiceError) => {\n\t\tconst { hasAsyncIterator, updatesBeforeAsyncIterator, promises, returnedNextPromise } = this\n\n\t\t// When receiving updates before anyone is reading, just queue them for replay when the iteration starts.\n\t\t// Recall that every update needs to have the appropriate onUpdate called, which isn't available yet.\n\t\tif (!hasAsyncIterator) {\n\t\t\tif (!value || value instanceof ServiceError) {\n\t\t\t\t// Only the internals call update() with a non-T value, and this shouldn't happen before iteration\n\t\t\t\tthrow new ServiceError.BadRequest(\"ServiceStream received return or throw before being read\")\n\t\t\t}\n\n\t\t\tupdatesBeforeAsyncIterator.push(value)\n\t\t\treturn\n\t\t}\n\n\t\t// Figure out which promise to resolve (depending on whether the writer or reader is \"ahead\")\n\t\tlet lastPromise = (promises as Partial<typeof promises>)[this.promises.length - 1]\n\t\tif (value && lastPromise === undefined) {\n\t\t\tif (!returnedNextPromise) {\n\t\t\t\tthis.log.warn(\"lastPromise and returnedNextPromise should never both be undefined\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlastPromise = returnedNextPromise\n\t\t}\n\n\t\tif (value === undefined) {\n\t\t\t// Done: clean up the last next() if necessary (may already have happened if cancel/return calls this)\n\t\t\tlastPromise?.resolve(this.doneResult)\n\t\t\t// Note: this depends on multiple resolves/rejects on a promise having no effect\n\t\t\treturnedNextPromise?.resolve(this.doneResult)\n\t\t} else if (value instanceof ServiceError) {\n\t\t\t// *Only* reject the already return promise, otherwise this will\n\t\t\t// cause an unhandled promise rejection error on the side where the\n\t\t\t// stream is registered.\n\t\t\treturnedNextPromise?.reject(value)\n\t\t} else {\n\t\t\t// Update: values may be intercepted (unlike returns/throws)\n\t\t\tif (this.onUpdate?.(value).ignore) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Prepare a promise for the next next()\n\t\t\tpromises.push(ServiceRuntimeInternal.newResolvablePromise())\n\t\t\tlastPromise?.resolve({ done: false, value })\n\t\t}\n\t}\n\n\treadonly next = async () => {\n\t\tconst promise = this.promises.shift()\n\t\tthis.returnedNextPromise = promise\n\t\treturn promise || this.doneResult\n\t}\n\n\treadonly return = async () => {\n\t\tthis.update(undefined)\n\t\tthis.onIteratorEnd?.()\n\t\treturn this.doneResult\n\t}\n\n\treadonly throw = async (error: ServiceError) => {\n\t\tthis.update(error)\n\t\tthis.onIteratorEnd?.()\n\t\treturn this.doneResult\n\t}\n\n\treadonly read = async (callback: ServiceStreamCallback<T>): Promise<void> => {\n\t\t// TODO: This could be a for await of loop but ESBuild doesn't support it yet in the figma-plugin\n\t\t// for await (const event of this) {\n\t\t//     await callback(event)\n\t\t// }\n\n\t\tconst iterator = this[Symbol.asyncIterator]()\n\t\tlet result = await iterator.next()\n\n\t\twhile (!result.done) {\n\t\t\tcallback(result.value)\n\t\t\tresult = await iterator.next()\n\t\t}\n\t}\n\n\treadonly cancel = async () => {\n\t\tawait this.return()\n\t}\n}\n"],
  "mappings": ";;;;;;;;AAGO,IAAU;AAAA,CAAV,CAAUA,sBAAV;AAGC,EAAIA,kBAAA,MAAc,UAAU,oDAA6C;AAAA,GAHhE;AAAA,CASV,CAAUA,sBAAV;AAGC,EAAIA,kBAAA,aAAa;AACxB,MAAI;AAGJ,iBAAsB,gBAAmB,SAAyB,IAAsB;AACvF,QAAI,CAACA,kBAAiB,YAAY;AACjC,YAAM,IAAI,MAAM,+DAA+D;AAAA,IAChF;AACA,QAAI,uBAAwB,OAAM,IAAI,MAAM,mDAAmD;AAE/F,QAAI;AACH,+BAAyB;AACzB,aAAO,MAAM,GAAG;AAAA,IAEjB,UAAE;AACD,+BAAyB;AAAA,IAC1B;AAAA,EACD;AAbA,EAAAA,kBAAsB;AAgBf,WAAS,iCAA6D;AAC5E,QAAIA,kBAAiB,YAAY;AAChC,UAAI,CAAC,wBAAwB;AAC5B,cAAM,IAAI,MAAM,+FAA+F;AAAA,MAChH,OAAO;AACN,eAAO;AAAA,MACR;AAAA,IACD;AAGA,WAAO;AAAA,EACR;AAXO,EAAAA,kBAAS;AAAA,GAvBA;;;ACM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EjC,aAAO,CAAC,OAAO,MAAM;AACpB,iBAAS,OAAO,KAAK;AACrB,iBAAS,MAAM,SAAS,KAAK;AAAA,MAC9B;AAAA,IACD;AAEA,wBAAS,UAAS,YAAY;AAC7B,YAAM,KAAK,OAAO;AAAA,IACnB;AAvGC,SAAK,WAAW,CAAC,uBAAuB,qBAAqB,CAAC;AAC9D,SAAK,KAAK,QAAQ,KAAK,MAAM;AAAA,EAC9B;AAAA;AAAA,EAGA,CAAC,OAAO,aAAa,EAAE,UAA+D;AACrF,QAAI,KAAK,kBAAkB;AAC1B,YAAM,IAAI,MAAM,+DAA+D;AAAA,IAChF;AACA,SAAK,WAAW;AAChB,SAAK,mBAAmB;AACxB,SAAK,2BAA2B,QAAQ,KAAK,MAAM;AACnD,SAAK,6BAA6B,CAAC;AACnC,WAAO;AAAA,EACR;AA0FD;",
  "names": ["ServiceDebugging", "ServiceChannel", "MessageType", "ServiceError", "Code", "ServiceRuntimeInternal", "ServiceStreamsPrivate", "ServiceManager", "Discovery", "StreamOperation", "ServiceRuntimePrivate"]
}
