Carries 359 template commits, tag v0.2.0 plus one documentation commit: the generator-built feature index with its app, bounded-context and feature declarations, the src/platform kernel and scale tooling, the 2026-09-24 src review fixes, and the 2026-09-25 maturity review round with its CHANGELOG [보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them merged with product changes; 127 are not carried. Product identity is unchanged: name, version 0.1.0, routes, design and the TechLog domain. Three decisions worth naming. TechLog stays composed directly, as the last two syncs recorded; its directory carries a NOT_INSTALLED marker that says so, and every installed-* composer takes the template's projection with TechLog added on top. The reference sample is no longer installed: the template now installs a feature only through feature-module.ts and context-routes.ts, which load the screens this product deleted, so its three operations, six schemas and one topic leave the registries, recorded as registry change evidence. And AppRouter mounts the platform and TechLog routes only; the template's bounded-context route gateway waits for a generator-installed feature. Required fixes: readSubject on the BFF session owner (without it every HTTP Studio session would close as integration-failed), zod through the facade in nine TechLog files, noUnusedLocals, and public/config.json written out to match the local profile. Derived baselines were recomputed after reproducing both sides' values: CI contract 101 commands / 106 references / 141 artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime config schema baseline equals the schema at8210d48. Verified here: types, lint, architecture, adapter inventory, CI contract, i18n, design system, diagnostics, browser security, dev release manifest, TechLog contract and build pass; 220 component, 155 integration, 15 contract, 418 TechLog, 43 reference-feature, 18 recipe and 46 release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at8210d48first and unchanged: check:registries (byte-identical), test:runtime-schema, verify:documentation. Brought by the template and escalated rather than suppressed: check:request-fanout on TechLog's cursor pagination, check:remediation-ledger (fails upstream too), the shared-chunk hash test, and the registry-dependent sample removal and second-feature tests. Playwright suites were not run. Full record, the five open questions and the follow-ups in docs/operations/template-sync-2026-09-29.md. (cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
697 lines
22 KiB
TypeScript
697 lines
22 KiB
TypeScript
import type {
|
|
FilePolicyReference,
|
|
FilePickerPort,
|
|
FileSelectionLimitReduction,
|
|
FileSelectionOutcome,
|
|
LocalFileRef,
|
|
} from "../../application/ports/browser-file-storage/file.ts";
|
|
import type { BrowserDataResult } from "../../application/ports/browser-file-storage/shared.ts";
|
|
import {
|
|
abortedResult,
|
|
browserDataFailure,
|
|
browserDataSuccess,
|
|
mapBrowserDataException,
|
|
} from "../browser-file-storage/result.ts";
|
|
import {
|
|
BrowserFileVault,
|
|
type SystemFileHandle,
|
|
} from "./browser-file-vault.ts";
|
|
import {
|
|
byteBucket,
|
|
observeBrowserFile,
|
|
type BrowserFileObserver,
|
|
} from "./file-observer.ts";
|
|
import type { RegisteredFileSelectionPolicy } from "./file-policy.ts";
|
|
import { BrowserFilePolicyRegistry } from "./browser-file-policy-registry.ts";
|
|
import { createAbortableOperation } from "../platform/abortable-operation.ts";
|
|
|
|
type UserActivationState = Readonly<{ isActive: boolean }>;
|
|
|
|
type PickerScheduler = Readonly<{
|
|
setTimeout(callback: () => void, delayMs: number): unknown;
|
|
clearTimeout(handle: unknown): void;
|
|
}>;
|
|
|
|
type InputEventDependencies = Readonly<{
|
|
add(
|
|
type: string,
|
|
listener: EventListener,
|
|
options?: AddEventListenerOptions,
|
|
): void;
|
|
remove(type: string, listener: EventListener): void;
|
|
getAttribute(name: string): string | null;
|
|
activate(): void;
|
|
}>;
|
|
|
|
type WindowEventDependencies = Readonly<{
|
|
add(type: "focus", listener: EventListener): void;
|
|
remove(type: "focus", listener: EventListener): void;
|
|
}>;
|
|
|
|
interface DisposableFilePicker extends FilePickerPort {
|
|
dispose(): void;
|
|
}
|
|
|
|
/**
|
|
* Focus can return before some engines dispatch the file input change event.
|
|
* This grace keeps the fallback from misclassifying a real selection as a
|
|
* dismissal. The native cancel event remains authoritative and immediate, and
|
|
* once a picker has seen it the fallback is no longer installed.
|
|
*/
|
|
export const DEFAULT_NATIVE_PICKER_FOCUS_GRACE_MS = 1_000;
|
|
|
|
export type NativeInputFilePickerOptions = Readonly<{
|
|
/**
|
|
* A connected, labelled input owned by presentation. The adapter does not
|
|
* create an inaccessible hidden control.
|
|
*/
|
|
input: HTMLInputElement;
|
|
vault: BrowserFileVault;
|
|
policies: BrowserFilePolicyRegistry;
|
|
window?: Pick<Window, "addEventListener" | "removeEventListener">;
|
|
userActivation?: UserActivationState;
|
|
scheduler?: PickerScheduler;
|
|
focusFallbackGraceMs?: number;
|
|
/** @deprecated Use focusFallbackGraceMs. */
|
|
cancelFallbackDelayMs?: number;
|
|
systemOpenPickerSupported?: boolean;
|
|
systemSavePickerSupported?: boolean;
|
|
observer?: BrowserFileObserver;
|
|
}>;
|
|
|
|
/**
|
|
* Canonical cross-browser picker. select() must be called directly from the
|
|
* input's labelled button/keyboard activation.
|
|
*/
|
|
export class NativeInputFilePicker implements DisposableFilePicker {
|
|
readonly support;
|
|
readonly #input: HTMLInputElement;
|
|
readonly #captureFiles: BrowserFileVault["captureFiles"];
|
|
readonly #releaseFile: BrowserFileVault["release"];
|
|
readonly #resolveSelection:
|
|
BrowserFilePolicyRegistry["resolveSelection"];
|
|
readonly #inputEvents: InputEventDependencies;
|
|
readonly #windowEvents: WindowEventDependencies | undefined;
|
|
readonly #userActivation: UserActivationState | undefined;
|
|
readonly #scheduler: PickerScheduler;
|
|
readonly #focusFallbackGraceMs: number;
|
|
readonly #observer: BrowserFileObserver | undefined;
|
|
#pending = false;
|
|
#disposed = false;
|
|
#abortPending: (() => void) | undefined;
|
|
/**
|
|
* Q-6.2-8. Once this engine has dispatched a native `cancel`, dismissal is
|
|
* reported natively, so the focus heuristic would only turn a slow `change`
|
|
* (a cloud provider still fetching the file) into a false dismissal.
|
|
*/
|
|
#nativeCancelObserved = false;
|
|
|
|
constructor(options: NativeInputFilePickerOptions) {
|
|
this.#input = options.input;
|
|
this.#captureFiles =
|
|
options.vault.captureFiles.bind(options.vault);
|
|
this.#releaseFile = options.vault.release.bind(options.vault);
|
|
this.#resolveSelection =
|
|
options.policies.resolveSelection.bind(options.policies);
|
|
const addInputEvent = options.input.addEventListener;
|
|
const removeInputEvent = options.input.removeEventListener;
|
|
const getInputAttribute = options.input.getAttribute;
|
|
const click = options.input.click;
|
|
if (
|
|
typeof addInputEvent !== "function" ||
|
|
typeof removeInputEvent !== "function" ||
|
|
typeof getInputAttribute !== "function" ||
|
|
typeof click !== "function"
|
|
) {
|
|
throw new TypeError("Native file input API is invalid.");
|
|
}
|
|
this.#inputEvents = Object.freeze({
|
|
add: addInputEvent.bind(options.input),
|
|
remove: removeInputEvent.bind(options.input),
|
|
getAttribute: getInputAttribute.bind(options.input),
|
|
// The baseline <input type="file"> path intentionally uses click().
|
|
// showPicker() exists in multiple engines but is not a portable
|
|
// automation/event-interception contract. Enhanced native picking is a
|
|
// separate capability owned by EnhancedFilePicker.
|
|
activate: click.bind(options.input),
|
|
});
|
|
const windowHost = options.window ?? globalThis.window;
|
|
if (windowHost) {
|
|
const addWindowEvent = windowHost.addEventListener;
|
|
const removeWindowEvent = windowHost.removeEventListener;
|
|
if (
|
|
typeof addWindowEvent !== "function" ||
|
|
typeof removeWindowEvent !== "function"
|
|
) {
|
|
throw new TypeError("Native picker window API is invalid.");
|
|
}
|
|
this.#windowEvents = Object.freeze({
|
|
add: addWindowEvent.bind(windowHost),
|
|
remove: removeWindowEvent.bind(windowHost),
|
|
});
|
|
} else {
|
|
this.#windowEvents = undefined;
|
|
}
|
|
this.#userActivation =
|
|
options.userActivation ?? globalThis.navigator?.userActivation;
|
|
const scheduler =
|
|
options.scheduler ??
|
|
({
|
|
setTimeout: (callback: () => void, delayMs: number) =>
|
|
globalThis.setTimeout(callback, delayMs),
|
|
clearTimeout: (handle: unknown) =>
|
|
globalThis.clearTimeout(
|
|
handle as ReturnType<typeof globalThis.setTimeout>,
|
|
),
|
|
} satisfies PickerScheduler);
|
|
if (
|
|
typeof scheduler.setTimeout !== "function" ||
|
|
typeof scheduler.clearTimeout !== "function"
|
|
) {
|
|
throw new TypeError("Native picker scheduler is invalid.");
|
|
}
|
|
this.#scheduler = Object.freeze({
|
|
setTimeout: scheduler.setTimeout.bind(scheduler),
|
|
clearTimeout: scheduler.clearTimeout.bind(scheduler),
|
|
});
|
|
if (
|
|
options.focusFallbackGraceMs !== undefined &&
|
|
options.cancelFallbackDelayMs !== undefined &&
|
|
options.focusFallbackGraceMs !== options.cancelFallbackDelayMs
|
|
) {
|
|
throw new TypeError("Native picker focus grace is ambiguous.");
|
|
}
|
|
this.#focusFallbackGraceMs =
|
|
options.focusFallbackGraceMs ??
|
|
options.cancelFallbackDelayMs ??
|
|
DEFAULT_NATIVE_PICKER_FOCUS_GRACE_MS;
|
|
this.#observer = options.observer;
|
|
this.support = Object.freeze({
|
|
nativeInput: true as const,
|
|
systemOpenPicker: options.systemOpenPickerSupported ?? false,
|
|
systemSavePicker: options.systemSavePickerSupported ?? false,
|
|
});
|
|
if (
|
|
!Number.isSafeInteger(this.#focusFallbackGraceMs) ||
|
|
this.#focusFallbackGraceMs < 0
|
|
) {
|
|
throw new TypeError("Native picker cancel fallback delay is invalid.");
|
|
}
|
|
}
|
|
|
|
async select(input: {
|
|
policy: FilePolicyReference;
|
|
limits?: FileSelectionLimitReduction;
|
|
signal?: AbortSignal;
|
|
}): Promise<BrowserDataResult<FileSelectionOutcome>> {
|
|
let request: SelectionRequestSnapshot;
|
|
try {
|
|
request = snapshotSelectionRequest(input);
|
|
} catch {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataFailure("INVALID_INPUT", "FILE_SELECT"),
|
|
);
|
|
}
|
|
if (this.#disposed) {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataFailure("UNAVAILABLE", "FILE_SELECT"),
|
|
);
|
|
}
|
|
const cancelled = abortedResult(request.signal, "FILE_SELECT");
|
|
if (cancelled) return observeSelection(this.#observer, cancelled);
|
|
const resolvedPolicy = this.#resolveSelection(
|
|
request.policy,
|
|
request.limits,
|
|
);
|
|
if (!resolvedPolicy.ok) {
|
|
return observeSelection(this.#observer, resolvedPolicy);
|
|
}
|
|
const policy = resolvedPolicy.value;
|
|
if (
|
|
!isUsableFileInput(
|
|
this.#input,
|
|
this.#inputEvents.getAttribute,
|
|
)
|
|
) {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataFailure("INVALID_INPUT", "FILE_SELECT"),
|
|
);
|
|
}
|
|
if (this.#pending) {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataFailure("BLOCKED", "FILE_SELECT"),
|
|
);
|
|
}
|
|
if (this.#userActivation && !this.#userActivation.isActive) {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataFailure("PERMISSION_DENIED", "FILE_SELECT"),
|
|
);
|
|
}
|
|
|
|
this.#pending = true;
|
|
try {
|
|
const result =
|
|
await new Promise<BrowserDataResult<FileSelectionOutcome>>(
|
|
(resolve) => {
|
|
let settled = false;
|
|
let focusTimer: unknown;
|
|
const signal = request.signal;
|
|
// The kernel operation owns the caller signal listener.
|
|
const operation = createAbortableOperation({ signal });
|
|
const finish = (
|
|
outcome: BrowserDataResult<FileSelectionOutcome>,
|
|
): void => {
|
|
if (settled) return;
|
|
settled = true;
|
|
this.#inputEvents.remove("change", onChange);
|
|
this.#inputEvents.remove("cancel", onCancel);
|
|
operation.close();
|
|
this.#windowEvents?.remove("focus", onWindowFocus);
|
|
if (focusTimer !== undefined) {
|
|
this.#scheduler.clearTimeout(focusTimer);
|
|
}
|
|
if (this.#abortPending === abortPending) {
|
|
this.#abortPending = undefined;
|
|
}
|
|
resolve(outcome);
|
|
};
|
|
const dismiss = (): void =>
|
|
finish(
|
|
browserDataSuccess(
|
|
Object.freeze({ kind: "DISMISSED" as const }),
|
|
),
|
|
);
|
|
const onChange = (): void => {
|
|
const files = this.#input.files;
|
|
if (!files || files.length === 0) {
|
|
dismiss();
|
|
return;
|
|
}
|
|
const captured = this.#captureFiles(
|
|
files,
|
|
policy,
|
|
"NATIVE_INPUT",
|
|
);
|
|
finish(
|
|
captured.ok
|
|
? browserDataSuccess(
|
|
Object.freeze({
|
|
kind: "SELECTED" as const,
|
|
files: captured.value,
|
|
}),
|
|
)
|
|
: captured,
|
|
);
|
|
};
|
|
const onCancel = (): void => {
|
|
this.#nativeCancelObserved = true;
|
|
dismiss();
|
|
};
|
|
const abortPending = (): void =>
|
|
finish(browserDataFailure("ABORTED", "FILE_SELECT"));
|
|
const onWindowFocus = (): void => {
|
|
if (settled || focusTimer !== undefined) return;
|
|
focusTimer = this.#scheduler.setTimeout(
|
|
() => {
|
|
focusTimer = undefined;
|
|
if (settled) return;
|
|
// Some engines expose FileList before dispatching change.
|
|
// Prefer the selected files over a synthetic dismissal.
|
|
if ((this.#input.files?.length ?? 0) > 0) {
|
|
onChange();
|
|
return;
|
|
}
|
|
dismiss();
|
|
},
|
|
this.#focusFallbackGraceMs,
|
|
);
|
|
};
|
|
|
|
this.#inputEvents.add("change", onChange, { once: true });
|
|
this.#inputEvents.add("cancel", onCancel, { once: true });
|
|
// Settles only when the operation ends; after `finish` this is a no-op.
|
|
void operation.race(new Promise<never>(() => {})).then(abortPending);
|
|
if (!this.#nativeCancelObserved) {
|
|
this.#windowEvents?.add("focus", onWindowFocus);
|
|
}
|
|
this.#abortPending = abortPending;
|
|
try {
|
|
this.#input.accept = pickerAcceptValue(policy);
|
|
this.#input.multiple = policy.multiple;
|
|
// Allows the same file to produce a new change event.
|
|
this.#input.value = "";
|
|
this.#inputEvents.activate();
|
|
} catch (error) {
|
|
finish(mapBrowserDataException(error, "FILE_SELECT"));
|
|
}
|
|
},
|
|
);
|
|
return observeSelection(this.#observer, result);
|
|
} catch (error) {
|
|
return observeSelection(
|
|
this.#observer,
|
|
mapBrowserDataException(error, "FILE_SELECT"),
|
|
);
|
|
} finally {
|
|
this.#pending = false;
|
|
}
|
|
}
|
|
|
|
release(ref: LocalFileRef): void {
|
|
this.#releaseFile(ref);
|
|
}
|
|
|
|
dispose(): void {
|
|
if (this.#disposed) return;
|
|
this.#disposed = true;
|
|
this.#abortPending?.();
|
|
try {
|
|
this.#input.value = "";
|
|
} catch {
|
|
// Some test doubles or constrained DOM hosts expose a readonly value.
|
|
}
|
|
}
|
|
}
|
|
|
|
export type SystemOpenPickerAcceptType = Readonly<{
|
|
description?: string;
|
|
accept: Readonly<Record<string, readonly string[]>>;
|
|
}>;
|
|
|
|
export type SystemOpenPickerOptions = Readonly<{
|
|
multiple: boolean;
|
|
excludeAcceptAllOption: boolean;
|
|
types: readonly SystemOpenPickerAcceptType[];
|
|
}>;
|
|
|
|
export type SystemOpenPicker = (
|
|
options: SystemOpenPickerOptions,
|
|
) => Promise<readonly SystemFileHandle[]>;
|
|
|
|
export type EnhancedFilePickerOptions = Readonly<{
|
|
showOpenFilePicker: SystemOpenPicker;
|
|
vault: BrowserFileVault;
|
|
policies: BrowserFilePolicyRegistry;
|
|
userActivation?: UserActivationState;
|
|
systemSavePickerSupported?: boolean;
|
|
observer?: BrowserFileObserver;
|
|
}>;
|
|
|
|
/**
|
|
* Progressive enhancement. Failure never opens the native fallback in the
|
|
* same activation; presentation may offer a baseline button for the next
|
|
* explicit user action.
|
|
*/
|
|
export class EnhancedFilePicker implements DisposableFilePicker {
|
|
readonly support;
|
|
readonly #showOpenFilePicker: SystemOpenPicker;
|
|
readonly #captureHandles: BrowserFileVault["captureHandles"];
|
|
readonly #releaseFile: BrowserFileVault["release"];
|
|
readonly #resolveSelection:
|
|
BrowserFilePolicyRegistry["resolveSelection"];
|
|
readonly #userActivation: UserActivationState | undefined;
|
|
readonly #observer: BrowserFileObserver | undefined;
|
|
#pending = false;
|
|
#disposed = false;
|
|
#abortPending: (() => void) | undefined;
|
|
|
|
constructor(options: EnhancedFilePickerOptions) {
|
|
if (typeof options.showOpenFilePicker !== "function") {
|
|
throw new TypeError("Enhanced file picker API is invalid.");
|
|
}
|
|
// Bound to undefined, not to options: `window.showOpenFilePicker` throws
|
|
// "Illegal invocation" for any other receiver, and Web IDL maps an
|
|
// undefined receiver to the global object.
|
|
this.#showOpenFilePicker =
|
|
options.showOpenFilePicker.bind(undefined);
|
|
this.#captureHandles =
|
|
options.vault.captureHandles.bind(options.vault);
|
|
this.#releaseFile = options.vault.release.bind(options.vault);
|
|
this.#resolveSelection =
|
|
options.policies.resolveSelection.bind(options.policies);
|
|
this.#userActivation =
|
|
options.userActivation ?? globalThis.navigator?.userActivation;
|
|
this.#observer = options.observer;
|
|
this.support = Object.freeze({
|
|
nativeInput: true as const,
|
|
systemOpenPicker: true,
|
|
systemSavePicker: options.systemSavePickerSupported ?? false,
|
|
});
|
|
}
|
|
|
|
async select(input: {
|
|
policy: FilePolicyReference;
|
|
limits?: FileSelectionLimitReduction;
|
|
signal?: AbortSignal;
|
|
}): Promise<BrowserDataResult<FileSelectionOutcome>> {
|
|
let request: SelectionRequestSnapshot;
|
|
try {
|
|
request = snapshotSelectionRequest(input);
|
|
} catch {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataFailure("INVALID_INPUT", "FILE_SELECT"),
|
|
);
|
|
}
|
|
if (this.#disposed) {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataFailure("UNAVAILABLE", "FILE_SELECT"),
|
|
);
|
|
}
|
|
const cancelled = abortedResult(request.signal, "FILE_SELECT");
|
|
if (cancelled) return observeSelection(this.#observer, cancelled);
|
|
const resolvedPolicy = this.#resolveSelection(
|
|
request.policy,
|
|
request.limits,
|
|
);
|
|
if (!resolvedPolicy.ok) {
|
|
return observeSelection(this.#observer, resolvedPolicy);
|
|
}
|
|
const policy = resolvedPolicy.value;
|
|
if (this.#pending) {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataFailure("BLOCKED", "FILE_SELECT"),
|
|
);
|
|
}
|
|
if (this.#userActivation && !this.#userActivation.isActive) {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataFailure("PERMISSION_DENIED", "FILE_SELECT"),
|
|
);
|
|
}
|
|
|
|
this.#pending = true;
|
|
try {
|
|
// This call intentionally happens before the first await.
|
|
const picker = this.#showOpenFilePicker(
|
|
systemPickerOptions(policy),
|
|
);
|
|
const handles = await this.#awaitPickerOrDispose(
|
|
picker,
|
|
request.signal,
|
|
);
|
|
const aborted = abortedResult(request.signal, "FILE_SELECT");
|
|
if (aborted) return observeSelection(this.#observer, aborted);
|
|
if (handles.length === 0) {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataSuccess(
|
|
Object.freeze({ kind: "DISMISSED" as const }),
|
|
),
|
|
);
|
|
}
|
|
const captured = await this.#captureHandles(
|
|
handles,
|
|
policy,
|
|
request.signal ?? new AbortController().signal,
|
|
);
|
|
return observeSelection(
|
|
this.#observer,
|
|
captured.ok
|
|
? browserDataSuccess(
|
|
Object.freeze({
|
|
kind: "SELECTED" as const,
|
|
files: captured.value,
|
|
}),
|
|
)
|
|
: captured,
|
|
);
|
|
} catch (error) {
|
|
if (error instanceof PickerDisposedError) {
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataFailure("ABORTED", "FILE_SELECT"),
|
|
);
|
|
}
|
|
if (error instanceof DOMException && error.name === "AbortError") {
|
|
const aborted = abortedResult(input.signal, "FILE_SELECT");
|
|
if (aborted) return observeSelection(this.#observer, aborted);
|
|
return observeSelection(
|
|
this.#observer,
|
|
browserDataSuccess(
|
|
Object.freeze({ kind: "DISMISSED" as const }),
|
|
),
|
|
);
|
|
}
|
|
return observeSelection(
|
|
this.#observer,
|
|
mapBrowserDataException(error, "FILE_SELECT"),
|
|
);
|
|
} finally {
|
|
this.#pending = false;
|
|
}
|
|
}
|
|
|
|
release(ref: LocalFileRef): void {
|
|
this.#releaseFile(ref);
|
|
}
|
|
|
|
dispose(): void {
|
|
if (this.#disposed) return;
|
|
this.#disposed = true;
|
|
this.#abortPending?.();
|
|
}
|
|
|
|
#awaitPickerOrDispose(
|
|
picker: Promise<readonly SystemFileHandle[]>,
|
|
signal?: AbortSignal,
|
|
): Promise<readonly SystemFileHandle[]> {
|
|
if (signal?.aborted) {
|
|
return Promise.reject(
|
|
new DOMException("Picker aborted", "AbortError"),
|
|
);
|
|
}
|
|
const operation = createAbortableOperation({ signal });
|
|
const abortPending = (): void => operation.close();
|
|
this.#abortPending = abortPending;
|
|
return operation.race(picker).then((outcome) => {
|
|
if (this.#abortPending === abortPending) {
|
|
this.#abortPending = undefined;
|
|
}
|
|
operation.close();
|
|
if (outcome.kind === "VALUE") return outcome.value;
|
|
throw outcome.kind === "REJECTED"
|
|
? outcome.reason
|
|
: outcome.terminal === "CALLER_ABORT"
|
|
? new DOMException("Picker aborted", "AbortError")
|
|
: new PickerDisposedError();
|
|
});
|
|
}
|
|
}
|
|
|
|
/** One observation per terminal selection result, shared by both pickers. */
|
|
function observeSelection(
|
|
observer: BrowserFileObserver | undefined,
|
|
result: BrowserDataResult<FileSelectionOutcome>,
|
|
): BrowserDataResult<FileSelectionOutcome> {
|
|
if (!result.ok) {
|
|
observeBrowserFile(observer, {
|
|
operation: "FILE_SELECT",
|
|
outcome: "FAILED",
|
|
failureCode: result.error.code,
|
|
});
|
|
} else if (result.value.kind === "DISMISSED") {
|
|
observeBrowserFile(observer, {
|
|
operation: "FILE_SELECT",
|
|
outcome: "DISMISSED",
|
|
});
|
|
} else {
|
|
const bytes = result.value.files.reduce(
|
|
(total, file) => total + file.sizeBytes,
|
|
0,
|
|
);
|
|
observeBrowserFile(observer, {
|
|
operation: "FILE_SELECT",
|
|
outcome: "SUCCESS",
|
|
byteBucket: byteBucket(bytes),
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
function pickerAcceptValue(
|
|
policy: RegisteredFileSelectionPolicy,
|
|
): string {
|
|
return policy.accept
|
|
.flatMap((rule) => [rule.mediaType, ...rule.extensions])
|
|
.join(",");
|
|
}
|
|
|
|
function systemPickerOptions(
|
|
policy: RegisteredFileSelectionPolicy,
|
|
): SystemOpenPickerOptions {
|
|
const types = policy.accept.map((rule) =>
|
|
Object.freeze({
|
|
accept: Object.freeze({
|
|
[rule.mediaType]: Object.freeze([...rule.extensions]),
|
|
}),
|
|
}),
|
|
);
|
|
return Object.freeze({
|
|
multiple: policy.multiple,
|
|
excludeAcceptAllOption: types.length > 0,
|
|
types: Object.freeze(types),
|
|
});
|
|
}
|
|
|
|
type SelectionRequestSnapshot = Readonly<{
|
|
policy: FilePolicyReference;
|
|
limits?: FileSelectionLimitReduction;
|
|
signal?: AbortSignal;
|
|
}>;
|
|
|
|
function snapshotSelectionRequest(input: {
|
|
policy: FilePolicyReference;
|
|
limits?: FileSelectionLimitReduction;
|
|
signal?: AbortSignal;
|
|
}): SelectionRequestSnapshot {
|
|
const policy = input.policy;
|
|
const limits = input.limits;
|
|
const signal = input.signal;
|
|
return Object.freeze({
|
|
policy,
|
|
...(limits
|
|
? {
|
|
limits: Object.freeze({
|
|
...(limits.maxCount !== undefined
|
|
? { maxCount: limits.maxCount }
|
|
: {}),
|
|
...(limits.maxFileBytes !== undefined
|
|
? { maxFileBytes: limits.maxFileBytes }
|
|
: {}),
|
|
...(limits.maxTotalBytes !== undefined
|
|
? { maxTotalBytes: limits.maxTotalBytes }
|
|
: {}),
|
|
}),
|
|
}
|
|
: {}),
|
|
...(signal ? { signal } : {}),
|
|
});
|
|
}
|
|
|
|
function isUsableFileInput(
|
|
input: HTMLInputElement,
|
|
getAttribute: (name: string) => string | null,
|
|
): boolean {
|
|
if (input.type !== "file" || !input.isConnected) return false;
|
|
if ((input.labels?.length ?? 0) > 0) return true;
|
|
return (
|
|
(getAttribute("aria-label")?.trim().length ?? 0) > 0 ||
|
|
(getAttribute("aria-labelledby")?.trim().length ?? 0) > 0
|
|
);
|
|
}
|
|
|
|
class PickerDisposedError extends Error {
|
|
constructor() {
|
|
super("Picker runtime disposed");
|
|
this.name = "PickerDisposedError";
|
|
}
|
|
}
|