# @embedpdf/svelte — ./runtime AbortablePromise [ClassDeclaration] (from packages/engine/core/src/promise/AbortablePromise.ts): export class AbortablePromise extends Promise{ static override get [Symbol.species](): PromiseConstructor{ return Promise; } readonly signal: AbortSignal; private readonly _ctrl: AbortController; private readonly _progressCbs: Set<(p: P) => void>; private readonly _state:{ settled: boolean} ; private readonly _internalReject: (reason: unknown) => void; constructor(executor: AbortableExecutor){ const ctrl = new AbortController(); const progressCbs = new Set<(p: P) => void>(); const state ={ settled: false} ; let capturedReject!: (reason: unknown) => void; super((resolve, reject) =>{ capturedReject = reject; const wrappedResolve = (value: T | PromiseLike) =>{ if (state.settled) return; state.settled = true; resolve(value); } ; const wrappedReject = (reason: unknown) =>{ if (state.settled) return; state.settled = true; reject(reason); } ; const progress = (p: P) =>{ if (state.settled) return; for (const cb of progressCbs){ try{ cb(p); } catch{ } } } ; executor(wrappedResolve, wrappedReject, progress, ctrl.signal); } ); this._ctrl = ctrl; this.signal = ctrl.signal; this._progressCbs = progressCbs; this._state = state; this._internalReject = capturedReject; } abort(reason?: unknown): void{ if (this._state.settled) return; if (this._ctrl.signal.aborted) return; const err = reason instanceof AbortError ? reason : new AbortError(reason); this._state.settled = true; this._ctrl.abort(err); this._internalReject(err); } abortWith(signal: AbortSignal): this{ if (signal.aborted){ this.abort(signal.reason); return this; } const onAbort = () => this.abort(signal.reason); signal.addEventListener('abort', onAbort, { once: true} ); const detach = () => signal.removeEventListener('abort', onAbort); Promise.prototype.then.call(this, detach, detach); return this; } onProgress(cb: (p: P) => void): () => void{ this._progressCbs.add(cb); return () =>{ this._progressCbs.delete(cb); } ; } static resolveValue(value: T | PromiseLike): AbortablePromise{ return new AbortablePromise((resolve) => resolve(value)); } static rejectReason(reason: unknown): AbortablePromise{ return new AbortablePromise((_resolve, reject) => reject(reason)); } static run( fn: (signal: AbortSignal, progress: (p: P) => void) => Promise, ): AbortablePromise{ return new AbortablePromise((resolve, reject, progress, signal) =>{ fn(signal, progress).then(resolve, reject); } ); } } AnnotationAppearanceImage [InterfaceDeclaration] (from packages/engine/core/src/dto/AnnotationRender.ts): export interface AnnotationAppearanceImage{ ref: AnnotationRef; mode: AnnotationAppearanceMode; state: string | null; rect: C['box']; image: PageImageHandle; } AnnotationRef [TypeAliasDeclaration] (from packages/engine/core/src/identity/AnnotationRef.ts): export type AnnotationRef = |{ kind: 'objectNumber'; page: PageRef; objectNumber: number; } |{ kind: 'baseIndex'; page: PageRef; baseIndex: number; } ; AnyPlugin [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type AnyPlugin = PluginDefinition; BatchResult [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface BatchResult{ readonly applied: readonly T[]; readonly skipped: readonly{ readonly ref: R; readonly reason: string} []; readonly failed: readonly{ readonly ref: R; readonly error: PluginErrorInfo} []; } CONTINUOUS_RENDER_POLICY [VariableDeclaration] (from packages/engine/core/src/engine/DocumentRenderService.ts): CONTINUOUS_RENDER_POLICY: EngineRenderPolicy ={ kind: 'continuous'} CallFacts [InterfaceDeclaration] (from packages/engine/core/src/scheduling/facts.ts): export interface CallFacts{ readonly priority?: CallPriority; readonly view?: string; } CallPriority [TypeAliasDeclaration] (from packages/engine/core/src/scheduling/facts.ts): export type CallPriority = 'high' | 'auto' | 'low'; Cancel [TypeAliasDeclaration] (from packages/core/main/src/clock.ts): export type Cancel = () => void; CancelledError [ClassDeclaration] (from packages/core/main/src/scope.ts): export class CancelledError extends Error{ constructor(what: string){ super(`[kernel] cancelled: ${ what} `); this.name = 'CancelledError'; } } CapabilityToken [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface CapabilityToken{ readonly name: string; readonly hint?: string; readonly promises?: Readonly>; readonly __type?: T; } ChangeLabel [InterfaceDeclaration] (from packages/core/main/src/changes.ts): export interface ChangeLabel{ readonly key: string; readonly [value: string]: string | number; } ChangeQueue [InterfaceDeclaration] (from packages/core/main/src/changes.ts): export interface ChangeQueue{ stage(change: StagedChange): PendingChange; hold(label: ChangeLabel, options?: HoldOptions): HeldChange; sendHolds(): void; group(label: ChangeLabel, run: () => T): T; takeObjectNumber(): number | null; reserveObjectNumbers(count: number): Promise; listPending(): readonly PendingChange[]; hasPending(): boolean; whenSettled(): Promise; readonly onStaged: EventHook; readonly onSettled: EventHook; } CommandContext [InterfaceDeclaration] (from packages/core/main/src/command-types.ts): export interface CommandContext{ readonly documentId: string | null; readonly appState: AppState; readonly args?: unknown; readonly signal?: AbortSignal; get(token: CapabilityToken): T; tryGet(token: CapabilityToken): T | null; } CommandDefinition [InterfaceDeclaration] (from packages/core/main/src/command-types.ts): export interface CommandDefinition{ readonly id: string; readonly label?: string; readonly labelKey?: string; readonly icon?: string; iconAccent?(context: CommandContext): IconAccent | null; readonly shortcut?: string | readonly string[]; readonly shortcutInTextFields?: boolean; readonly categories?: readonly string[]; readonly requires?: readonly Permission[]; allowed?(context: CommandContext): boolean; readonly notAllowedKey?: string; locked?(context: CommandContext): SettingLock | null; readonly menu?: string; readonly panel?: | string |{ readonly id: string; readonly exclusive?: string; readonly focus?: boolean} ; readonly modal?: string; enabled?(context: CommandContext): boolean; active?(context: CommandContext): boolean; visible?(context: CommandContext): boolean; labelParams?(context: CommandContext): Readonly>; run?(context: CommandContext): void | Promise; } CommandFamily [InterfaceDeclaration] (from packages/core/main/src/command-types.ts): export interface CommandFamily{ readonly prefix: string; readonly names: (context: CommandContext) => readonly string[]; readonly command: (name: string) => Omit; } CoreState [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface CoreState{ readonly documents: Readonly>; readonly pending: Readonly>; readonly order: readonly string[]; readonly activeId: string | null; } CurrentValue [InterfaceDeclaration] (from packages/framework/svelte/src/runtime/values.svelte.ts): export interface CurrentValue{ readonly current: T; } CustomMetadata [TypeAliasDeclaration] (from packages/engine/core/src/dto/CustomMetadata.ts): export type CustomMetadata = Record; CustomMetadataPatch [TypeAliasDeclaration] (from packages/engine/core/src/dto/CustomMetadataPatch.ts): export type CustomMetadataPatch = Record; CustomMetadataUpdateResult [InterfaceDeclaration] (from packages/engine/core/src/mutation/CustomMetadataUpdateResult.ts): export interface CustomMetadataUpdateResult{ custom: CustomMetadata; meta: MutationMeta; } DeepPartial [TypeAliasDeclaration] (from packages/core/main/src/settings.ts): export type DeepPartial ={ readonly [K in keyof T]?: DeepPartialValue} ; DocCapability [TypeAliasDeclaration] (from packages/engine/core/src/auth/scope/types.ts): export type DocCapability = | 'doc.open' | 'doc.render' | 'doc.text.copy' | 'doc.text.search' | 'doc.content.copy' | 'doc.download' | 'doc.download.flattened' | 'doc.print' | 'doc.print.high' | 'doc.pages.modify' | 'doc.pages.assemble' | 'doc.forms.read' | 'doc.forms.fill' | 'doc.forms.modify' | 'doc.forms.import' | 'doc.forms.script' | 'doc.forms.submit' | 'doc.annotate.read' | 'doc.annotate.modify' | 'doc.annotate.import' | 'doc.metadata.modify' | 'doc.attachments.modify' | 'doc.outline.modify' | 'doc.redact' | 'doc.sign' | 'doc.sign.certify'; DocumentActiveChangedEvent [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DocumentActiveChangedEvent{ readonly documentId: string | null; readonly previousDocumentId: string | null; } DocumentClosedEvent [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DocumentClosedEvent{ readonly documentId: string; } DocumentEvent [TypeAliasDeclaration] (from packages/engine/core/src/events/DocumentEvent.ts): export type DocumentEvent = | ({ type: 'pages.scaleSet'; origin: EventOrigin; pages: PageRef[]; measure: PdfMeasure | null; } & PageScaleResult) | ({ type: 'annotations.created'; page: PageRef; origin: EventOrigin; } & AnnotationCreateResult) | ({ type: 'annotations.updated'; page: PageRef; origin: EventOrigin; } & AnnotationUpdateResult) | ({ type: 'annotations.deleted'; page: PageRef; origin: EventOrigin; deleted: AnnotationRef[]; } & AnnotationDeleteResult) | ({ type: 'annotations.reordered'; page: PageRef; origin: EventOrigin; } & AnnotationReorderResult) |{ type: 'annotations.restored'; page: PageRef; origin: EventOrigin; annotations: Annotation[]; meta: AnnotationListMutationMeta; } | ({ type: 'annotations.flattened'; origin: EventOrigin; } & AnnotationFlattenResult) | ({ type: 'pages.reordered'; origin: EventOrigin} & PageReorderResult) | ({ type: 'pages.rotated'; pages: PageRef[]; rotation: PdfRotation; origin: EventOrigin; } & PageRotateResult) | ({ type: 'pages.deleted'; pages: PageRef[]; origin: EventOrigin; } & PageDeleteResult) | ({ type: 'pages.inserted'; origin: EventOrigin} & PageInsertResult) | ({ type: 'pages.restored'; origin: EventOrigin} & PageRestoreResult) | ({ type: 'pages.named'; name: string; page: PageRef | null; origin: EventOrigin; } & PageNameResult) | ({ type: 'attachments.created'; origin: EventOrigin} & AttachmentCreateResult) | ({ type: 'attachments.deleted'; origin: EventOrigin; deleted: AttachmentRef | null; } & AttachmentDeleteResult) |{ type: 'fonts.changed'; origin: EventOrigin; } | ({ type: 'attachments.restored'; origin: EventOrigin} & AttachmentRestoreResult) | ({ type: 'metadata.updated'; origin: EventOrigin} & MetadataUpdateResult) | ({ type: 'metadata.customUpdated'; origin: EventOrigin} & CustomMetadataUpdateResult) | ({ type: 'outline.created'; origin: EventOrigin} & OutlineCreateResult) | ({ type: 'outline.updated'; origin: EventOrigin} & OutlineUpdateResult) | ({ type: 'outline.moved'; origin: EventOrigin} & OutlineMoveResult) | ({ type: 'outline.deleted'; origin: EventOrigin; deleted: OutlineItemRef[]; } & OutlineDeleteResult) | ({ type: 'outline.restored'; origin: EventOrigin; } & OutlineRestoreResult) | ({ type: 'forms.valueSet'; origin: EventOrigin} & FormSetValueResult) | ({ type: 'forms.repaired'; origin: EventOrigin} & FormRepairResult) | ({ type: 'forms.created'; origin: EventOrigin} & FormFieldCreateResult) | ({ type: 'forms.updated'; origin: EventOrigin} & FormFieldUpdateResult) | ({ type: 'forms.deleted'; origin: EventOrigin; deleted: FormFieldRef | null; } & FormFieldDeleteResult) |{ type: 'forms.restored'; origin: EventOrigin; field: FormField; widgets: WidgetAnnotation[]; meta: FormMutationMeta; } | ({ type: 'forms.widgetAdded'; origin: EventOrigin} & FormWidgetLinkResult) | ({ type: 'forms.widgetRemoved'; origin: EventOrigin} & FormWidgetLinkResult) | ({ type: 'forms.widgetDeleted'; origin: EventOrigin} & FormWidgetDeleteResult) | ({ type: 'forms.widgetRestored'; origin: EventOrigin; } & FormWidgetRestoreResult) | ({ type: 'forms.widgetUpdated'; origin: EventOrigin} & FormWidgetUpdateResult) | ({ type: 'forms.widgetsReordered'; origin: EventOrigin; } & FormWidgetsReorderResult) | ({ type: 'forms.calculationsReordered'; origin: EventOrigin; } & FormCalculationsReorderResult) | ({ type: 'pages.flattened'; pages: PageRef[]; usage: PageFlattenUsage; origin: EventOrigin; } & PageFlattenResult) | ({ type: 'redaction.applied'; origin: EventOrigin; } & RedactionApplyResult) | ({ type: 'signatures.prepared'; field: FormFieldRef; origin: EventOrigin; } & SignaturePrepared) | ({ type: 'signatures.completed'; signingId: string; origin: EventOrigin; } & SignatureCompleteResult) |{ type: 'signatures.cancelled'; signingId: string; origin: EventOrigin; } | ({ type: 'signatures.validationInfoAdded'; origin: EventOrigin; } & ValidationInfoAddResult) |{ type: 'document.versioned'; version: BaseVersionInfo; origin: EventOrigin; } |{ type: 'stream.desynced'; reason: 'backlog-overflow' | 'unknown-change'; at: string; } ; DocumentGate [SvelteComponent] (from packages/framework/svelte/src/runtime/DocumentGate.svelte): props DocumentGateProps DocumentGateProps [InterfaceDeclaration] (from packages/framework/svelte/src/runtime/props.ts): export interface DocumentGateProps{ fallback?: Snippet; locked?: Snippet<[document: LockedDocumentInfo]>; error?: Snippet<[document: FailedDocumentInfo]>; children?: Snippet; } DocumentHandle [InterfaceDeclaration] (from packages/engine/core/src/engine/DocumentHandle.ts): export interface DocumentHandle{ readonly id: string; readonly security: DocumentSecurityService; readonly metadata: MetadataService; readonly annotations: DocumentAnnotationsService; readonly actions: DocumentActionsService; readonly attachments: DocumentAttachmentsService; readonly forms: DocumentFormsService; readonly fonts: DocumentFontsService; readonly outline: DocumentOutlineService; readonly search: DocumentSearchService; readonly render: DocumentRenderService; readonly pages: DocumentPagesService; readonly redaction: DocumentRedactionService; readonly signatures: DocumentSignaturesService; readonly events: DocumentEventStream; readonly objectNumbers: ObjectNumberPool; readonly grant?: DocumentGrant; page(ref: PageRef): PageHandle; apply(change: Change, options?: WriteOptions): AbortablePromise; with(facts: CallFacts): DocumentHandle; setWorkingSet(view: string, pages: readonly WorkingSetPage[]): void; download(options?: DownloadOptions): AbortablePromise; close(): AbortablePromise; } DocumentInfo [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DocumentInfo{ readonly id: string; readonly name?: string; readonly status: DocumentStatus; readonly pageCount: number; readonly hasUnsavedChanges: boolean; readonly passwordProvided?: boolean; readonly error?: PluginErrorInfo; readonly openRequest?: GrantOpenRequest; readonly identityRequest?: VisitorIdentityRequest; } DocumentLockedEvent [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DocumentLockedEvent{ readonly documentId: string; readonly passwordProvided: boolean; } DocumentMeta [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DocumentMeta{ readonly id: string; readonly instanceId: string; readonly name?: string; readonly pageCount: number; readonly pages: readonly PageLayout[]; readonly pageLabels: readonly PageLabelSection[]; readonly pendingPages: ReadonlyMap; readonly pagesSequence: number; readonly renderPolicy: EngineRenderPolicy; readonly hasUnsavedChanges: boolean; readonly identityRequest?: VisitorIdentityRequest; readonly openRequest?: GrantOpenRequest; } DocumentMetadata [InterfaceDeclaration] (from packages/engine/core/src/dto/DocumentMetadata.ts): export interface DocumentMetadata{ title: string | null; author: string | null; subject: string | null; keywords: string | null; producer: string | null; creator: string | null; createdAt: IsoDateTime | null; modifiedAt: IsoDateTime | null; trapped: DocumentMetadataTrapped; } DocumentOpenFailedEvent [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DocumentOpenFailedEvent{ readonly documentId: string; readonly error: PluginErrorInfo; } DocumentOpenedEvent [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DocumentOpenedEvent{ readonly documentId: string; readonly info: DocumentInfo; } DocumentPagesChangedEvent [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DocumentPagesChangedEvent{ readonly documentId: string; readonly pagesSequence: number; readonly pages: readonly PageInfo[]; } DocumentScope [SvelteComponent] (from packages/framework/svelte/src/runtime/DocumentScope.svelte): props DocumentScopeProps DocumentScopeProps [InterfaceDeclaration] (from packages/framework/svelte/src/runtime/props.ts): export interface DocumentScopeProps{ id: string; children?: Snippet; } DocumentStatus [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type DocumentStatus = 'loading' | 'locked' | 'ready' | 'error'; DocumentUnsavedChangesChangedEvent [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DocumentUnsavedChangesChangedEvent{ readonly documentId: string; readonly hasUnsavedChanges: boolean; } DocumentsCapability [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DocumentsCapability{ open(source: OpenSource, options?: OpenDocumentOptions): Promise; canOpenFiles(): boolean; retry(id: string, options?: RetryOptions): Promise; identify(id: string, answers: VisitorAnswers): Promise; declineIdentity(id: string): void; rename(id: string, name: string): void; openAll(documents: readonly InitialDocument[]): readonly string[]; unlock(id: string, options: UnlockOptions): Promise; close(id: string): Promise; closeAll(): Promise; setActive(id: string): void; getActiveId(): string | null; getActive(): DocumentInfo | null; list(): readonly DocumentInfo[]; get(id?: string): DocumentInfo | null; has(id: string): boolean; getCount(): number; getOrder(): readonly string[]; setOrder(ids: readonly string[]): void; move(id: string, toIndex: number): void; swap(id: string, otherId: string): void; download(id?: string, options?: DownloadOptions): Promise; downloadLayer(id?: string, options?: OperationOptions): Promise; canDownload(id?: string): boolean; preparePrint(id?: string, options?: PrintOptions): Promise; print(id?: string, options?: PrintOptions): Promise; getPrintQuality(id?: string): PrintQuality | null; canPrint(id?: string): boolean; listPages(id?: string): readonly PageInfo[]; getPage(page: PageRef | number, id?: string): PageInfo | null; getPageIndex(ref: PageRef, id?: string): number; getRevision(id?: string): number; readonly onOpened: EventHook; readonly onOpenFailed: EventHook; readonly onLocked: EventHook; readonly onClosed: EventHook; readonly onActiveChanged: EventHook; readonly onPagesChanged: EventHook; readonly onUnsavedChangesChanged: EventHook; } DocumentsState [InterfaceDeclaration] (from packages/core/main/src/documents-state.ts): export interface DocumentsState{ readonly documents: readonly DocumentInfo[]; readonly activeId: string | null; } DocumentsToken [VariableDeclaration] (from packages/core/main/src/types.ts): DocumentsToken: CapabilityToken ={ name: 'documents'} DownloadOptions [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface DownloadOptions extends OperationOptions{ readonly mode?: PdfSaveMode; } Engine [InterfaceDeclaration] (from packages/engine/core/src/engine/Engine.ts): export interface Engine{ readonly canOpenFiles: boolean; open(input: OpenInput, options?: OpenOptions): AbortablePromise; destroy(): AbortablePromise; } EngineFactory [TypeAliasDeclaration] (from packages/engine/core/src/engine/Engine.ts): export type EngineFactory = () => Engine; EngineRenderPolicy [TypeAliasDeclaration] (from packages/engine/core/src/engine/DocumentRenderService.ts): export type EngineRenderPolicy = |{ readonly kind: 'continuous'} |{ readonly kind: 'lattice'; readonly fullPage:{ readonly widths: readonly number[]} ; readonly tiles?:{ readonly tileSizes: readonly number[]; readonly scales: readonly number[]; } ; readonly appearances?:{ readonly scales: readonly number[]} ; readonly maxRenderPixels?: number; readonly formats: readonly ('webp' | 'png')[]; readonly background: 'white'; readonly enforced: boolean; } ; EpdfTheme [TypeAliasDeclaration] (from packages/framework/web/src/theme.ts): export type EpdfTheme = Intersection<{ [Name in EpdfSettingVariable]: ThemeBranch< ThemePath, ThemeValue >; } [EpdfSettingVariable] >; EventHook [TypeAliasDeclaration] (from packages/core/main/src/event-hook.ts): export type EventHook = ( listener: (event: T) => void, options?:{ signal?: AbortSignal} , ) => Unsubscribe; EventHookSource [InterfaceDeclaration] (from packages/core/main/src/event-hook.ts): export interface EventHookSource{ readonly on: EventHook; emit(event: T): void; destroy(): void; } EventOrigin [InterfaceDeclaration] (from packages/engine/core/src/events/DocumentEvent.ts): export interface EventOrigin{ kind: 'local' | 'remote'; sessionId: string; subject: string | null; at: string; serverSequence: number | null; transaction?:{ id: string; index: number; count: number} ; undoOf?: string; } FailedDocumentInfo [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface FailedDocumentInfo extends DocumentInfo{ readonly status: 'error'; readonly error: PluginErrorInfo; } Font [InterfaceDeclaration] (from packages/engine/core/src/dto/DocumentFonts.ts): export interface Font{ name: FontName; source: FontSource; builtIn: boolean; familyName: string; weight: number; italic: boolean; postScriptName: string | null; canChoose: boolean; restrictions: FontRestriction[]; programs: FontProgram[]; } FontList [InterfaceDeclaration] (from packages/engine/core/src/dto/DocumentFonts.ts): export interface FontList{ fonts: Font[]; fallbacks: FontName[]; lastResort: FontProgram; } FontName [TypeAliasDeclaration] (from packages/engine/core/src/annotation/primitives.ts): export type FontName = StandardFont | (string &{ } ); FontProgram [InterfaceDeclaration] (from packages/engine/core/src/dto/DocumentFonts.ts): export interface FontProgram{ displaySha256: string | null; sourceSha256: string | null; embedded: 'whole' | 'subset' | 'none'; format: FontFormat | null; embeddingPermission: FontEmbeddingPermission | null; canDownload: boolean; } FontProgramInfo [InterfaceDeclaration] (from packages/engine/core/src/dto/DocumentFonts.ts): export interface FontProgramInfo extends FontProgram{ covers: CodePointRange[]; ascent: number; descent: number; } FontResolution [InterfaceDeclaration] (from packages/engine/core/src/dto/DocumentFonts.ts): export interface FontResolution{ runs: ResolvedFontRun[]; missingCharacters: string[]; } FontResolveRequest [InterfaceDeclaration] (from packages/engine/core/src/dto/DocumentFonts.ts): export interface FontResolveRequest{ annotation?: AnnotationRef; runs: FontResolveRun[]; } FontRestriction [TypeAliasDeclaration] (from packages/engine/core/src/dto/DocumentFonts.ts): export type FontRestriction = | 'subset' | 'not-embedded' | 'preview-and-print' | 'unsupported-format' | 'no-unicode-map' | 'not-served'; FontSource [TypeAliasDeclaration] (from packages/engine/core/src/dto/DocumentFonts.ts): export type FontSource = 'standard' | 'engine' | 'document'; GlobalState [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface GlobalState{ readonly core: CoreState; readonly plugins: Readonly>; } GrantOpenRequest [TypeAliasDeclaration] (from packages/engine/core/src/dto/GrantVisitor.ts): export type GrantOpenRequest = |{ readonly kind: 'passphrase'; readonly passphraseProvided: boolean} |{ readonly kind: 'identity'; readonly request: VisitorIdentityRequest} ; HeldChange [InterfaceDeclaration] (from packages/core/main/src/changes.ts): export interface HeldChange{ readonly open: boolean; readonly change: PendingChange | null; set(ops: readonly ChangeOp[], undo?: readonly PredictedOp[]): void; send(): PendingChange | null; cancel(): void; } HistoryOptions [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface HistoryOptions{ readonly history?: false; } HoldOptions [InterfaceDeclaration] (from packages/core/main/src/changes.ts): export interface HoldOptions{ readonly merge?: string; } HostClock [InterfaceDeclaration] (from packages/core/main/src/clock.ts): export interface HostClock{ now(): number; after(ms: number, run: () => void): Cancel; nextFrame?(run: (timeMs: number) => void): Cancel; } HostFetch [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type HostFetch = ( url: string, init:{ readonly signal: AbortSignal} , ) => Promise<{ readonly ok: boolean; readonly status: number; arrayBuffer(): Promise; } >; HostFontProgram [InterfaceDeclaration] (from packages/core/main/src/measurer.ts): export interface HostFontProgram{ readonly family: string; readonly weight: number; readonly style: 'normal' | 'italic'; load(): Promise; } HostPrinter [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface HostPrinter{ readonly needsTap?: boolean; stage( sheets: readonly PrintSheet[], options:{ readonly name: string; readonly signal?: AbortSignal} , ): Promise; stagePdf?( pdf: Uint8Array, options:{ readonly name: string; readonly signal?: AbortSignal} , ): Promise; } HostTextMeasurer [InterfaceDeclaration] (from packages/core/main/src/measurer.ts): export interface HostTextMeasurer{ ready(program: HostFontProgram): boolean; refused(program: HostFontProgram): boolean; width(program: HostFontProgram, text: string, rtl: boolean): number; onChange(listener: () => void): () => void; } IconAccent [InterfaceDeclaration] (from packages/core/main/src/command-types.ts): export interface IconAccent{ readonly primary?: string; readonly secondary?: string; } Identity [InterfaceDeclaration] (from packages/engine/core/src/auth/scope/types.ts): export interface Identity{ readonly userId?: string; readonly displayName?: string; readonly email?: string; readonly title?: string; readonly organization?: string; readonly organizationalUnit?: string; readonly groupId?: string; } InitialDocument [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type InitialDocument ={ source: OpenSource; active?: boolean} & Omit< OpenDocumentOptions, 'activate' | 'signal' >; Kernel [InterfaceDeclaration] (from packages/core/main/src/kernel.ts): export interface Kernel extends SettingsApi{ readonly engine: Engine; readonly documents: DocumentsCapability; capability(token: CapabilityToken, documentId?: string): T; tryCapability(token: CapabilityToken, documentId?: string): T | null; scopeOf(token: CapabilityToken): PluginScope; settingsOf(token: CapabilityToken): SettingsApi>; subscribe(listener: () => void): Unsubscribe; getState(): GlobalState; getStatus(): KernelStatus; start(): Promise; destroy(): Promise; } KernelProvider [SvelteComponent] (from packages/framework/svelte/src/runtime/KernelProvider.svelte): props KernelProviderProps KernelProviderProps [InterfaceDeclaration] (from packages/framework/svelte/src/runtime/props.ts): export interface KernelProviderProps{ kernel: Kernel; children?: Snippet; } KernelStatus [TypeAliasDeclaration] (from packages/core/main/src/kernel.ts): export type KernelStatus = | 'created' | 'starting' | 'started' | 'failed' | 'destroying' | 'destroyed'; LatestCancellation [InterfaceDeclaration] (from packages/core/main/src/lanes.ts): export interface LatestCancellation{ readonly runId: string; readonly reason: string; } LatestLane [InterfaceDeclaration] (from packages/core/main/src/lanes.ts): export interface LatestLane{ readonly running: boolean; run(fn: (run: LatestRun) => Promise, options?: OperationOptions): Promise; cancel(reason?: unknown): void; } LatestRun [InterfaceDeclaration] (from packages/core/main/src/lanes.ts): export interface LatestRun{ readonly id: string; readonly signal: AbortSignal; readonly superseded: boolean; commit(fn: () => void): boolean; } LockedDocumentInfo [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface LockedDocumentInfo extends DocumentInfo{ readonly status: 'locked'; readonly passwordProvided: boolean; } MaybeGetter [TypeAliasDeclaration] (from packages/framework/svelte/src/runtime/values.svelte.ts): export type MaybeGetter = T | (() => T); MetadataPatch [InterfaceDeclaration] (from packages/engine/core/src/dto/MetadataPatch.ts): export interface MetadataPatch{ title?: string | null; author?: string | null; subject?: string | null; keywords?: string | null; producer?: string | null; creator?: string | null; createdAt?: DateInput | null; modifiedAt?: DateInput | null; trapped?: DocumentMetadataTrapped; } MetadataUpdateResult [InterfaceDeclaration] (from packages/engine/core/src/mutation/MetadataUpdateResult.ts): export interface MetadataUpdateResult{ metadata: DocumentMetadata; meta: MutationMeta; } Mirror [InterfaceDeclaration] (from packages/core/main/src/mirror.ts): export interface Mirror{ get(): V; view(): V; getStatus(): ResourceStatus; ensureLoaded(): Promise; refresh(): Promise; settled(): Promise; } MirrorChange [InterfaceDeclaration] (from packages/core/main/src/mirror.ts): export interface MirrorChange{ readonly cause: 'load' | 'event'; readonly event: DocumentEvent | null; readonly pages: 'all' | readonly PageRef[] | null; readonly previous: V; readonly next: V; } MirrorReload [InterfaceDeclaration] (from packages/core/main/src/mirror.ts): export interface MirrorReload{ readonly [RELOAD]: 'all' | readonly PageRef[]; } MirrorSpec [InterfaceDeclaration] (from packages/core/main/src/mirror.ts): export interface MirrorSpec{ readonly name: string; readonly initial: () => V; readonly readable?: () => boolean; readonly onDemand?: true; load(doc: DocumentHandle, signal: AbortSignal): Promise<{ value: V; cursor?: number} >; fold(value: V, event: DocumentEvent): V | MirrorReload; predict?(value: V, op: PredictedOp): V; loadPages?( doc: DocumentHandle, pages: readonly PageRef[], signal: AbortSignal, ): Promise<(value: V) => V>; readonly onChanged?: (change: MirrorChange) => void; } NoSettings [InterfaceDeclaration] (from packages/core/main/src/settings.ts): export interface NoSettings{ readonly [noSettings]: true; } OpenDocumentOptions [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type OpenDocumentOptions = OpenOptions &{ readonly activate?: boolean; readonly name?: string; readonly signal?: AbortSignal; } ; OpenDocumentResult [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface OpenDocumentResult{ readonly document: DocumentInfo; } OpenInput [TypeAliasDeclaration] (from packages/engine/core/src/dto/OpenInput.ts): export type OpenInput = | OpenInputBytes | OpenInputLayerBytes | OpenInputLayerFile | OpenInputById | OpenInputToken | OpenInputGrant; OpenOptions [InterfaceDeclaration] (from packages/engine/core/src/dto/OpenInput.ts): export interface OpenOptions{ password?: string; scope?: ReadonlyArray; identity?: Identity; } OpenSource [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type OpenSource = | OpenInput | UrlSource | ((signal: AbortSignal) => OpenInput | UrlSource | Promise); OperationOptions [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface OperationOptions{ readonly signal?: AbortSignal; } PageContextValue [TypeAliasDeclaration] (from packages/framework/svelte/src/runtime/page.ts): export type PageContextValue = PageContext; PageDeleteResult [InterfaceDeclaration] (from packages/engine/core/src/mutation/PageDeleteResult.ts): export interface PageDeleteResult{ layout: PageListSnapshot; meta: MutationMeta; } PageDestination [TypeAliasDeclaration] (from packages/engine/core/src/dto/PdfDestination.ts): export type PageDestination = |{ kind: 'xyz'; page: PageRef; x: number | null; y: number | null; zoom: number | null} |{ kind: 'fit'; page: PageRef} |{ kind: 'fitH'; page: PageRef; y: number | null} |{ kind: 'fitV'; page: PageRef; x: number | null} |{ kind: 'fitR'; page: PageRef; x: number; y: number; width: number; height: number} |{ kind: 'fitB'; page: PageRef} |{ kind: 'fitBH'; page: PageRef; y: number | null} |{ kind: 'fitBV'; page: PageRef; x: number | null} ; PageHandle [InterfaceDeclaration] (from packages/engine/core/src/engine/PageHandle.ts): export interface PageHandle{ readonly ref: PageRef; readonly annotations: PageAnnotationsService; readonly forms: PageFormsService; readonly text: PageTextService; readonly render: PageRenderService; readonly measure: PageMeasureService; } PageImageHandle [InterfaceDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export interface PageImageHandle extends PageImageResult, ImageSource{ } PageImageObjectUrl [InterfaceDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export interface PageImageObjectUrl{ url: string; revoke(): void; } PageImageOptions [InterfaceDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export interface PageImageOptions< C extends Coordinates = PageCoordinates, > extends PageRenderOptions{ format?: PageRenderEncodedFormat; quality?: number; } PageInfo [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type PageInfo = PageLayout; PageInsertBlankSpec [InterfaceDeclaration] (from packages/engine/core/src/mutation/PageInsertBlankInput.ts): export interface PageInsertBlankSpec{ size: PdfSize; count?: number; } PageInsertResult [InterfaceDeclaration] (from packages/engine/core/src/mutation/PageInsertResult.ts): export interface PageInsertResult{ insertedPages: PageRef[]; layout: PageListSnapshot; meta: MutationMeta; } PageLayerRights [InterfaceDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export interface PageLayerRights{ readonly annotations: boolean; readonly formFields: boolean; } PageLayout [InterfaceDeclaration] (from packages/engine/core/src/dto/PageLayout.ts): export interface PageLayout{ index: number; ref: PageRef; label: string | null; size: PdfSize; rotation: PdfRotation; userUnit: number; tabOrder: PageTabOrder | null; boxes: PageBoxes; pdfCropBox: PdfRect; actions?: PdfPageActions; viewports?: PageMeasurementViewport[]; } PageMirror [InterfaceDeclaration] (from packages/core/main/src/page-mirror.ts): export interface PageMirror{ get(page: PageRef): V | undefined; view(page: PageRef): V | undefined; getStatus(page: PageRef): ResourceStatus; ensureLoaded(page: PageRef, options?: OperationOptions): Promise; refresh(page?: PageRef): Promise; } PageMirrorChange [InterfaceDeclaration] (from packages/core/main/src/page-mirror.ts): export interface PageMirrorChange{ readonly page: PageRef; readonly cause: 'load' | 'event' | 'drop'; readonly event: DocumentEvent | null; readonly previous: V | undefined; readonly next: V | undefined; } PageMirrorSpec [InterfaceDeclaration] (from packages/core/main/src/page-mirror.ts): export interface PageMirrorSpec{ readonly name: string; load(doc: DocumentHandle, page: PageRef, signal: AbortSignal): Promise; affected(event: DocumentEvent): readonly PageRef[] | 'all' | null; fold?(value: V, event: DocumentEvent, page: PageRef): V | 'reload'; predict?(value: V, op: PredictedOp, page: PageRef): V; readonly onChanged?: (change: PageMirrorChange) => void; } PageObjectNumber [TypeAliasDeclaration] (from packages/engine/core/src/identity/PageObjectNumber.ts): export type PageObjectNumber = number; PagePosition [TypeAliasDeclaration] (from packages/engine/core/src/mutation/ListPosition.ts): export type PagePosition = ListPosition; PageRaster [InterfaceDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export interface PageRaster{ width: number; height: number; stride: number; color: 'rgba8'; premultipliedAlpha: false; data: ArrayBuffer; } PageRef [TypeAliasDeclaration] (from packages/engine/core/src/identity/PageRef.ts): export type PageRef ={ kind: 'objectNumber'; objectNumber: PageObjectNumber} ; PageRenderLayers [InterfaceDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export interface PageRenderLayers{ readonly includeAnnotations: boolean; readonly includeFormFields: boolean; } PageRenderOptions [InterfaceDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export interface PageRenderOptions{ target?: PageRenderTarget; viewport?: PageRenderViewport; rotation?: PdfRotation; background?: PageRenderBackground; includeAnnotations?: boolean; includeFormFields?: boolean; usage?: PageFlattenUsage; maxOutputPixels?: number; } PageRenderTarget [TypeAliasDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export type PageRenderTarget = |{ kind: 'page'} |{ kind: 'rect'; rect: C['box']; } ; PageRenderViewport [TypeAliasDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export type PageRenderViewport = | PageScreenViewport |{ kind: 'thumbnail'; } |{ kind: 'dpi'; dpi: PrintDpi; } ; PageReorderResult [InterfaceDeclaration] (from packages/engine/core/src/mutation/PageReorderResult.ts): export interface PageReorderResult{ pages: PageRef[]; layout: PageListSnapshot; meta: MutationMeta; } PageRotateResult [InterfaceDeclaration] (from packages/engine/core/src/mutation/PageRotateResult.ts): export interface PageRotateResult{ layout: PageListSnapshot; meta: MutationMeta; } PdfDestination [TypeAliasDeclaration] (from packages/engine/core/src/dto/PdfDestination.ts): export type PdfDestination = |{ kind: 'xyz'; page: PageRef; left: number | null; top: number | null; zoom: number | null; } |{ kind: 'fit'; page: PageRef} |{ kind: 'fitH'; page: PageRef; top: number | null} |{ kind: 'fitV'; page: PageRef; left: number | null} |{ kind: 'fitR'; page: PageRef; left: number; bottom: number; right: number; top: number; } |{ kind: 'fitB'; page: PageRef} |{ kind: 'fitBH'; page: PageRef; top: number | null} |{ kind: 'fitBV'; page: PageRef; left: number | null} ; PdfRect [InterfaceDeclaration] (from packages/engine/core/src/geometry/primitives.ts): export interface PdfRect{ left: number; bottom: number; right: number; top: number; } PdfRotation [TypeAliasDeclaration] (from packages/engine/core/src/geometry/primitives.ts): export type PdfRotation = 0 | 90 | 180 | 270; PdfSaveMode [TypeAliasDeclaration] (from packages/engine/core/src/dto/PdfSaveMode.ts): export type PdfSaveMode = 'incremental' | 'rewrite'; PdfSize [InterfaceDeclaration] (from packages/engine/core/src/geometry/primitives.ts): export interface PdfSize{ width: number; height: number; } PendingChange [InterfaceDeclaration] (from packages/core/main/src/changes.ts): export interface PendingChange{ readonly opId: string; readonly label: ChangeLabel; readonly undoOf: string | null; readonly merge: string | null; readonly shows: readonly PredictedOp[]; readonly undo: readonly PredictedOp[]; readonly history: boolean; readonly held: boolean; readonly result: Promise; } PendingMeta [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface PendingMeta{ readonly id: string; readonly name?: string; readonly status: 'loading' | 'locked' | 'error'; readonly passwordProvided?: boolean; readonly error?: unknown; readonly openRequest?: GrantOpenRequest; } PendingPage [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type PendingPage = |{ readonly kind: 'blank'} |{ readonly kind: 'own'} |{ readonly kind: 'copy'; readonly of: PageRef} ; Permission [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type Permission = DocCapability | 'annotations:create' | PluginPermission; PermissionDenied [ClassDeclaration] (from packages/engine/core/src/auth/scope/errors.ts): export class PermissionDenied extends EngineError{ override readonly name: string = 'PermissionDenied'; constructor( public readonly required: string, public readonly context?: string, public readonly anyOf?: readonly string[], public readonly refs?: readonly AnnotationRef[], ){ super( EngineErrorCode.Forbidden, `permission denied${ context ? ` (${ context} )` : ''} : ${ anyOf ? `one of ${ anyOf.join(', ')} ` : required} ${ refs ? ` for ${ refs.length} annotation${ refs.length === 1 ? '' : 's'} ` : ''} `, { details:{ required, ...(context === undefined ?{ } :{ context} ), ...(anyOf === undefined ?{ } :{ anyOf: [...anyOf]} ), ...(refs === undefined ?{ } :{ refs: [...refs]} ), } , } , ); } } PluginClock [InterfaceDeclaration] (from packages/core/main/src/clock.ts): export interface PluginClock{ after(ms: number, run: () => void): Cancel; nextFrame(run: (timeMs: number) => void): Cancel; readonly hasFrames: boolean; } PluginContext [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface PluginContext{ readonly id: string; readonly instanceId: string; readonly documentId?: string; readonly engine: Engine; readonly doc: DocumentHandle; documentHandle(documentId?: string): DocumentHandle | null; document(): DocumentMeta | null; getPage(page: PageRef | number): PageInfo | null; pageOf(page: PageRef | number): PageInfo; assertPageRef(ref: PageRef): void; allows(permission: Permission): boolean; assertAllowed(permission: Permission, operation: string): void; allowsField(action: 'fill' | 'sign', field:{ readonly groupId: string | null} ): boolean; assertAllowedField( action: 'fill' | 'sign', field:{ readonly groupId: string | null} , operation: string, ): void; get(token: CapabilityToken): T; tryGet(token: CapabilityToken): T | null; forDocument(token: CapabilityToken, documentId: string): T; tryForDocument(token: CapabilityToken, documentId: string): T | null; readonly state: StateCell; readonly settings: () => Settings; notify(): void; storeChangeCount(): number; watch( select: () => R, handler: (value: R, previous: R) => void, isEqual?: (left: R, right: R) => boolean, ): Unsubscribe; waitFor(predicate: () => boolean, options?: OperationOptions): Promise; mirror(spec: MirrorSpec): Mirror; pageMirror(spec: PageMirrorSpec): PageMirror; readonly changes: ChangeQueue; readonly events:{ source():{ readonly on: EventHook; emit(event: T): void; destroy(): void} ; } ; listen(source: Subscribable, listener: (event: T) => void): void; cleanup(fn: () => void | Promise): void; readonly clock: PluginClock; readonly measurer: HostTextMeasurer | null; onSettle(flush: (signal: AbortSignal) => Promise | void): void; aroundDownload(wrap: (read: () => Promise) => Promise): void; aroundPrint(wrap: (print: () => Promise) => Promise): void; acquire( get: (lifetime: AbortSignal) => Promise, release: (resource: R) => void | Promise, ): Promise; cancellable(signal: AbortSignal | undefined, task: Promise): Promise; latest(key: string): import('./lanes').LatestLane; serialQueue(key?: string): SerialQueue; } PluginDefinition [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface PluginDefinition< State = unknown, Capability = unknown, PluginSettings extends object = NoSettings, >{ readonly id: string; readonly token?: CapabilityToken; readonly scope?: PluginScope; readonly requires?: ReadonlyArray>; readonly optional?: ReadonlyArray>; readonly resolvesAnyCapability?: true; readonly state?: () => State; readonly settings?: SettingsDeclaration; readonly create: NoInfer< (ctx: PluginContext) =>{ api: Capability; connect?: () => void} >; readonly inScope?: NoInfer<(api: Capability, documentId: string) => Capability>; } PluginError [ClassDeclaration] (from packages/core/main/src/errors.ts): export class PluginError extends Error{ override readonly name = 'PluginError'; readonly code: PluginErrorCode; readonly capability: string; readonly permission: string | null; readonly details: unknown; constructor( code: PluginErrorCode, capability: string, message: string, options:{ cause?: unknown; details?: unknown; permission?: string | null} ={ } , ){ super(message); if (options.cause !== undefined) (this as{ cause?: unknown} ).cause = options.cause; this.code = code; this.capability = capability; this.permission = options.permission ?? null; this.details = options.details; } } PluginErrorCode [TypeAliasDeclaration] (from packages/core/main/src/errors.ts): export type PluginErrorCode = | 'permission-denied' | 'unsupported' | 'not-found' | 'not-ready' | 'invalid-input' | 'conflict' | 'instance-closed' | 'operation-cancelled' | 'operation-failed'; PluginErrorInfo [InterfaceDeclaration] (from packages/core/main/src/errors.ts): export interface PluginErrorInfo{ readonly code: PluginErrorCode; readonly message: string; readonly capability: string; readonly permission: string | null; } PluginPermission [TypeAliasDeclaration] (from packages/engine/core/src/auth/scope/types.ts): export type PluginPermission = keyof PluginPermissions & string; PluginPermissions [InterfaceDeclaration] (from packages/engine/core/src/auth/scope/types.ts): export interface PluginPermissions{ } PluginScope [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type PluginScope = 'workspace' | 'document'; PredictedOp [TypeAliasDeclaration] (from packages/core/main/src/changes.ts): export type PredictedOp = | ChangeOp |{ readonly type: 'annotations.restore'; readonly annotation: Annotation; readonly index: number; } |{ readonly type: 'forms.restore'; readonly field: FormField; readonly widgets: readonly WidgetAnnotation[]; } |{ readonly type: 'forms.restoreWidget'; readonly widget: WidgetAnnotation; readonly field: FormField | null; } |{ readonly type: 'outline.restore'; readonly items: readonly OutlineItem[]; readonly index: number; } |{ readonly type: 'attachments.restore'; readonly attachment: Attachment; } |{ readonly type: 'pages.restore'; readonly pages: readonly RestoredPage[]; } |{ readonly type: 'pages.relabel'; readonly labels: readonly PageLabelSection[]; } ; PreparedPrint [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface PreparedPrint{ readonly quality: PrintQuality; readonly pageCount: number; readonly needsTap: boolean; print(options?: OperationOptions): Promise; destroy(): void; } PrintDpi [TypeAliasDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export type PrintDpi = 150 | 300; PrintOptions [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface PrintOptions extends OperationOptions{ readonly pages?: readonly PageRef[]; readonly includeAnnotations?: boolean; readonly onProgress?: (progress: PrintProgress) => void; } PrintProgress [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface PrintProgress{ readonly pagesRendered: number; readonly pageCount: number; } PrintQuality [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type PrintQuality = |{ readonly kind: 'pdf'} |{ readonly kind: 'images'; readonly dpi: PrintDpi} ; PrintSheet [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface PrintSheet{ readonly image: Blob; readonly widthPt: number; readonly heightPt: number; } PromiseMemberOf [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type PromiseMemberOf = | PromiseMethodOf |{ [Key in keyof Capability & string]-?: Capability[Key] extends (...args: never[]) => unknown ? never : Capability[Key] extends object ? `${ Key} .${ PromiseMethodOf} ` : never; } [keyof Capability & string]; PromiseMembers [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type PromiseMembers ={ readonly [Path in PromiseMemberOf]: true} ; ResourceStatus [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type ResourceStatus = 'idle' | 'loading' | 'ready' | 'forbidden' | 'error'; RestoredPage [InterfaceDeclaration] (from packages/engine/core/src/pages/predict.ts): export interface RestoredPage{ readonly page: PageLayout; readonly after: PageRef | null; } RetryOptions [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface RetryOptions extends OperationOptions{ readonly passphrase?: string; readonly visitorIdentity?: VisitorAnswers; } SendChange [TypeAliasDeclaration] (from packages/core/main/src/changes.ts): export type SendChange = ( doc: DocumentHandle, write:{ readonly opId: string} , ) => PromiseLike; SerialQueue [InterfaceDeclaration] (from packages/core/main/src/serial-queue.ts): export interface SerialQueue{ (operation: () => Promise, options?: OperationOptions): Promise; idle(): Promise; } SettingLock [InterfaceDeclaration] (from packages/core/main/src/settings.ts): export interface SettingLock{ readonly by: string; readonly reasonKey?: string; } Settings [InterfaceDeclaration] (from packages/core/main/src/settings.ts): export interface Settings{ get(): T; readonly api: SettingsApi; } SettingsApi [InterfaceDeclaration] (from packages/core/main/src/settings.ts): export interface SettingsApi{ getSettings(): T; updateSettings(changes: DeepPartial): void; resetSettings(): void; readonly onSettingsChanged: EventHook>; } SettingsChangedEvent [InterfaceDeclaration] (from packages/core/main/src/settings.ts): export interface SettingsChangedEvent{ readonly settings: T; readonly changedKeys: readonly (keyof T)[]; } SettingsDeclaration [InterfaceDeclaration] (from packages/core/main/src/settings.ts): export interface SettingsDeclaration{ readonly defaults: T; readonly registered?: DeepPartial | undefined; readonly whole?: readonly SettingPath[]; } SettingsOf [TypeAliasDeclaration] (from packages/core/main/src/settings.ts): export type SettingsOf = Capability extends{ getSettings(): infer T} ? T : never; SettingsReader [InterfaceDeclaration] (from packages/framework/svelte/src/runtime/state.svelte.ts): export interface SettingsReader{ (): Readonly; (select: (settings: Settings) => Selected): CurrentValue; } SettledChange [TypeAliasDeclaration] (from packages/core/main/src/changes.ts): export type SettledChange = |{ readonly change: PendingChange; readonly status: 'applied'; readonly result: ChangeResult} |{ readonly change: PendingChange; readonly status: 'refused'; readonly error: PluginError} ; SliceChange [InterfaceDeclaration] (from packages/core/main/src/store.ts): export interface SliceChange{ readonly next: S; readonly previous: S; } SliceLease [InterfaceDeclaration] (from packages/core/main/src/store.ts): export interface SliceLease{ readonly key: string; readonly instanceId: string; readonly live: boolean; read(): S; write(next: S): boolean; readonly onChange: EventHook>; revoke(): void; } StagedChange [TypeAliasDeclaration] (from packages/core/main/src/changes.ts): export type StagedChange = |{ readonly label: ChangeLabel; readonly ops: readonly ChangeOp[]; readonly undo?: readonly PredictedOp[]; readonly history?: false; } |{ readonly label: ChangeLabel; readonly undoOf: string; readonly shows: readonly PredictedOp[]; } |{ readonly label: ChangeLabel; readonly send: SendChange; readonly opId?: string; readonly history?: false; } ; StagedPrint [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface StagedPrint{ print(): Promise; destroy(): void; } StateCell [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface StateCell{ get(): State; update( transition: (state: State, ...args: Args) => State, ...args: Args ): void; readonly onChange: EventHook>; } StateChange [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface StateChange{ readonly next: S; readonly previous: S; } StateDeclaration [InterfaceDeclaration] (from packages/core/main/src/state.ts): export interface StateDeclaration{ readonly token: CapabilityToken; readonly read: (capability: Capability) => State; readonly empty: State; readonly ensure?: (capability: Capability) => Promise; } StateReader [InterfaceDeclaration] (from packages/framework/svelte/src/runtime/state.svelte.ts): export interface StateReader{ (): Readonly; (select: (state: State) => Selected): CurrentValue; } Subscribable [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type Subscribable = | ((listener: (event: T) => void) => Unsubscribe) |{ subscribe(listener: (event: T) => void): Unsubscribe} ; UnlockOptions [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface UnlockOptions extends OperationOptions{ readonly password: string; } Unsubscribe [TypeAliasDeclaration] (from packages/core/main/src/types.ts): export type Unsubscribe = () => void; UrlSource [InterfaceDeclaration] (from packages/core/main/src/types.ts): export interface UrlSource{ readonly kind: 'url'; readonly url: string; readonly id?: string; } VIEWER_DEFAULTS [VariableDeclaration] (from packages/core/main/src/viewer-settings.ts): VIEWER_DEFAULTS: ViewerSettings = Object.freeze({ identity: null, scope: null, accent: '#3858e9', page: Object.freeze({ background: '#ffffff', shadow: '0 6px 18px rgb(0 0 0 / 0.18)'} ), } ) VIEWER_WHOLE_SETTINGS [VariableDeclaration] (from packages/core/main/src/viewer-settings.ts): VIEWER_WHOLE_SETTINGS = ['identity'] as const Viewer [SvelteComponent] (from packages/framework/svelte/src/runtime/Viewer.svelte): props ViewerProps ViewerPageSettings [InterfaceDeclaration] (from packages/core/main/src/viewer-settings.ts): export interface ViewerPageSettings{ readonly background: string; readonly shadow: string; } ViewerProps [InterfaceDeclaration] (from packages/framework/svelte/src/runtime/props.ts): export interface ViewerProps{ engine: Engine | EngineFactory; plugins: AnyPlugin[]; initialDocuments?: InitialDocument[]; onReady?: (kernel: Kernel) => void; identity?: Identity | null; scope?: readonly string[] | null; accent?: string; page?: Partial; fetch?: HostFetch; fallback?: Snippet; error?: Snippet<[error: unknown]>; children?: Snippet; } ViewerSettings [InterfaceDeclaration] (from packages/core/main/src/viewer-settings.ts): export interface ViewerSettings{ readonly identity: Identity | null; readonly scope: readonly string[] | null; readonly accent: string; readonly page: ViewerPageSettings; } ViewerSettingsInput [InterfaceDeclaration] (from packages/core/main/src/viewer-settings.ts): export interface ViewerSettingsInput{ readonly identity?: Identity | null; readonly scope?: readonly string[] | null; readonly accent?: string; readonly page?: Partial; } VisitorAnswers [TypeAliasDeclaration] (from packages/engine/core/src/dto/GrantVisitor.ts): export type VisitorAnswers = Partial>; VisitorIdentityRequest [InterfaceDeclaration] (from packages/engine/core/src/dto/GrantVisitor.ts): export interface VisitorIdentityRequest{ readonly fields: Partial>; readonly missing: readonly VisitorIdentityField[]; readonly invalid: readonly VisitorIdentityField[]; readonly purpose?: string; readonly privacyUrl?: string; } WorkingSetPage [InterfaceDeclaration] (from packages/engine/core/src/scheduling/facts.ts): export interface WorkingSetPage{ readonly page: PageRef; readonly role: 'visible' | 'near'; readonly visible?: PageBox; readonly pixels: number; } annotationKey [FunctionDeclaration] (from packages/engine/core/src/identity/annotationKey.ts): export function annotationKey(ref: AnnotationRef): string{ switch (ref.kind){ case 'objectNumber': return `obj:${ ref.objectNumber} `; case 'baseIndex': return `base:${ ref.page.objectNumber} :${ ref.baseIndex} `; } } composeApi [FunctionDeclaration] (from packages/core/main/src/compose.ts): export function composeApi( capability: string, slices: T, ): UnionToIntersection{ const seen = new Set(); const api: Record ={ } ; for (const slice of slices){ for (const key of Object.keys(slice)){ if (seen.has(key)){ throw new Error(`[${ capability} ] api member '${ key} ' is defined twice`); } seen.add(key); api[key] = (slice as Record)[key]; } } return api as UnionToIntersection; } copyImage [FunctionDeclaration] (from packages/framework/web/src/clipboard.ts): export async function copyImage( image: ClipboardImageSource | PromiseLike, ): Promise{ const blob = Promise.resolve(image).then((picture) => picture.blob()); await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob} )]); } createCapabilityToken [FunctionDeclaration] (from packages/core/main/src/index.ts): export function createCapabilityToken( name: string, options?:{ hint?: string; promises?: PromiseMembers} , ): CapabilityToken{ return{ name, hint: options?.hint, ...(options?.promises ?{ promises: options.promises as Readonly>} :{ } ), } ; } createEventHook [FunctionDeclaration] (from packages/core/main/src/event-hook.ts): export function createEventHook( onListenerError?: (error: unknown) => void, ): EventHookSource{ let listeners: Set<(event: T) => void> | null = new Set(); return{ on(listener, options){ if (!listeners || options?.signal?.aborted) return () =>{ } ; listeners.add(listener); const off = () => void listeners?.delete(listener); options?.signal?.addEventListener('abort', off, { once: true} ); return off; } , emit(event){ if (!listeners) return; for (const listener of [...listeners]){ try{ listener(event); } catch (error){ onListenerError?.(error); } } } , destroy(){ listeners = null; } , } ; } createHostToken [FunctionDeclaration] (from packages/core/main/src/index.ts): export function createHostToken(token: CapabilityToken): CapabilityToken{ return token as CapabilityToken; } createKernel [FunctionDeclaration] (from packages/core/main/src/kernel.ts): export function createKernel(config:{ engine: Engine; plugins: AnyPlugin[]; settings?: DeepPartial; report?: (error: unknown) => void; clock?: HostClock; printer?: HostPrinter; measurer?: HostTextMeasurer; fetch?: HostFetch; } ): Kernel{ const{ engine, plugins} = config; const report = config.report ?? ((error: unknown) => console.error('[kernel]', error)); const store = createStore(report); const plan = planPlugins(plugins); const documentScopedPlugins = plan.ordered.filter(isDocumentScoped); const workspaceCapabilities = new Map, unknown>(); const workspaceLeases = new Map>(); const workspaceConnectors = new Map void>(); const workspaceCancel = new AbortController(); const workspaceScope = createScope(report); const inScopeByToken = new Map, NonNullable>([ [DocumentsToken, documentsInScope], ]); for (const plugin of plan.ordered){ if (plugin.token && plugin.inScope && !isDocumentScoped(plugin)){ inScopeByToken.set(plugin.token, plugin.inScope); } } const opened = createEventHook(report); const openFailed = createEventHook(report); const locked = createEventHook(report); const closed = createEventHook(report); const activeChanged = createEventHook(report); const pagesChanged = createEventHook(report); const unsavedChangesChanged = createEventHook(report); workspaceScope.defer(() =>{ for (const hook of [ opened, openFailed, locked, closed, activeChanged, pagesChanged, unsavedChangesChanged, ]) hook.destroy(); } ); const setCore = (patch: Partial): void =>{ const before = store.getCore().activeId; store.setCore(patch); const after = store.getCore().activeId; if (before !== after) activeChanged.emit({ documentId: after, previousDocumentId: before} ); } ; const sessions = new Map(); let status: KernelStatus = 'created'; let startPromise: Promise | null = null; let destroyPromise: Promise | null = null; const guardUsable = (what: string) =>{ if (status === 'failed' || status === 'destroying' || status === 'destroyed'){ throw new Error(`[kernel] ${ what} on a ${ status} kernel`); } } ; const checkpoint = (session: DocumentSession) =>{ if (session.cancel.signal.aborted){ throw new CancelledError(`closed while opening: ${ session.id} `); } } ; async function engineCall( session: DocumentSession, call: Promise, onLateResult?: (value: T) => void | Promise, ): Promise{ const abortable = call as Promise &{ abort?: (reason?: unknown) => void} ; session.engineOp = typeof abortable.abort === 'function' ? (abortable as never) : null; const signal = session.cancel.signal; let onAbort: (() => void) | undefined; const cancellation = new Promise((_, reject) =>{ onAbort = () => reject(new CancelledError(`closed while opening: ${ session.id} `)); if (signal.aborted) onAbort(); else signal.addEventListener('abort', onAbort, { once: true} ); } ); try{ return await Promise.race([call, cancellation]); } catch (error){ if (isCancelled(error)){ void call.then( (value) =>{ if (onLateResult) session.scope.defer(() => onLateResult(value)); } , () =>{ } , ); } throw error; } finally{ if (onAbort) signal.removeEventListener('abort', onAbort); session.engineOp = null; } } function createSession(id: string, name: string | undefined): DocumentSession{ const cancel = new AbortController(); const changes = createDocumentChanges({ handle: () => session.handle, notify: () =>{ refreshPages(session); store.notify(); } , report, } ); const session: DocumentSession ={ id, instanceId: `${ id} #${ ++instanceCounter} `, name, source: null, grantInput: null, openOptions: undefined, phase: 'opening', handle: null, stagedMeta: null, scope: createScope(report), operation: null, engineOp: null, cancel, signal: cancel.signal, capabilities: new Map(), building: new Set(), views: new Map(), connectors: new Map(), leases: new Map(), settleFlushes: new Set(), downloadWraps: [], printWraps: [], changes, pageView: createPageView({ changes, report} ), changeCount: 0, changesSeen: 0, close: () => closeSession(session), } ; session.settleFlushes.add(() => session.changes.settle()); session.scope.defer(() => session.changes.close()); return session; } function beginOperation(session: DocumentSession, run: () => Promise): Promise{ if (session.operation){ throw new Error(`[documents] "${ session.id} " already has an active transition`); } const operation = run().finally(() =>{ if (session.operation === operation) session.operation = null; } ); session.operation = operation; return operation; } function rekeySession(session: DocumentSession, nextId: string): void{ const previousId = session.id; if (previousId === nextId) return; const core = store.getCore(); if (sessions.has(nextId) || core.documents[nextId] || core.pending[nextId]){ throw new PluginError('conflict', 'documents', `duplicate document id: ${ nextId} `); } sessions.delete(previousId); session.id = nextId; sessions.set(nextId, session); session.views.clear(); const slot = core.pending[previousId]; if (slot){ const{ [previousId]: _moved, ...pending} = core.pending; setCore({ pending:{ ...pending, [nextId]:{ ...slot, id: nextId} } , order: core.order.map((id) => (id === previousId ? nextId : id)), activeId: core.activeId === previousId ? nextId : core.activeId, } ); } } const closingSessions = new WeakMap>(); function closeSession(session: DocumentSession): Promise{ const inFlight = closingSessions.get(session); if (inFlight) return inFlight; const closing = (async () =>{ session.phase = 'closing'; unpublishSlot(session.id); for (const lease of session.leases.values()) lease.revoke(); const reason = new CancelledError(`closed while opening: ${ session.id} `); session.cancel.abort(reason); session.engineOp?.abort(reason); await session.operation?.catch((error) =>{ if (!isCancelled(error) && !isAbortLike(error)) report(error); } ); await session.scope.destroy(); if (sessions.get(session.id) === session) sessions.delete(session.id); session.views.clear(); closed.emit({ documentId: session.id} ); } )(); closingSessions.set(session, closing); return closing; } function nextActiveDocument(core: CoreState, removedId: string): string | null{ if (core.activeId !== removedId) return core.activeId; const index = core.order.indexOf(removedId); const remaining = core.order.filter((id) => id !== removedId); return remaining.length === 0 ? null : (remaining[Math.max(0, index - 1)] ?? remaining[0]); } function publishPendingSlot(session: DocumentSession, activate: boolean): void{ const core = store.getCore(); setCore({ pending:{ ...core.pending, [session.id]:{ id: session.id, name: session.name, status: 'loading'} , } , order: core.order.includes(session.id) ? core.order : [...core.order, session.id], activeId: activate || core.activeId === null ? session.id : core.activeId, } ); } function publishLocked(session: DocumentSession, passwordProvided: boolean): void{ const core = store.getCore(); setCore({ pending:{ ...core.pending, [session.id]:{ id: session.id, name: session.name, status: 'locked', passwordProvided} , } , } ); locked.emit({ documentId: session.id, passwordProvided} ); } function publishError(session: DocumentSession, error: unknown): void{ const core = store.getCore(); const openRequest = openRequestOf(error, session.grantInput); setCore({ pending:{ ...core.pending, [session.id]:{ id: session.id, name: session.name, status: 'error', error, ...(openRequest ?{ openRequest} :{ } ), } , } , } ); openFailed.emit({ documentId: session.id, error: toPluginErrorInfo(toPluginError('documents', error)), } ); } function unpublishSlot(id: string): void{ const core = store.getCore(); if (!core.pending[id] && !core.documents[id]) return; const{ [id]: _pending, ...pending} = core.pending; const{ [id]: _document, ...documents} = core.documents; setCore({ pending, documents, order: core.order.filter((other) => other !== id), activeId: nextActiveDocument(core, id), } ); } function commitReady(session: DocumentSession): void{ session.phase = 'ready'; session.pageView.refresh(); const meta = pageMetaOf(session.stagedMeta!, session.pageView.current()); const core = store.getCore(); const{ [session.id]: _resolved, ...pending} = core.pending; setCore({ documents:{ ...core.documents, [session.id]: meta} , pending} ); const grant = session.handle?.grant; if (grant){ session.scope.defer( grant.onIdentityRequested((request) => setIdentityRequest(session, request)), ); session.scope.defer(grant.onOpenRequested((request) => setOpenRequest(session, request))); } opened.emit({ documentId: session.id, info: documentInfoOf(meta)} ); } function pageMetaOf(meta: DocumentMeta, view: PageView): DocumentMeta{ const{ pages, labels, pending} = view; if (meta.pages === pages && meta.pageLabels === labels && meta.pendingPages === pending){ return meta; } return{ ...meta, pageCount: pages.length, pages, pageLabels: labels, pendingPages: pending, pagesSequence: meta.pages === pages ? meta.pagesSequence : meta.pagesSequence + 1, } ; } function refreshPages(session: DocumentSession): void{ const view = session.pageView.refresh(); if (!view) return; const now = store.getCore(); const existing = now.documents[session.id]; if (!existing) return; const updated = pageMetaOf(existing, view); if (updated === existing) return; setCore({ documents:{ ...now.documents, [session.id]: updated} } ); if (updated.pages === existing.pages) return; pagesChanged.emit({ documentId: session.id, pagesSequence: updated.pagesSequence, pages: updated.pages, } ); } function setOpenRequest(session: DocumentSession, request: GrantOpenRequest | null): void{ const core = store.getCore(); const published = core.documents[session.id]; if (!published || (published.openRequest ?? null) === request) return; const{ openRequest: _shown, ...rest} = published; setCore({ documents:{ ...core.documents, [session.id]: request ?{ ...rest, openRequest: request} : rest, } , } ); } async function resumeGrant(session: DocumentSession, options: RetryOptions | undefined){ const grant = session.handle!.grant!; const{ passphrase, visitorIdentity} = options ??{ } ; try{ await grant.resume({ ...(passphrase !== undefined ?{ passphrase} :{ } ), ...(visitorIdentity !== undefined ?{ visitorIdentity} :{ } ), } ); } catch (error){ setOpenRequest(session, grant.openRequest); throw toPluginError('documents', error); } setOpenRequest(session, grant.openRequest); return{ document: getDocument(session.id)!} ; } function setIdentityRequest( session: DocumentSession, request: VisitorIdentityRequest | null, ): void{ const core = store.getCore(); const published = core.documents[session.id]; if (!published || (published.identityRequest ?? null) === request) return; const{ identityRequest: _shown, ...rest} = published; setCore({ documents:{ ...core.documents, [session.id]: request ?{ ...rest, identityRequest: request} : rest, } , } ); } async function identify(id: string, answers: VisitorAnswers): Promise{ const session = readySession(id, 'identify'); const grant = session.handle!.grant; if (!grant){ throw new PluginError('invalid-input', 'documents', `${ id} isn't from a grant`); } try{ await grant.identify(answers); } catch (error){ const request = visitorIdentityRequestOf(error); if (request) setIdentityRequest(session, request); throw toPluginError('documents', error); } setIdentityRequest(session, grant.identityRequest); } function declineIdentity(id: string): void{ const session = readySession(id, 'decline'); session.handle!.grant?.decline(); setIdentityRequest(session, null); } function setUnsavedChanges(session: DocumentSession, hasUnsavedChanges: boolean): void{ const core = store.getCore(); const published = core.documents[session.id]; if (!published){ if (session.stagedMeta && session.stagedMeta.hasUnsavedChanges !== hasUnsavedChanges){ session.stagedMeta ={ ...session.stagedMeta, hasUnsavedChanges} ; } return; } if (published.hasUnsavedChanges === hasUnsavedChanges) return; setCore({ documents:{ ...core.documents, [session.id]:{ ...published, hasUnsavedChanges} } , } ); unsavedChangesChanged.emit({ documentId: session.id, hasUnsavedChanges} ); } const sessionOf = (documentId?: string): DocumentSession | null =>{ const id = documentId ?? store.getCore().activeId; return id ? (sessions.get(id) ?? null) : null; } ; const documentHandle = (documentId?: string): DocumentHandle | null =>{ const session = sessionOf(documentId); if (!session) return null; return session.phase === 'bringup' || session.phase === 'ready' ? session.handle : null; } ; function readySession(documentId: string | undefined, verb: string): DocumentSession{ const session = sessionOf(documentId); if (!session || !documentHandle(session.id)){ throw new PluginError('not-ready', 'documents', `no open document to ${ verb} `); } return session; } const allowsOn = (documentId: string | undefined, permission: Permission): boolean =>{ const handle = documentHandle(documentId); return handle ? sessionAllows(handle.security, permission) : false; } ; async function downloadFile( documentId: string | undefined, signal: AbortSignal | undefined, verb: string, read: (handle: DocumentHandle) => Promise, refuse?: (handle: DocumentHandle) => PluginError | null, ): Promise{ const session = readySession(documentId, verb); if (!allowsOn(session.id, 'doc.download')){ throw permissionDenied('documents', 'doc.download', `documents.${ verb} `); } const refusal = refuse?.(session.handle!); if (refusal) throw refusal; try{ await settle(session.settleFlushes, [signal, session.signal], report); const handle = documentHandle(session.id); if (!handle) throw new PluginError('not-ready', 'documents', `no open document to ${ verb} `); let readAt = -1; const readFile = () =>{ readAt = session.changeCount; return cancellable('documents', signal, read(handle)); } ; const bytes = await runWrapped(session.downloadWraps, readFile); if (readAt === session.changeCount) setUnsavedChanges(session, false); return bytes; } catch (error){ throw toPluginError('documents', error); } } const printer = config.printer ?? null; const canPrintOn = (documentId: string | undefined): boolean => printer !== null && allowsOn(documentId, 'doc.print'); const printQualityOf = (documentId: string | undefined): PrintQuality | null =>{ if (!canPrintOn(documentId)) return null; if (!allowsOn(documentId, 'doc.print.high')) return PRINT_STANDARD; const mayKeepCopy = allowsOn(documentId, 'doc.download') || allowsOn(documentId, 'doc.download.flattened'); return mayKeepCopy && printer?.stagePdf ? PRINT_PDF : PRINT_HIGH; } ; function printPagesOf( session: DocumentSession, pages: readonly PageRef[] | undefined, ): readonly PageInfo[]{ const all = metaOf(session.id)?.pages ?? EMPTY_PAGES; if (pages === undefined) return all; if (pages.length === 0){ throw new PluginError('invalid-input', 'documents', 'a print needs at least one page'); } const found = pages.map((ref) =>{ const page = findPage(all, ref); if (!page){ throw new PluginError( 'not-found', 'documents', `page ${ ref.objectNumber} is not in this document`, ); } return page; } ); if (new Set(found).size !== found.length){ throw new PluginError('invalid-input', 'documents', 'a print names a page twice'); } return found; } const printLayersOf = (documentId: string, options: PrintOptions) => ({ includeAnnotations: options.includeAnnotations ?? allowsOn(documentId, 'doc.annotate.read'), includeFormFields: allowsOn(documentId, 'doc.forms.read'), } ); async function stagePrint( session: DocumentSession, activePrinter: HostPrinter, quality: PrintQuality, options: PrintOptions, ): Promise<{ staged: StagedPrint; quality: PrintQuality; changesSeen: number} >{ const{ signal} = options; await settle(session.settleFlushes, [signal, session.signal], report); const handle = documentHandle(session.id); if (!handle) throw new PluginError('not-ready', 'documents', 'no open document to print'); const changesSeen = session.changesSeen; const job: PrintJob ={ handle, pages: printPagesOf(session, options.pages), layers: printLayersOf(session.id, options), name: session.name ?? 'document', options, } ; options.onProgress?.({ pagesRendered: 0, pageCount: job.pages.length} ); if (quality.kind === 'images'){ return{ staged: await stagePictures(job, activePrinter, quality.dpi), quality, changesSeen} ; } try{ return{ staged: await stagePdfCopy(job, activePrinter), quality, changesSeen} ; } catch (error){ if (signal?.aborted) throw error; const staged = await stagePictures(job, activePrinter, PRINT_HIGH.dpi); return{ staged, quality: PRINT_HIGH, changesSeen} ; } } async function stagePdfCopy(job: PrintJob, activePrinter: HostPrinter): Promise{ const{ handle, pages, layers, name, options} = job; const{ signal} = options; if (!activePrinter.stagePdf){ throw new PluginError('unsupported', 'documents', 'this printer prints no PDF'); } const pdf = await cancellable( 'documents', signal, handle.pages.extract( pages.map((page) => page.ref), { flatten:{ usage: 'print'} , ...layers} , ), ); const staged = await activePrinter.stagePdf(pdf, { name, ...(signal ?{ signal} :{ } )} ); options.onProgress?.({ pagesRendered: pages.length, pageCount: pages.length} ); return staged; } async function stagePictures( job: PrintJob, activePrinter: HostPrinter, dpi: PrintDpi, ): Promise{ const{ handle, pages, layers, name, options} = job; const{ signal} = options; const sheets: PrintSheet[] = []; for (const page of pages){ const image = await cancellable( 'documents', signal, handle.page(page.ref).render.image({ usage: 'print', viewport:{ kind: 'dpi', dpi} , format: 'png', ...layers, } ), ); const blob = await cancellable('documents', signal, image.blob()); sheets.push({ image: blob, widthPt: page.size.width, heightPt: page.size.height} ); options.onProgress?.({ pagesRendered: sheets.length, pageCount: pages.length} ); } return activePrinter.stage(sheets, { name, ...(signal ?{ signal} :{ } )} ); } async function preparePrint( documentId: string | undefined, options: PrintOptions ={ } , ): Promise{ const session = readySession(documentId, 'preparePrint'); if (!allowsOn(session.id, 'doc.print')){ throw permissionDenied('documents', 'doc.print', 'documents.preparePrint'); } const quality = printQualityOf(session.id); if (!printer || !quality){ throw new PluginError( 'unsupported', 'documents', 'no printer: pass one to createKernel({ printer} ), such as browserPrinter() from @embedpdf/web', ); } const pageCount = printPagesOf(session, options.pages).length; try{ let{ staged, changesSeen, quality: printed, } = await stagePrint(session, printer, quality, options); let disposed = false; const destroy = () =>{ if (disposed) return; disposed = true; staged.destroy(); } ; session.scope.defer(destroy); const restage = async (as: PrintQuality, signal: AbortSignal | undefined) =>{ const fresh = await stagePrint(session, printer, as, { ...(options.pages ?{ pages: options.pages} :{ } ), ...(options.includeAnnotations !== undefined ?{ includeAnnotations: options.includeAnnotations} :{ } ), ...(signal ?{ signal} :{ } ), } ); staged.destroy(); ({ staged, changesSeen, quality: printed} = fresh); } ; return{ get quality(){ return printed; } , pageCount, needsTap: printer.needsTap === true, async print(printOptions){ if (disposed){ throw new PluginError('invalid-input', 'documents', 'this print was disposed'); } const signal = printOptions?.signal; const run = async () =>{ if (session.changesSeen !== changesSeen) await restage(quality, signal); if (signal?.aborted){ throw new PluginError('operation-cancelled', 'documents', 'print cancelled', { cause: signal.reason, } ); } try{ await staged.print(); } catch (error){ if (printed.kind !== 'pdf') throw error; await restage(PRINT_HIGH, signal); await staged.print(); } } ; try{ await runWrapped(session.printWraps, run); } catch (error){ throw toPluginError('documents', error); } } , destroy, } ; } catch (error){ throw toPluginError('documents', error); } } const isBuilding = (plugin: AnyPlugin, session: DocumentSession): boolean => session.building.has(plugin) && !session.capabilities.has(plugin); function buildDocumentCapability(plugin: AnyPlugin, session: DocumentSession): unknown{ let capability = session.capabilities.get(plugin); if (!capability){ if (session.building.has(plugin)){ throw new PluginError( 'not-ready', plugin.id, `"${ plugin.id} " was asked for while it is being created`, ); } const ctx = createPluginContext(services, plugin, session, session.signal, session.scope); session.building.add(plugin); let created: ReturnType; try{ created = plugin.create(ctx); } finally{ session.building.delete(plugin); } const{ api, connect} = created; capability = api; session.connectors.set(plugin, () =>{ connect?.(); markConnected(ctx); } ); session.capabilities.set(plugin, capability); } return capability; } function workspaceViewOf( token: CapabilityToken, capability: T, documentId: string | undefined, ): T{ const inScope = inScopeByToken.get(token); const session = documentId === undefined ? undefined : sessions.get(documentId); if (!inScope || !session) return capability; let view = session.views.get(token); if (view === undefined){ view = inScope(capability, session.id); session.views.set(token, view); } return view as T; } function resolveCapability(token: CapabilityToken, documentId?: string): T{ guardUsable(`capability("${ token.name} ")`); const workspaceCapability = workspaceCapabilities.get(token); if (workspaceCapability) return workspaceViewOf(token, workspaceCapability as T, documentId); const provider = plan.providerOf(token); if (!provider) throw new Error(`No capability "${ token.name} ".`); const id = documentId ?? store.getCore().activeId; if (!id) throw new Error(`Capability "${ token.name} " requires an active document.`); const session = sessions.get(id); if (!session) throw new Error(`Capability "${ token.name} " unavailable: no document "${ id} ".`); if (session.phase === 'bringup' || session.phase === 'ready'){ return buildDocumentCapability(provider, session) as T; } const shown = session.phase === 'opening' ? 'loading' : session.phase; throw new Error(`Capability "${ token.name} " unavailable: document "${ id} " is ${ shown} .`); } function tryResolveInternal(token: CapabilityToken, documentId?: string): T | null{ if (status === 'destroying' || status === 'destroyed') return null; const workspaceCapability = workspaceCapabilities.get(token); if (workspaceCapability) return workspaceViewOf(token, workspaceCapability as T, documentId); const provider = plan.providerOf(token); if (!provider) return null; const session = sessionOf(documentId); if (!session || (session.phase !== 'bringup' && session.phase !== 'ready')) return null; if (isBuilding(provider, session)) return null; return buildDocumentCapability(provider, session) as T; } function tryResolveCapability(token: CapabilityToken, documentId?: string): T | null{ if (status === 'destroying' || status === 'destroyed') return null; const workspaceCapability = workspaceCapabilities.get(token); if (workspaceCapability) return workspaceViewOf(token, workspaceCapability as T, documentId); const provider = plan.providerOf(token); if (!provider) return null; const session = sessionOf(documentId); if (!session || session.phase !== 'ready') return null; if (isBuilding(provider, session)) return null; return buildDocumentCapability(provider, session) as T; } const viewerSettings = createSettingsStore({ defaults: VIEWER_DEFAULTS, registered: config.settings, whole: VIEWER_WHOLE_SETTINGS} , store.notify, report, ); workspaceScope.defer(() => viewerSettings.destroy()); const settingsStores = new Map>(); for (const plugin of plan.ordered){ if (plugin.settings){ settingsStores.set(plugin, createSettingsStore(plugin.settings, store.notify, report)); } } workspaceScope.defer(() =>{ for (const settings of settingsStores.values()) settings.destroy(); } ); function settingsOf(token: CapabilityToken): SettingsApi>{ const provider = plan.providerOf(token); if (!provider) throw new Error(`No capability "${ token.name} ".`); const settings = settingsStores.get(provider); if (!settings) throw new Error(`Plugin "${ provider.id} " has no settings.`); return settings.api as unknown as SettingsApi>; } const services: ContextServices ={ engine, store, workspaceScope, workspaceSignal: workspaceCancel.signal, workspaceLeases, report, clock: config.clock ?? timerClock, measurer: config.measurer ?? null, resolveCapability, tryResolveCapability: tryResolveInternal, documentHandle, settingsStoreOf: (plugin) => settingsStores.get(plugin), } ; let ticketCounter = 0; const nextTicket = () => `pending:${ ++ticketCounter} `; async function bringUp( session: DocumentSession, snapshot:{ pageCount: number; pages: DocumentMeta['pages']; labels: DocumentMeta['pageLabels']; } , ): Promise{ session.phase = 'bringup'; let renderPolicy: EngineRenderPolicy = CONTINUOUS_RENDER_POLICY; try{ renderPolicy = (await session.handle!.render?.getPolicy()) ?? CONTINUOUS_RENDER_POLICY; } catch{ } checkpoint(session); session.pageView.setEnginePages(snapshot); session.pageView.refresh(); session.stagedMeta ={ id: session.id, instanceId: session.instanceId, name: session.name, pageCount: snapshot.pageCount, pages: session.pageView.current().pages, pageLabels: session.pageView.current().labels, pendingPages: NO_PENDING_PAGES, pagesSequence: 0, renderPolicy, hasUnsavedChanges: false, } ; const tracksChanges = isLocalDocument(session.handle!); const bursts = createBurstGate(store); session.scope.defer(bursts.close); let layoutsSeen = 0; let pageReads = 0; const readPagesAgain = (): void =>{ const seen = layoutsSeen; const read = ++pageReads; session.handle!.pages.list().then( (snapshot) =>{ if (session.cancel.signal.aborted || layoutsSeen !== seen || pageReads !== read) return; session.pageView.setEnginePages(snapshot); refreshPages(session); } , (error: unknown) =>{ if (!session.cancel.signal.aborted) report(error); } , ); } ; const unsubscribeEvents = session.handle!.events.subscribe((event) =>{ bursts.first(event); if (changesDocument(event)){ session.changesSeen += 1; if (tracksChanges){ session.changeCount += 1; setUnsavedChanges(session, true); } } const layout = layoutFromEvent(event); if (layout){ layoutsSeen += 1; session.pageView.setEnginePages(layout); } if (event.type === 'stream.desynced') readPagesAgain(); session.pageView.fold(event); refreshPages(session); } ); session.scope.defer(unsubscribeEvents); for (const plugin of documentScopedPlugins){ const lease = store.lease( sliceKey(plugin.id, session.id), initialStateOf(plugin), session.instanceId, ); session.leases.set(plugin, lease); session.scope.defer(() => lease.revoke()); } const release = store.hold(); try{ for (const plugin of documentScopedPlugins){ buildDocumentCapability(plugin, session); session.connectors.get(plugin)?.(); } } finally{ release(); } session.scope.defer(session.handle!.events.subscribe((event) => bursts.last(event))); checkpoint(session); } function openedResult(session: DocumentSession): OpenDocumentResult{ const core = store.getCore(); const entry = core.documents[session.id] ?? core.pending[session.id]; if (!entry) throw new PluginError('instance-closed', 'documents', `${ session.id} was closed`); return{ document: documentInfoOf(entry)} ; } async function openDocument( input: OpenSource, options?: OpenDocumentOptions, slotId?: string, ): Promise{ const signal = options?.signal; if (signal?.aborted){ throw new PluginError('operation-cancelled', 'documents', 'the open was cancelled'); } try{ const{ session, done} = reserveAndOpen(input, options, slotId); const cancel = () => void session.close(); signal?.addEventListener('abort', cancel, { once: true} ); try{ return openedResult(await done); } finally{ signal?.removeEventListener('abort', cancel); } } catch (error){ throw toPluginError('documents', error); } } function engineOptionsOf(options: OpenDocumentOptions | undefined){ const{ activate: _activate, name: _name, signal: _signal, ...own} = options ??{ } ; const viewer = viewerSettings.api.getSettings(); const scope = own.scope ?? viewer.scope ?? undefined; const identity = own.identity ?? viewer.identity ?? undefined; return{ ...own, ...(scope !== undefined ?{ scope} :{ } ), ...(identity !== undefined ?{ identity} :{ } ), } ; } function reserveAndOpen( input: OpenSource, options?: OpenDocumentOptions, slotId?: string, ):{ session: DocumentSession; done: Promise} { guardUsable('documents.open()'); const engineOptions = engineOptionsOf(options); const requestedId = slotId ?? (typeof input === 'function' ? nextTicket() : (idOfInput(input) ?? nextTicket())); if (sessions.has(requestedId)){ throw new PluginError('conflict', 'documents', `document already open: ${ requestedId} `); } const session = createSession(requestedId, options?.name); session.source = input; session.openOptions = options; sessions.set(session.id, session); publishPendingSlot(session, options?.activate ?? true); const done = beginOperation(session, async () =>{ try{ const given = typeof input === 'function' ? await engineCall(session, Promise.resolve(input(session.cancel.signal))) : input; checkpoint(session); const source = isUrlSource(given) ? await engineCall(session, fetchUrlSource(given, session.cancel.signal, config.fetch)) : given; checkpoint(session); session.grantInput = source.kind === 'grant' ? source : null; const sourceId = idOfInput(source); if (sourceId) rekeySession(session, sourceId); const handle = await engineCall(session, engine.open(source, engineOptions), (late) => late.close(), ); session.handle = handle; session.scope.defer(() => handle.close()); checkpoint(session); if (handle.id !== session.id) rekeySession(session, handle.id); const prompt = handle.security?.passwordPrompt; if (prompt?.state === 'required'){ session.phase = 'locked'; publishLocked(session, prompt.incorrect); return session; } const snapshot = await engineCall(session, handle.pages.list()); checkpoint(session); await bringUp(session, snapshot); commitReady(session); return session; } catch (error){ if (isCancelled(error)) throw error; if (session.phase === 'closing' || isAbortLike(error)){ throw new CancelledError(`closed while opening: ${ session.id} `); } await session.scope.destroy(); session.phase = 'error'; publishError(session, error); throw error; } } ); return{ session, done} ; } async function unlockDocument(id: string, options: UnlockOptions): Promise{ guardUsable('documents.unlock()'); const session = sessions.get(id); if (!session || session.phase !== 'locked' || !session.handle){ throw new PluginError('invalid-input', 'documents', `document is not locked: ${ id} `); } const handle = session.handle; return beginOperation(session, async () =>{ try{ await cancellable( 'documents', options.signal, engineCall(session, handle.security.unlock({ password: options.password} )), ); } catch (error){ if (session.phase === 'closing' || isAbortLike(error)){ throw new CancelledError(`closed while opening: ${ session.id} `); } throw error; } checkpoint(session); try{ const snapshot = await engineCall(session, handle.pages.list()); checkpoint(session); await bringUp(session, snapshot); commitReady(session); } catch (error){ if (isCancelled(error)) throw error; if (session.phase === 'closing' || isAbortLike(error)){ throw new CancelledError(`closed while opening: ${ session.id} `); } await session.scope.destroy(); session.phase = 'error'; publishError(session, error); throw error; } } ).catch((error: unknown) =>{ throw toPluginError('documents', error); } ); } async function closeDocument(documentId: string): Promise{ const session = sessions.get(documentId); if (!session) return; await session.close(); } function reorder(next: string[]){ setCore({ order: next} ); } const metaOf = (documentId?: string): DocumentMeta | null =>{ const core = store.getCore(); const id = documentId ?? core.activeId; return id ? (core.documents[id] ?? null) : null; } ; let listMemo:{ core: CoreState; value: readonly DocumentInfo[]} | null = null; const listDocuments = (): readonly DocumentInfo[] =>{ const core = store.getCore(); if (listMemo?.core === core) return listMemo.value; const next = core.order.map((id) => documentInfoOf(core.documents[id] ?? core.pending[id])); const previous = listMemo?.value; const same = previous !== undefined && previous.length === next.length && previous.every((info, i) => info === next[i]); const value = same ? previous : Object.freeze(next); listMemo ={ core, value} ; return value; } ; const getDocument = (documentId?: string): DocumentInfo | null =>{ const core = store.getCore(); const id = documentId ?? core.activeId; const entry = id ? (core.documents[id] ?? core.pending[id]) : undefined; return entry ? documentInfoOf(entry) : null; } ; const documents: DocumentsCapability ={ open: openDocument, canOpenFiles: () => engine.canOpenFiles, retry: async (id, options) =>{ const session = sessions.get(id); if (session?.phase === 'ready' && session.handle?.grant?.openRequest){ return resumeGrant(session, options); } if (!session || session.phase !== 'error' || session.source === null){ throw new PluginError( 'invalid-input', 'documents', `${ id} didn't fail to open; nothing to retry`, ); } const{ source, grantInput, openOptions} = session; const given = retrySourceOf(source, grantInput, options); const identity = options?.visitorIdentity !== undefined ?{ ...engineOptionsOf(openOptions).identity, ...options.visitorIdentity} : undefined; sessions.delete(id); return openDocument( given, { ...openOptions, ...(identity !== undefined ?{ identity} :{ } ), activate: false, signal: options?.signal, } , id, ); } , identify, declineIdentity, rename: (id, name) =>{ const core = store.getCore(); if (core.documents[id]){ setCore({ documents:{ ...core.documents, [id]:{ ...core.documents[id], name} } } ); } else if (core.pending[id]){ setCore({ pending:{ ...core.pending, [id]:{ ...core.pending[id], name} } } ); } const session = sessions.get(id); if (session) session.name = name; } , openAll: (initialDocuments) =>{ guardUsable('documents.openAll()'); const activeIndex = Math.max( 0, initialDocuments.findIndex((initialDocument) => initialDocument.active), ); return initialDocuments.map(({ source, active: _active, ...options} , index) =>{ try{ const{ session, done} = reserveAndOpen(source, { ...options, activate: index === activeIndex, } ); void done.catch(() =>{ } ); return session.id; } catch{ return typeof source === 'function' ? '' : (idOfInput(source) ?? ''); } } ); } , unlock: unlockDocument, close: closeDocument, closeAll: async () =>{ for (const id of [...store.getCore().order]) await closeDocument(id); } , setActive: (id) =>{ const core = store.getCore(); if (core.documents[id] || core.pending[id]) setCore({ activeId: id} ); } , getActiveId: () => store.getCore().activeId, getActive: () => getDocument(), list: listDocuments, get: getDocument, has: (id) =>{ const core = store.getCore(); return core.documents[id] !== undefined || core.pending[id] !== undefined; } , getCount: () => store.getCore().order.length, getOrder: () => store.getCore().order, setOrder: (ids) =>{ const current = store.getCore().order; const same = ids.length === current.length && [...ids].sort().join('\0') === [...current].sort().join('\0'); if (!same){ throw new PluginError( 'invalid-input', 'documents', 'setOrder() needs a permutation of the current order', ); } reorder([...ids]); } , move: (id, toIndex) =>{ const core = store.getCore(); if (!core.documents[id] && !core.pending[id]) return; const without = core.order.filter((documentId) => documentId !== id); const clamped = Math.max(0, Math.min(toIndex, without.length)); without.splice(clamped, 0, id); reorder(without); } , swap: (id, otherId) =>{ const core = store.getCore(); const index = core.order.indexOf(id); const otherIndex = core.order.indexOf(otherId); if (index < 0 || otherIndex < 0) return; const next = [...core.order]; next[index] = otherId; next[otherIndex] = id; reorder(next); } , download: (id, options) => downloadFile(id, options?.signal, 'download', (handle) => handle.download(options?.mode !== undefined ?{ mode: options.mode} : undefined), ), downloadLayer: (id, options) => downloadFile( id, options?.signal, 'downloadLayer', (handle) => (isLocalDocument(handle) ? handle.downloadLayer() : Promise.reject(noLayer())), (handle) => (isLocalDocument(handle) ? null : noLayer()), ), preparePrint: (id, options) => preparePrint(id, options), async print(id, options ={ } ){ const prepared = await preparePrint(id, options); try{ await prepared.print(options.signal ?{ signal: options.signal} : undefined); } finally{ prepared.destroy(); } } , getPrintQuality: (id) => printQualityOf(id), canDownload: (id) => allowsOn(id, 'doc.download'), canPrint: (id) => canPrintOn(id), listPages: (id) => metaOf(id)?.pages ?? EMPTY_PAGES, getPage: (page, id) => findPage(metaOf(id)?.pages ?? EMPTY_PAGES, page), getPageIndex: (ref, id) => metaOf(id)?.pages.findIndex((pageInfo) => pageRefsEqual(pageInfo.ref, ref)) ?? -1, getRevision: (id) => metaOf(id)?.pagesSequence ?? -1, onOpened: opened.on, onOpenFailed: openFailed.on, onLocked: locked.on, onClosed: closed.on, onActiveChanged: activeChanged.on, onPagesChanged: pagesChanged.on, onUnsavedChangesChanged: unsavedChangesChanged.on, } ; workspaceCapabilities.set(DocumentsToken, documents); for (const plugin of plan.ordered){ if (!isDocumentScoped(plugin)){ workspaceLeases.set(plugin, store.lease(plugin.id, initialStateOf(plugin))); } } for (const plugin of plan.ordered){ if (isDocumentScoped(plugin)) continue; const ctx = createPluginContext( services, plugin, undefined, workspaceCancel.signal, workspaceScope, ); const{ api, connect} = plugin.create(ctx); if (plugin.token) workspaceCapabilities.set(plugin.token, api); workspaceConnectors.set(plugin, () =>{ connect?.(); markConnected(ctx); } ); } return{ ...viewerSettings.api, engine, documents, capability: resolveCapability, tryCapability: tryResolveCapability, scopeOf: plan.scopeOf, settingsOf, subscribe: store.subscribe, getState: store.getState, getStatus: () => status, start: () =>{ if (status === 'destroying' || status === 'destroyed' || status === 'failed'){ return Promise.reject(new Error(`[kernel] start() on a ${ status} kernel`)); } return (startPromise ??= (async () =>{ status = 'starting'; try{ for (const plugin of plan.ordered){ if (status !== 'starting') return; if (!isDocumentScoped(plugin)) workspaceConnectors.get(plugin)?.(); } status = 'started'; } catch (error){ status = 'failed'; await workspaceScope.destroy(); workspaceCapabilities.clear(); throw error; } } )()); } , destroy: () =>{ return (destroyPromise ??= (async () =>{ const wasFailed = status === 'failed'; status = 'destroying'; workspaceCancel.abort(new CancelledError('kernel destroyed')); await startPromise?.catch((error) =>{ if (!isCancelled(error) && !wasFailed) report(error); } ); await Promise.allSettled([...sessions.values()].map((session) => session.close())); sessions.clear(); await workspaceScope.destroy(); workspaceCapabilities.clear(); store.destroy(); status = 'destroyed'; } )()); } , } ; } createLatestLane [FunctionDeclaration] (from packages/core/main/src/lanes.ts): export function createLatestLane( lifetime: AbortSignal, capability: string, name: string, ): LatestLane{ let generation = 0; let active: AbortController | null = null; const closed = () => new PluginError('instance-closed', capability, `${ name} : instance closed`); const cancelled = (id: string, why: string) => new PluginError('operation-cancelled', capability, `${ name} : ${ why} `, { details:{ runId: id, reason: why} , } ); return{ get running(){ return active !== null; } , cancel(reason){ active?.abort(reason ?? 'cancelled'); active = null; } , async run(fn, options){ if (lifetime.aborted) throw closed(); if (options?.signal?.aborted) throw cancelled(`${ name} #${ generation + 1} `, 'cancelled before start'); const mine = ++generation; const id = `${ name} #${ mine} `; const controller = new AbortController(); const previous = active; active = controller; const onLifetime = () => controller.abort('instance-closed'); const onCaller = () => controller.abort('cancelled'); lifetime.addEventListener('abort', onLifetime, { once: true} ); options?.signal?.addEventListener('abort', onCaller, { once: true} ); const current = () => mine === generation && !controller.signal.aborted; const run: LatestRun ={ id, signal: controller.signal, get superseded(){ return mine !== generation; } , commit(commitFn){ if (!current()) return false; commitFn(); return true; } , } ; try{ previous?.abort('superseded'); if (!current()) throw cancelled(id, 'superseded'); const value = await fn(run); if (!current()) throw cancelled(id, String(controller.signal.reason ?? 'superseded')); return value; } catch (error){ if (lifetime.aborted) throw closed(); if (!current()) throw cancelled(id, String(controller.signal.reason ?? 'superseded')); throw toPluginError(capability, error); } finally{ lifetime.removeEventListener('abort', onLifetime); options?.signal?.removeEventListener('abort', onCaller); if (active === controller) active = null; } } , } ; } createSerialQueue [FunctionDeclaration] (from packages/core/main/src/serial-queue.ts): export function createSerialQueue(capability: string): SerialQueue{ let tail: Promise = Promise.resolve(); const queue = (operation: () => Promise, options?: OperationOptions): Promise =>{ const start = (): Promise => options?.signal?.aborted ? Promise.reject( new PluginError('operation-cancelled', capability, 'cancelled before it started', { cause: options.signal.reason, } ), ) : operation(); const result = tail.then(start, start); tail = result.then( () => undefined, () => undefined, ); return result; } ; return Object.assign(queue, { idle: () => tail} ); } decodePageKey [FunctionDeclaration] (from packages/engine/core/src/identity/PageRef.ts): export function decodePageKey(key: string): PageRef | null{ if (!key.startsWith('obj:')) return null; const rest = key.slice('obj:'.length); const n = Number.parseInt(rest, 10); if (!Number.isInteger(n) || n <= 0 || String(n) !== rest) return null; return{ kind: 'objectNumber', objectNumber: n} ; } definePlugin [FunctionDeclaration] (from packages/core/main/src/index.ts): export function definePlugin< State = void, Capability = unknown, Settings extends object = NoSettings, >( definition: PluginDefinition, ): PluginDefinition{ return definition; } defineState [FunctionDeclaration] (from packages/core/main/src/state.ts): export function defineState( token: CapabilityToken, declaration:{ readonly read: (capability: Capability) => State; readonly empty: NoInfer; readonly ensure?: (capability: NoInfer) => Promise; } , ): StateDeclaration{ return{ token, read: declaration.read, empty: Object.freeze(declaration.empty), ...(declaration.ensure ?{ ensure: declaration.ensure} :{ } ), } ; } documentCommands [VariableDeclaration] (from packages/framework/svelte/src/command-lists.ts): documentCommands = createDocumentCommands(standardCommandsBrowser) documentState [VariableDeclaration] (from packages/core/main/src/documents-state.ts): documentState = defineState(DocumentsToken, { read: (documents): DocumentInfo => documents.get() ?? NO_DOCUMENT, empty: NO_DOCUMENT, } ) documentsState [VariableDeclaration] (from packages/core/main/src/documents-state.ts): documentsState = defineState(DocumentsToken, { read: (documents): DocumentsState => ({ documents: documents.list(), activeId: documents.getActiveId(), } ), empty:{ documents: [], activeId: null} , } ) encodePageKey [FunctionDeclaration] (from packages/engine/core/src/identity/PageRef.ts): export function encodePageKey(ref: PageRef): string{ if (!isValidPageObjectNumber(ref.objectNumber)){ throw new RangeError( `encodePageKey: objectNumber must be a positive integer, got ${ ref.objectNumber} `, ); } return `obj:${ ref.objectNumber} `; } epdfTheme [FunctionDeclaration] (from packages/framework/svelte/src/runtime/theme.ts): export function epdfTheme(theme: EpdfTheme): string{ return Object.entries(epdfThemeVariables(theme)) .map(([name, value]) => `${ name} : ${ value} ; `) .join(' '); } guardHandle [FunctionDeclaration] (from packages/core/main/src/guarded-handle.ts): export function guardHandle( handle: DocumentHandle, lifetime: GuardedLifetime, capability: string, ): DocumentHandle{ const cache = new WeakMap(); const closedError = () => new PluginError( 'instance-closed', capability, `document instance ${ lifetime.instanceId} was closed`, ); const guardPromise = (pending: PromiseLike): Promise =>{ const abortable = pending as PromiseLike &{ abort?: (reason?: unknown) => void} ; const guarded = new Promise((resolve, reject) =>{ const onAbort = () =>{ abortable.abort?.(lifetime.signal.reason); reject(closedError()); } ; if (lifetime.signal.aborted){ onAbort(); } else{ lifetime.signal.addEventListener('abort', onAbort, { once: true} ); } Promise.resolve(pending).then( (value) =>{ lifetime.signal.removeEventListener('abort', onAbort); if (!lifetime.signal.aborted) resolve(value); } , (error) =>{ lifetime.signal.removeEventListener('abort', onAbort); if (!lifetime.signal.aborted) reject(toPluginError(capability, error)); } , ); } ); if (typeof abortable.abort === 'function'){ Object.defineProperty(guarded, 'abort', { value: (reason?: unknown) => abortable.abort!(reason), enumerable: false, } ); } return guarded; } ; const wrapFunction = (fn: (...args: unknown[]) => unknown, target: object) => function guardedCall(...args: unknown[]): unknown{ let result: unknown; try{ result = fn.apply(target, args); } catch (error){ throw toPluginError(capability, error); } if (isPromiseLike(result)) return guardPromise(result); return wrapValue(result, target); } ; const wrapValue = (value: unknown, target: object): unknown =>{ if (typeof value === 'function') return wrapFunction(value as (...args: unknown[]) => unknown, target); if (isPlainWrappable(value)) return wrapObject(value); return value; } ; const wrapObject = (target: object): object =>{ let proxy = cache.get(target); if (!proxy){ proxy = new Proxy(target, { get(proxyTarget, property){ return wrapValue(Reflect.get(proxyTarget, property, proxyTarget), proxyTarget); } , } ); cache.set(target, proxy); } return proxy; } ; return wrapObject(handle) as DocumentHandle; } isCancelled [VariableDeclaration] (from packages/core/main/src/scope.ts): isCancelled = (error: unknown): error is CancelledError => error instanceof CancelledError isLocalEngine [FunctionDeclaration] (from packages/engine/core/src/engine/LocalEngine.ts): export function isLocalEngine(engine: Engine): engine is LocalEngine{ return hasLocalEngineBrand(engine); } isPdf [FunctionDeclaration] (from packages/core/main/src/pdf-header.ts): export function isPdf(bytes: Uint8Array): boolean{ const end = Math.min(bytes.length - PDF_HEADER.length, 1024); for (let start = 0; start <= end; start++){ if (PDF_HEADER.every((byte, index) => bytes[start + index] === byte)) return true; } return false; } isPluginError [FunctionDeclaration] (from packages/core/main/src/errors.ts): export function isPluginError(value: unknown, code?: PluginErrorCode): value is PluginError{ if (!(value instanceof PluginError)) return false; return code === undefined || value.code === code; } isReadMember [FunctionDeclaration] (from packages/core/main/src/capability-handle.ts): export function isReadMember(name: string): boolean{ return READ.test(name); } makePageContext [FunctionDeclaration] (from packages/framework/web/src/page-context.ts): export function makePageContext( documentId: string, view: string, ref: PageRef, pageIndex: number, frame: PageFrameShape, transform: Transform, getRect: () => ClientBox, getViewDemand?: () => Demand, ): PageContext{ return{ documentId, view, ref, pageIndex, frame, transform, ...(getViewDemand ?{ getViewDemand} :{ } ), ...pageClientSpace(() => transform, getRect), } ; } memo [FunctionDeclaration] (from packages/core/main/src/memo.ts): export function memo( inputs: () => Inputs, compute: (...inputs: Computed) => Result, ): () => Result{ let last:{ inputs: Inputs; result: Result} | null = null; return () =>{ const next = inputs(); if (last && sameInputs(last.inputs, next)) return last.result; const result = compute(...(next as unknown as Computed)); last ={ inputs: next, result} ; return result; } ; } memoByKey [FunctionDeclaration] (from packages/core/main/src/memo.ts): export function memoByKey( inputs: (key: Key) => Inputs, compute: (key: Key, ...inputs: Computed) => Result, options:{ maxEntries?: number} ={ } , ): (key: Key) => Result{ const cache = new Map(); return (key) =>{ const next = inputs(key); const cached = cache.get(key); if (cached && sameInputs(cached.inputs, next)) return cached.result; const result = compute(key, ...(next as unknown as Computed)); if (cached) cache.delete(key); else if (options.maxEntries !== undefined && cache.size >= options.maxEntries){ const oldest = cache.keys().next(); if (!oldest.done) cache.delete(oldest.value); } cache.set(key, { inputs: next, result} ); return result; } ; } mergeSettings [FunctionDeclaration] (from packages/core/main/src/settings.ts): export function mergeSettings( settings: T, changes: DeepPartial | undefined, declaration?: Pick, 'defaults' | 'whole'>, ): T{ const whole = declaration?.whole ?? []; if (whole.length === 0 || !isPlainObject(changes)) return mergeValue(settings, changes) as T; const paths = whole.map((path) => path.split('.')); let merged = mergeValue(settings, withoutPaths(changes, paths)); for (const path of paths){ const change = valueAt(changes, path); if (change === undefined) continue; const value = filledFrom(valueAt(declaration?.defaults, path), change); if (!sameValue(valueAt(merged, path), value)) merged = withValueAt(merged, path, value); } return merged as T; } pageRefsEqual [FunctionDeclaration] (from packages/engine/core/src/identity/PageRef.ts): export function pageRefsEqual(a: PageRef, b: PageRef): boolean{ return a.kind === b.kind && a.objectNumber === b.objectNumber; } reload [FunctionDeclaration] (from packages/core/main/src/mirror.ts): export function reload(options?:{ pages?: readonly PageRef[]} ): MirrorReload{ return{ [RELOAD]: options?.pages ?? 'all'} ; } reorderBackOf [FunctionDeclaration] (from packages/engine/core/src/pages/predict.ts): export function reorderBackOf( pages: readonly PageLayout[], refs: readonly PageRef[], ): PageOp<'pages.reorder'>[]{ return restoredPagesOf(pages, refs).map(({ page, after} ) => ({ type: 'pages.reorder', pages: [page.ref], position: after ?{ after} : 'start', } )); } resolvePageLayers [FunctionDeclaration] (from packages/engine/core/src/dto/PageRender.ts): export function resolvePageLayers( options:{ includeAnnotations?: boolean; includeFormFields?: boolean} | undefined, may: PageLayerRights, ): PageRenderLayers{ const{ includeAnnotations, includeFormFields} = options ??{ } ; if (includeAnnotations === true && !may.annotations){ throw new PermissionDenied('doc.annotate.read', 'includeAnnotations'); } if (includeFormFields === true && !may.formFields){ throw new PermissionDenied('doc.forms.read', 'includeFormFields'); } return{ includeAnnotations: includeAnnotations ?? may.annotations, includeFormFields: includeFormFields ?? (includeAnnotations === false ? false : may.formFields), } ; } restoredPagesOf [FunctionDeclaration] (from packages/engine/core/src/pages/predict.ts): export function restoredPagesOf( pages: readonly PageLayout[], refs: readonly PageRef[], ): RestoredPage[]{ const deleting = new Set(refs.map(encodePageKey)); return pages.flatMap((page, index) => deleting.has(keyOf(page)) ? [{ page, after: index > 0 ? pages[index - 1]!.ref : null} ] : [], ); } returnsPromise [FunctionDeclaration] (from packages/core/main/src/capability-handle.ts): export function returnsPromise(token: CapabilityToken, path: string): boolean{ return token.promises?.[path] === true; } rotateBackOf [FunctionDeclaration] (from packages/engine/core/src/pages/predict.ts): export function rotateBackOf( pages: readonly PageLayout[], refs: readonly PageRef[], ): PageOp<'pages.rotate'>[]{ const rotations = new Map(pages.map((page) => [keyOf(page), page.rotation])); const groups = new Map(); for (const ref of refs){ const rotation = rotations.get(encodePageKey(ref)); if (rotation === undefined) continue; groups.set(rotation, [...(groups.get(rotation) ?? []), ref]); } return [...groups].map(([rotation, group]) => ({ type: 'pages.rotate', pages: group, rotation, } )); } saveFile [FunctionDeclaration] (from packages/framework/web/src/file-picker.ts): export function saveFile(bytes: Uint8Array | Blob, name: string, mimeType?: string): void{ const blob = bytes instanceof Blob ? bytes : new Blob([bytes as BlobPart], { type: mimeType ?? 'application/octet-stream'} ); const url = URL.createObjectURL(blob); const anchor = document.createElement('a'); anchor.href = url; anchor.download = name; anchor.style.display = 'none'; document.body.appendChild(anchor); anchor.click(); anchor.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); } setPageContext [FunctionDeclaration] (from packages/framework/svelte/src/runtime/page.ts): export function setPageContext(page: PageContextValue): void{ setContext(PAGE, page); } settingsReader [FunctionDeclaration] (from packages/framework/svelte/src/runtime/state.svelte.ts): export function settingsReader( token: CapabilityToken, ): SettingsReader & object>{ type Settings = SettingsOf & object; return function useSettings(select?: (settings: Settings) => Selected){ const binding = useKernelBinding(); const initial = settingsOf(binding.kernel, token) as Settings; const whole = derivedValue(() =>{ binding.track(); return settingsOf(binding.kernel, token) as Settings; } , shallowEqual); return readRecord(whole, Object.keys(initial) as (keyof Settings)[], select); } as SettingsReader; } shallowArray [VariableDeclaration] (from packages/framework/svelte/src/runtime/readers.svelte.ts): shallowArray = (left: readonly T[], right: readonly T[]): boolean => left === right || (left.length === right.length && left.every((item, i) => item === right[i])) shallowEqual [FunctionDeclaration] (from packages/core/main/src/state.ts): export function shallowEqual(left: unknown, right: unknown): boolean{ if (Object.is(left, right)) return true; if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null){ return false; } if (Array.isArray(left) !== Array.isArray(right)) return false; const leftFields = left as Record; const rightFields = right as Record; const keys = Object.keys(leftFields); return ( keys.length === Object.keys(rightFields).length && keys.every((key) => key in rightFields && Object.is(leftFields[key], rightFields[key])) ); } snapAppearanceScale [FunctionDeclaration] (from packages/engine/core/src/engine/DocumentRenderService.ts): export function snapAppearanceScale(policy: EngineRenderPolicy, scale: number): number{ if (policy.kind === 'continuous' || policy.appearances === undefined) return scale; if (policy.appearances.scales.length === 0){ throw new EngineError( EngineErrorCode.InvalidArg, 'render policy has an empty appearance-scale lattice', ); } const scales = [...policy.appearances.scales].sort((a, b) => a - b); return scales.find((s) => s >= scale) ?? scales[scales.length - 1]!; } snapFullPageViewport [FunctionDeclaration] (from packages/engine/core/src/engine/DocumentRenderService.ts): export function snapFullPageViewport( policy: EngineRenderPolicy, viewport: PageRenderViewport, options?:{ pageWidth?: number} , ): PageRenderViewport{ if (policy.kind === 'continuous') return viewport; if (viewport.kind === 'dpi' || viewport.kind === 'thumbnail') return viewport; if (policy.fullPage.widths.length === 0){ throw new EngineError(EngineErrorCode.InvalidArg, 'render policy has an empty width ladder'); } const widths = [...policy.fullPage.widths].sort((a, b) => a - b); let requested: number; if (viewport.kind === 'width'){ requested = viewport.width; } else{ const pageWidth = options?.pageWidth; if (pageWidth === undefined || pageWidth <= 0){ throw new EngineError( EngineErrorCode.InvalidArg, 'snapping a scale viewport to a width lattice requires opts.pageWidth', ); } requested = (viewport.scale ?? 1) * pageWidth; } const snapped = widths.find((width) => width >= requested) ?? widths[widths.length - 1]!; return{ kind: 'width', width: snapped} ; } snapTileScale [FunctionDeclaration] (from packages/engine/core/src/engine/DocumentRenderService.ts): export function snapTileScale(policy: EngineRenderPolicy, scale: number): number{ if (policy.kind === 'continuous' || policy.tiles === undefined) return scale; if (policy.tiles.scales.length === 0){ throw new EngineError( EngineErrorCode.InvalidArg, 'render policy has an empty tile-scale lattice', ); } const scales = [...policy.tiles.scales].sort((a, b) => a - b); return scales.find((s) => s >= scale) ?? scales[scales.length - 1]!; } standInFor [FunctionDeclaration] (from packages/core/main/src/capability-handle.ts): export function standInFor(kernel: Kernel, token: CapabilityToken): T{ let byToken = standIns.get(kernel); if (!byToken){ byToken = new WeakMap(); standIns.set(kernel, byToken); } let standIn = byToken.get(token); if (!standIn){ standIn = createStandIn(token, () => kernel.settingsOf(token)); byToken.set(token, standIn); } return standIn as T; } stateReader [FunctionDeclaration] (from packages/framework/svelte/src/runtime/state.svelte.ts): export function stateReader( declaration: StateDeclaration, ): StateReader{ const keys = Object.keys(declaration.empty) as (keyof State)[]; const{ ensure} = declaration; return function useDeclaredState(select?: (state: State) => Selected){ const binding = useKernelBinding(); const whole = declaredState(binding, declaration.token, declaration.read, declaration.empty); if (ensure) ensureWhileRead(binding, declaration.token, ensure); return readRecord(whole, keys, select); } as StateReader; } timerClock [VariableDeclaration] (from packages/core/main/src/clock.ts): timerClock: HostClock ={ now: () => performance.now(), after(ms, run){ const timer = setTimeout(run, ms); return () => clearTimeout(timer); } , } toPageRef [FunctionDeclaration] (from packages/engine/core/src/identity/PageRef.ts): export function toPageRef(pageObjectNumber: PageObjectNumber): PageRef{ return{ kind: 'objectNumber', objectNumber: pageObjectNumber} ; } toPluginError [FunctionDeclaration] (from packages/core/main/src/errors.ts): export function toPluginError(capability: string, error: unknown): PluginError{ if (error instanceof PluginError) return error; if (isCancelled(error) || (error instanceof Error && error.name === 'AbortError')){ return new PluginError('operation-cancelled', capability, 'operation cancelled', { cause: error, } ); } if (EngineError.is(error)){ const code = ENGINE_CODE_MAP[String(error.code)] ?? 'operation-failed'; return new PluginError(code, capability, error.message, { cause: error, details: error.details, permission: code === 'permission-denied' ? requiredPermissionOf(error) : null, } ); } const message = error instanceof Error ? error.message : String(error); return new PluginError('operation-failed', capability, message, { cause: error} ); } toPluginErrorInfo [FunctionDeclaration] (from packages/core/main/src/errors.ts): export function toPluginErrorInfo(error: PluginError): PluginErrorInfo{ return{ code: error.code, message: error.message, capability: error.capability, permission: error.permission, } ; } useActiveDocumentId [FunctionDeclaration] (from packages/framework/svelte/src/runtime/readers.svelte.ts): export function useActiveDocumentId(): CurrentValue{ return useKernelValue((kernel) => kernel.documents.getActiveId()); } useCapability [FunctionDeclaration] (from packages/framework/svelte/src/runtime/readers.svelte.ts): export function useCapability(token: MaybeGetter>): T{ const binding = useKernelBinding(); const{ kernel} = binding; const scoped = documentScopeOf(); const initial = untrack(() => valueOf(token)); if (kernel.scopeOf(initial) !== 'document') kernel.capability(initial); return capabilityHandle( () =>{ const current = valueOf(token); return kernel.tryCapability(current, scoped() ?? undefined) ?? standInFor(kernel, current); } , () => binding.track(), ); } useCapabilityEvent [FunctionDeclaration] (from packages/framework/svelte/src/runtime/readers.svelte.ts): export function useCapabilityEvent( token: MaybeGetter>, select: (capability: C) => EventHook, handler: (event: T) => void, ): void{ const capability = useOptionalCapability(token); $effect(() =>{ const current = capability.current; if (!current) return; return untrack(() => select(current)((event) => handler(event))); } ); } useDocument [FunctionDeclaration] (from packages/framework/svelte/src/runtime/documents.svelte.ts): export function useDocument(): Readonly; useDocumentId [FunctionDeclaration] (from packages/framework/svelte/src/runtime/readers.svelte.ts): export function useDocumentId(): CurrentValue{ const scoped = documentScopeOf(); return useKernelValue((kernel) => scoped() ?? kernel.documents.getActiveId()); } useDocumentScope [FunctionDeclaration] (from packages/framework/svelte/src/runtime/readers.svelte.ts): export function useDocumentScope(): CurrentValue{ return currentOf(documentScopeOf()); } useDocuments [FunctionDeclaration] (from packages/framework/svelte/src/runtime/documents.svelte.ts): export function useDocuments(): DocumentsCapability{ return useCapability(DocumentsToken); } useDocumentsEvent [FunctionDeclaration] (from packages/framework/svelte/src/runtime/documents.svelte.ts): export function useDocumentsEvent( select: (documents: DocumentsCapability) => EventHook, handler: (event: T) => void, ): void{ useCapabilityEvent(DocumentsToken, select, handler); } useDocumentsState [FunctionDeclaration] (from packages/framework/svelte/src/runtime/documents.svelte.ts): export function useDocumentsState(): Readonly; useKernel [FunctionDeclaration] (from packages/framework/svelte/src/runtime/binding.svelte.ts): export function useKernel(): Kernel{ return useKernelBinding().kernel; } useKernelValue [FunctionDeclaration] (from packages/framework/svelte/src/runtime/readers.svelte.ts): export function useKernelValue( select: (kernel: Kernel) => R, isEqual: (left: R, right: R) => boolean = Object.is, ): CurrentValue{ const binding = useKernelBinding(); return currentOf( derivedValue(() =>{ binding.track(); return select(binding.kernel); } , isEqual), ); } useOptionalCapability [FunctionDeclaration] (from packages/framework/svelte/src/runtime/readers.svelte.ts): export function useOptionalCapability( token: MaybeGetter>, ): CurrentValue{ const binding = useKernelBinding(); const scoped = documentScopeOf(); return currentOf( derivedValue(() =>{ binding.track(); return binding.kernel.tryCapability(valueOf(token), scoped() ?? undefined); } ), ); } useOptionalSelector [FunctionDeclaration] (from packages/framework/svelte/src/runtime/readers.svelte.ts): export function useOptionalSelector( token: MaybeGetter>, select: (capability: C) => R, fallback: R, isEqual: (left: R, right: R) => boolean = Object.is, ): CurrentValue{ const binding = useKernelBinding(); const scoped = documentScopeOf(); return currentOf( derivedValue(() =>{ binding.track(); const capability = binding.kernel.tryCapability(valueOf(token), scoped() ?? undefined); if (capability === null) return fallback; try{ return select(capability); } catch{ return fallback; } } , isEqual), ); } usePage [FunctionDeclaration] (from packages/framework/svelte/src/runtime/page.ts): export function usePage(): PageContextValue{ if (!hasContext(PAGE)){ throw new Error('[embedpdf] usePage() must be used inside or a page.'); } return getContext(PAGE); } usePageList [FunctionDeclaration] (from packages/framework/svelte/src/runtime/documents.svelte.ts): export function usePageList(): CurrentValue{ const documentId = useDocumentId(); return useKernelValue((kernel) => documentId.current ? kernel.documents.listPages(documentId.current) : NO_PAGES, ); } useSelector [FunctionDeclaration] (from packages/framework/svelte/src/runtime/readers.svelte.ts): export function useSelector( token: MaybeGetter>, select: (capability: C) => R, isEqual: (left: R, right: R) => boolean = Object.is, ): CurrentValue{ const binding = useKernelBinding(); const scoped = documentScopeOf(); return currentOf( derivedValue(() =>{ binding.track(); const current = valueOf(token); const documentId = scoped() ?? undefined; const capability = binding.kernel.tryCapability(current, documentId) ?? binding.kernel.capability(current, documentId); return select(capability); } , isEqual), ); } useViewerSettings [FunctionDeclaration] (from packages/framework/svelte/src/runtime/documents.svelte.ts): export function useViewerSettings(): Readonly; viewerSettingsOf [FunctionDeclaration] (from packages/core/main/src/viewer-settings.ts): export function viewerSettingsOf({ identity, scope, accent, page, } : ViewerSettingsInput): ViewerSettings{ return{ identity: identity ?? null, scope: scope ?? null, accent: accent ?? VIEWER_DEFAULTS.accent, page:{ ...VIEWER_DEFAULTS.page, ...page} , } ; }