@ng-native/device 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/accessibility.d.ts +5 -3
- package/dist/accessibility.js +5 -0
- package/dist/accessibility.js.map +1 -1
- package/dist/desktop-options.d.ts +5 -0
- package/dist/desktop-options.js +6 -1
- package/dist/desktop-options.js.map +1 -1
- package/dist/dialogs.js +4 -2
- package/dist/dialogs.js.map +1 -1
- package/dist/dock.d.ts +2 -0
- package/dist/dock.js +4 -1
- package/dist/dock.js.map +1 -1
- package/dist/menu-model.d.ts +11 -9
- package/dist/menu-model.js +72 -9
- package/dist/menu-model.js.map +1 -1
- package/dist/menus.js +2 -2
- package/dist/menus.js.map +1 -1
- package/dist/os-support.d.ts +1 -1
- package/dist/os-support.js +188 -62
- package/dist/os-support.js.map +1 -1
- package/dist/os-version.d.ts +3 -1
- package/dist/os-version.js +3 -1
- package/dist/os-version.js.map +1 -1
- package/dist/os.d.ts +5 -3
- package/dist/os.js +5 -3
- package/dist/os.js.map +1 -1
- package/dist/processes.d.ts +2 -0
- package/dist/processes.js +4 -1
- package/dist/processes.js.map +1 -1
- package/dist/safe-area.d.ts +12 -3
- package/dist/safe-area.js +16 -4
- package/dist/safe-area.js.map +1 -1
- package/dist/sharing.js +4 -3
- package/dist/sharing.js.map +1 -1
- package/dist/spawn-rules.js +8 -0
- package/dist/spawn-rules.js.map +1 -1
- package/dist/tray.d.ts +6 -3
- package/dist/tray.js +8 -4
- package/dist/tray.js.map +1 -1
- package/dist/vibration.d.ts +1 -1
- package/dist/vibration.js +3 -3
- package/dist/vibration.js.map +1 -1
- package/dist/window-restore.js +1 -1
- package/dist/window-restore.js.map +1 -1
- package/package.json +2 -2
package/dist/processes.d.ts
CHANGED
|
@@ -81,6 +81,8 @@ export declare class Processes {
|
|
|
81
81
|
/** Overridden in a test to start the app with an environment, and to fake programs. */
|
|
82
82
|
static readonly SOURCE: InjectionToken<NativeProcesses | null>;
|
|
83
83
|
private readonly native;
|
|
84
|
+
/** The OS the app runs on, whose template script rebuilds the host. */
|
|
85
|
+
private readonly os;
|
|
84
86
|
private readonly capabilities;
|
|
85
87
|
private readonly running;
|
|
86
88
|
/**
|
package/dist/processes.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* arrive on `ngNativeProcesses`.
|
|
15
15
|
*/
|
|
16
16
|
import { InjectionToken, Service, inject, signal } from '@angular/core';
|
|
17
|
+
import { injectOs } from "./os.js";
|
|
17
18
|
import { reactNative } from "./react-native.js";
|
|
18
19
|
import { compileCapability, filterEnvironment, matchSpawn, } from "./spawn-rules.js";
|
|
19
20
|
import * as i0 from "@angular/core";
|
|
@@ -60,6 +61,8 @@ export class Processes {
|
|
|
60
61
|
/** Overridden in a test to start the app with an environment, and to fake programs. */
|
|
61
62
|
static SOURCE = new InjectionToken('angular-native.processesSource', { factory: processesSource });
|
|
62
63
|
native = inject(Processes.SOURCE);
|
|
64
|
+
/** The OS the app runs on, whose template script rebuilds the host. */
|
|
65
|
+
os = injectOs();
|
|
63
66
|
capabilities = (this.native?.spawnCapabilities ?? []).map(compileCapability);
|
|
64
67
|
running = new Map();
|
|
65
68
|
/**
|
|
@@ -93,7 +96,7 @@ export class Processes {
|
|
|
93
96
|
if (!match) {
|
|
94
97
|
throw new UndeclaredCapabilityError(`[angular-native] ${program} ${JSON.stringify(args)} matches no spawn capability. ` +
|
|
95
98
|
'Declare the program and its arguments in capabilities.spawn of the @ng-native/desktop ' +
|
|
96
|
-
|
|
99
|
+
`plugin options in app.json, then rebuild with npm run ${this.os}.`);
|
|
97
100
|
}
|
|
98
101
|
const env = filterEnvironment(options.env ?? this.env, native.envNames ?? Object.keys(this.env));
|
|
99
102
|
this.spawning++;
|
package/dist/processes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processes.js","sourceRoot":"","sources":["../src/processes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;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AAM,CAAC,CAAC;YAC3C,IAAI,KAAK;gBAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;gBACxB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;YAC3C,OAAO;QACT,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC1B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAClC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;YAC3D,OAAO;QACT,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;YAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IAED,8CAA8C;IAC9C,WAAW;QACT,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;IACvB,CAAC;uGA7HU,SAAS;wGAAT,SAAS;;2FAAT,SAAS;kBADrB,OAAO","sourcesContent":["/**\n * `Processes`: the app's environment on a desktop OS, and the programs it declares, run with\n * `spawn`. Absent on iOS, Android and the web, which give an app neither.\n *\n * The host contract, on the `NgNativeProcesses` module:\n *\n * - `getConstants()` answers `env` (the environment, already filtered to `capabilities.env`),\n * `envNames` (`capabilities.env` itself), `spawn` (the declared spawn capabilities) and `resolved` (where each declared bare name was\n * pinned at startup, or null where it is absent).\n * - `spawn(program, args, cwd, env)` runs the program, never through a shell, after checking the\n * call against the declaration again, and answers a handle; it rejects an undeclared call.\n * - `write(handle, data)`, `closeStdin(handle)` and `kill(handle, signal)`.\n * - `{ type: 'stdout' | 'stderr', handle, data }` and `{ type: 'exit', handle, code, signal }`\n * arrive on `ngNativeProcesses`.\n */\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { reactNative } from './react-native.ts';\nimport {\n compileCapability,\n filterEnvironment,\n matchSpawn,\n type CompiledCapability,\n type SpawnCapability,\n} from './spawn-rules.ts';\n\n/** How a spawned program ended: its exit code, or the signal that stopped it. */\nexport interface ProcessExit {\n readonly code: number | null;\n readonly signal: string | null;\n}\n\n/** What the host reports about a spawned program. */\nexport type ProcessEvent =\n | { readonly type: 'stdout' | 'stderr'; readonly handle: number; readonly data: string }\n | {\n readonly type: 'exit';\n readonly handle: number;\n readonly code: number | null;\n readonly signal: string | null;\n };\n\n/** What the desktop host's module reports, and what a test fakes. */\nexport interface NativeProcesses {\n /** The environment variables the app was started with, filtered to those it declares. */\n readonly env: Readonly<Record<string, string>>;\n /** The variables `capabilities.env` declares: all a spawned program may be given. */\n readonly envNames?: readonly string[];\n /** The declared spawn capabilities. None declared, nothing may be spawned. */\n readonly spawnCapabilities?: readonly SpawnCapability[];\n /** Where each declared bare program name was pinned at startup, or null where it is absent. */\n readonly resolved?: Readonly<Record<string, string | null>>;\n spawn?(\n program: string,\n args: readonly string[],\n cwd: string | null,\n env: Readonly<Record<string, string>>,\n ): Promise<number>;\n write?(handle: number, data: string): void;\n closeStdin?(handle: number): void;\n kill?(handle: number, signal: string): void;\n subscribe?(listener: (event: ProcessEvent) => void): () => void;\n}\n\n/** A program `spawn` started. */\nexport interface ChildProcess {\n /** Settles once the program has ended. */\n readonly exit: Promise<ProcessExit>;\n /** Hear what the program writes to standard output. Answers the function that stops it. */\n onStdout(listener: (chunk: string) => void): () => void;\n /** Hear what the program writes to standard error. */\n onStderr(listener: (chunk: string) => void): () => void;\n /** Write to the program's standard input. */\n write(data: string): void;\n /** Close the program's standard input. */\n end(): void;\n /** Stop the program. `SIGTERM` unless it says. */\n kill(signal?: 'SIGTERM' | 'SIGINT' | 'SIGKILL' | 'SIGHUP'): void;\n}\n\n/** What `spawn` takes beside the program and its arguments. */\nexport interface SpawnOptions {\n /** The working directory. The app's own when unset. */\n readonly cwd?: string;\n /**\n * The program's environment. Only the variables the app declares in `capabilities.env` are\n * passed; the rest are left out. Unset, it gets `Processes.env`.\n */\n readonly env?: Readonly<Record<string, string>>;\n}\n\n/** A spawn the app did not declare: a misconfiguration, so it throws rather than doing nothing. */\nexport class UndeclaredCapabilityError extends Error {\n override readonly name = 'UndeclaredCapabilityError';\n}\n\n/** The desktop host's TurboModule. */\ninterface ProcessesTurboModule {\n getConstants?(): {\n env?: Record<string, string>;\n envNames?: string[];\n spawn?: SpawnCapability[];\n resolved?: Record<string, string | null>;\n };\n spawn?(program: string, args: string[], cwd: string | null, env: object): Promise<number>;\n write?(handle: number, data: string): void;\n closeStdin?(handle: number): void;\n kill?(handle: number, signal: string): void;\n}\n\n/** React Native's event emitter, which the host's process events arrive on. */\ntype Emitter = {\n addListener(event: string, listener: (event: unknown) => void): { remove(): void };\n};\n\n/** The desktop host's module, or null where there is none: every OS but a desktop one. */\nfunction processesSource(): NativeProcesses | null {\n const native = reactNative() as {\n TurboModuleRegistry?: { get?(name: string): unknown };\n DeviceEventEmitter?: Emitter;\n } | null;\n const module = native?.TurboModuleRegistry?.get?.('NgNativeProcesses') as\n ProcessesTurboModule | null | undefined;\n const constants = module?.getConstants?.();\n if (!module || !constants?.env) return null;\n return {\n ...declared(constants.env, constants),\n ...processMethods(module, native?.DeviceEventEmitter),\n };\n}\n\n/** What the host's constants declare, with what an older host leaves out filled in. */\nfunction declared(\n env: Record<string, string>,\n constants: ReturnType<NonNullable<ProcessesTurboModule['getConstants']>>,\n) {\n return {\n env,\n envNames: constants.envNames ?? Object.keys(env),\n spawnCapabilities: constants.spawn ?? [],\n resolved: constants.resolved ?? {},\n };\n}\n\n/** The module's methods, as the service calls them. */\nfunction processMethods(module: ProcessesTurboModule, emitter: Emitter | undefined) {\n return {\n spawn:\n module.spawn &&\n ((...call: Parameters<NonNullable<NativeProcesses['spawn']>>) =>\n module.spawn!(call[0], [...call[1]], call[2], call[3])),\n write: (handle: number, data: string) => module.write?.(handle, data),\n closeStdin: (handle: number) => module.closeStdin?.(handle),\n kill: (handle: number, signal: string) => module.kill?.(handle, signal),\n subscribe: (listener: (event: ProcessEvent) => void) => {\n const subscription = emitter?.addListener('ngNativeProcesses', (event) =>\n listener(event as ProcessEvent),\n );\n return () => subscription?.remove();\n },\n };\n}\n\n/** One spawned program's listeners, until it exits. */\ninterface Running {\n readonly stdout: Set<(chunk: string) => void>;\n readonly stderr: Set<(chunk: string) => void>;\n exited(exit: ProcessExit): void;\n}\n\n@Service()\nexport class Processes {\n /** Overridden in a test to start the app with an environment, and to fake programs. */\n static readonly SOURCE = new InjectionToken<NativeProcesses | null>(\n 'angular-native.processesSource',\n { factory: processesSource },\n );\n\n private readonly native = inject(Processes.SOURCE);\n private readonly capabilities: readonly CompiledCapability[] = (\n this.native?.spawnCapabilities ?? []\n ).map(compileCapability);\n private readonly running = new Map<number, Running>();\n /**\n * What the host said of a program before its spawn resolved with the handle: its reader threads\n * can queue a short program's output and exit ahead of that answer.\n */\n private readonly early = new Map<number, ProcessEvent[]>();\n /** Spawns waiting on the host, while which an unknown handle's events are kept. */\n private spawning = 0;\n /** Held events not yet replayed, by handle: live ones queue behind them, in order. */\n private readonly replaying = new Map<number, ProcessEvent[]>();\n private readonly unsubscribe = this.native?.subscribe?.((event) => this.heard(event)) ?? null;\n\n /** Whether the OS gives the app processes: a desktop OS with the desktop host's module. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /** The environment variables, as the app was started with them. Empty where absent. */\n readonly env: Readonly<Record<string, string>> = Object.freeze({ ...this.native?.env });\n\n /**\n * Run `program` with `args`, never through a shell. The call has to match a capability the app\n * declares in app.json; one that does not throws `UndeclaredCapabilityError`. Resolves to null\n * where processes are absent.\n *\n * const git = await processes.spawn('git', ['status', '--porcelain'], { cwd: repo });\n * git?.onStdout((chunk) => output.update((text) => text + chunk));\n * const { code } = (await git?.exit) ?? { code: null };\n */\n async spawn(\n program: string,\n args: readonly string[] = [],\n options: SpawnOptions = {},\n ): Promise<ChildProcess | null> {\n const native = this.native;\n if (!native?.spawn) return null;\n const match = matchSpawn(this.capabilities, program, args, native.resolved ?? {});\n if (!match) {\n throw new UndeclaredCapabilityError(\n `[angular-native] ${program} ${JSON.stringify(args)} matches no spawn capability. ` +\n 'Declare the program and its arguments in capabilities.spawn of the @ng-native/desktop ' +\n 'plugin options in app.json, then rebuild with npm run macos.',\n );\n }\n const env = filterEnvironment(\n options.env ?? this.env,\n native.envNames ?? Object.keys(this.env),\n );\n this.spawning++;\n let handle: number;\n try {\n handle = await native.spawn(match.path, args, options.cwd ?? null, env);\n } finally {\n this.spawning--;\n }\n const child = this.child(native, handle);\n // Nothing is waiting for the rest: they were another program's, gone before the app heard it.\n if (!this.spawning) this.early.clear();\n return child;\n }\n\n private child(native: NativeProcesses, handle: number): ChildProcess {\n const stdout = new Set<(chunk: string) => void>();\n const stderr = new Set<(chunk: string) => void>();\n let exited!: (exit: ProcessExit) => void;\n const exit = new Promise<ProcessExit>((resolve) => (exited = resolve));\n this.running.set(handle, { stdout, stderr, exited });\n const early = this.early.get(handle);\n if (early) {\n this.early.delete(handle);\n this.replaying.set(handle, early);\n // A turn later, as the host's events arrive, so the caller has listened by then.\n setTimeout(() => {\n this.replaying.delete(handle);\n early.forEach((event) => this.heard(event));\n }, 0);\n }\n const listen = (set: Set<(chunk: string) => void>, listener: (chunk: string) => void) => {\n set.add(listener);\n return () => void set.delete(listener);\n };\n return {\n exit,\n onStdout: (listener) => listen(stdout, listener),\n onStderr: (listener) => listen(stderr, listener),\n write: (data) => native.write?.(handle, data),\n end: () => native.closeStdin?.(handle),\n kill: (signal = 'SIGTERM') => native.kill?.(handle, signal),\n };\n }\n\n private heard(event: ProcessEvent): void {\n const queued = this.replaying.get(event.handle);\n if (queued) {\n queued.push(event);\n return;\n }\n const running = this.running.get(event.handle);\n if (!running) {\n if (!this.spawning) return;\n const early = this.early.get(event.handle);\n if (early) early.push(event);\n else this.early.set(event.handle, [event]);\n return;\n }\n if (event.type === 'exit') {\n this.running.delete(event.handle);\n running.exited({ code: event.code, signal: event.signal });\n return;\n }\n for (const listener of running[event.type]) listener(event.data);\n }\n\n /** Stop hearing the host, as the app goes. */\n ngOnDestroy(): void {\n this.unsubscribe?.();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"processes.js","sourceRoot":"","sources":["../src/processes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAe,MAAM,eAAe,CAAC;AACrF,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,GAGX,MAAM,kBAAkB,CAAC;;AAmE1B,mGAAmG;AACnG,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IAChC,IAAI,GAAG,2BAA2B,CAAC;CACtD;AAqBD,0FAA0F;AAC1F,SAAS,eAAe;IACtB,MAAM,MAAM,GAAG,WAAW,EAGlB,CAAC;IACT,MAAM,MAAM,GAAG,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,CAAC,mBAAmB,CAC5B,CAAC;IAC1C,MAAM,SAAS,GAAG,MAAM,EAAE,YAAY,EAAE,EAAE,CAAC;IAC3C,IAAI,CAAC,MAAM,IAAI,CAAC,SAAS,EAAE,GAAG;QAAE,OAAO,IAAI,CAAC;IAC5C,OAAO;QACL,GAAG,QAAQ,CAAC,SAAS,CAAC,GAAG,EAAE,SAAS,CAAC;QACrC,GAAG,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,kBAAkB,CAAC;KACtD,CAAC;AACJ,CAAC;AAED,uFAAuF;AACvF,SAAS,QAAQ,CACf,GAA2B,EAC3B,SAAwE;IAExE,OAAO;QACL,GAAG;QACH,QAAQ,EAAE,SAAS,CAAC,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,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,CAAC,MAAM,CAAC,CAAC;QAChD,IAAI,MAAM,EAAE,CAAC;YACX,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACnB,OAAO;QACT,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC/C,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,IAAI,CAAC,IAAI,CAAC,QAAQ;gBAAE,OAAO;YAC3B,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAC3C,IAAI,KAAK;gBAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;gBACxB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;YAC3C,OAAO;QACT,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC1B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAClC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;YAC3D,OAAO;QACT,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;YAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IAED,8CAA8C;IAC9C,WAAW;QACT,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;IACvB,CAAC;uGA/HU,SAAS;wGAAT,SAAS;;2FAAT,SAAS;kBADrB,OAAO","sourcesContent":["/**\n * `Processes`: the app's environment on a desktop OS, and the programs it declares, run with\n * `spawn`. Absent on iOS, Android and the web, which give an app neither.\n *\n * The host contract, on the `NgNativeProcesses` module:\n *\n * - `getConstants()` answers `env` (the environment, already filtered to `capabilities.env`),\n * `envNames` (`capabilities.env` itself), `spawn` (the declared spawn capabilities) and `resolved` (where each declared bare name was\n * pinned at startup, or null where it is absent).\n * - `spawn(program, args, cwd, env)` runs the program, never through a shell, after checking the\n * call against the declaration again, and answers a handle; it rejects an undeclared call.\n * - `write(handle, data)`, `closeStdin(handle)` and `kill(handle, signal)`.\n * - `{ type: 'stdout' | 'stderr', handle, data }` and `{ type: 'exit', handle, code, signal }`\n * arrive on `ngNativeProcesses`.\n */\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { injectOs } from './os.ts';\nimport { reactNative } from './react-native.ts';\nimport {\n compileCapability,\n filterEnvironment,\n matchSpawn,\n type CompiledCapability,\n type SpawnCapability,\n} from './spawn-rules.ts';\n\n/** How a spawned program ended: its exit code, or the signal that stopped it. */\nexport interface ProcessExit {\n readonly code: number | null;\n readonly signal: string | null;\n}\n\n/** What the host reports about a spawned program. */\nexport type ProcessEvent =\n | { readonly type: 'stdout' | 'stderr'; readonly handle: number; readonly data: string }\n | {\n readonly type: 'exit';\n readonly handle: number;\n readonly code: number | null;\n readonly signal: string | null;\n };\n\n/** What the desktop host's module reports, and what a test fakes. */\nexport interface NativeProcesses {\n /** The environment variables the app was started with, filtered to those it declares. */\n readonly env: Readonly<Record<string, string>>;\n /** The variables `capabilities.env` declares: all a spawned program may be given. */\n readonly envNames?: readonly string[];\n /** The declared spawn capabilities. None declared, nothing may be spawned. */\n readonly spawnCapabilities?: readonly SpawnCapability[];\n /** Where each declared bare program name was pinned at startup, or null where it is absent. */\n readonly resolved?: Readonly<Record<string, string | null>>;\n spawn?(\n program: string,\n args: readonly string[],\n cwd: string | null,\n env: Readonly<Record<string, string>>,\n ): Promise<number>;\n write?(handle: number, data: string): void;\n closeStdin?(handle: number): void;\n kill?(handle: number, signal: string): void;\n subscribe?(listener: (event: ProcessEvent) => void): () => void;\n}\n\n/** A program `spawn` started. */\nexport interface ChildProcess {\n /** Settles once the program has ended. */\n readonly exit: Promise<ProcessExit>;\n /** Hear what the program writes to standard output. Answers the function that stops it. */\n onStdout(listener: (chunk: string) => void): () => void;\n /** Hear what the program writes to standard error. */\n onStderr(listener: (chunk: string) => void): () => void;\n /** Write to the program's standard input. */\n write(data: string): void;\n /** Close the program's standard input. */\n end(): void;\n /** Stop the program. `SIGTERM` unless it says. */\n kill(signal?: 'SIGTERM' | 'SIGINT' | 'SIGKILL' | 'SIGHUP'): void;\n}\n\n/** What `spawn` takes beside the program and its arguments. */\nexport interface SpawnOptions {\n /** The working directory. The app's own when unset. */\n readonly cwd?: string;\n /**\n * The program's environment. Only the variables the app declares in `capabilities.env` are\n * passed; the rest are left out. Unset, it gets `Processes.env`.\n */\n readonly env?: Readonly<Record<string, string>>;\n}\n\n/** A spawn the app did not declare: a misconfiguration, so it throws rather than doing nothing. */\nexport class UndeclaredCapabilityError extends Error {\n override readonly name = 'UndeclaredCapabilityError';\n}\n\n/** The desktop host's TurboModule. */\ninterface ProcessesTurboModule {\n getConstants?(): {\n env?: Record<string, string>;\n envNames?: string[];\n spawn?: SpawnCapability[];\n resolved?: Record<string, string | null>;\n };\n spawn?(program: string, args: string[], cwd: string | null, env: object): Promise<number>;\n write?(handle: number, data: string): void;\n closeStdin?(handle: number): void;\n kill?(handle: number, signal: string): void;\n}\n\n/** React Native's event emitter, which the host's process events arrive on. */\ntype Emitter = {\n addListener(event: string, listener: (event: unknown) => void): { remove(): void };\n};\n\n/** The desktop host's module, or null where there is none: every OS but a desktop one. */\nfunction processesSource(): NativeProcesses | null {\n const native = reactNative() as {\n TurboModuleRegistry?: { get?(name: string): unknown };\n DeviceEventEmitter?: Emitter;\n } | null;\n const module = native?.TurboModuleRegistry?.get?.('NgNativeProcesses') as\n ProcessesTurboModule | null | undefined;\n const constants = module?.getConstants?.();\n if (!module || !constants?.env) return null;\n return {\n ...declared(constants.env, constants),\n ...processMethods(module, native?.DeviceEventEmitter),\n };\n}\n\n/** What the host's constants declare, with what an older host leaves out filled in. */\nfunction declared(\n env: Record<string, string>,\n constants: ReturnType<NonNullable<ProcessesTurboModule['getConstants']>>,\n) {\n return {\n env,\n envNames: constants.envNames ?? Object.keys(env),\n spawnCapabilities: constants.spawn ?? [],\n resolved: constants.resolved ?? {},\n };\n}\n\n/** The module's methods, as the service calls them. */\nfunction processMethods(module: ProcessesTurboModule, emitter: Emitter | undefined) {\n return {\n spawn:\n module.spawn &&\n ((...call: Parameters<NonNullable<NativeProcesses['spawn']>>) =>\n module.spawn!(call[0], [...call[1]], call[2], call[3])),\n write: (handle: number, data: string) => module.write?.(handle, data),\n closeStdin: (handle: number) => module.closeStdin?.(handle),\n kill: (handle: number, signal: string) => module.kill?.(handle, signal),\n subscribe: (listener: (event: ProcessEvent) => void) => {\n const subscription = emitter?.addListener('ngNativeProcesses', (event) =>\n listener(event as ProcessEvent),\n );\n return () => subscription?.remove();\n },\n };\n}\n\n/** One spawned program's listeners, until it exits. */\ninterface Running {\n readonly stdout: Set<(chunk: string) => void>;\n readonly stderr: Set<(chunk: string) => void>;\n exited(exit: ProcessExit): void;\n}\n\n@Service()\nexport class Processes {\n /** Overridden in a test to start the app with an environment, and to fake programs. */\n static readonly SOURCE = new InjectionToken<NativeProcesses | null>(\n 'angular-native.processesSource',\n { factory: processesSource },\n );\n\n private readonly native = inject(Processes.SOURCE);\n /** The OS the app runs on, whose template script rebuilds the host. */\n private readonly os = injectOs();\n private readonly capabilities: readonly CompiledCapability[] = (\n this.native?.spawnCapabilities ?? []\n ).map(compileCapability);\n private readonly running = new Map<number, Running>();\n /**\n * What the host said of a program before its spawn resolved with the handle: its reader threads\n * can queue a short program's output and exit ahead of that answer.\n */\n private readonly early = new Map<number, ProcessEvent[]>();\n /** Spawns waiting on the host, while which an unknown handle's events are kept. */\n private spawning = 0;\n /** Held events not yet replayed, by handle: live ones queue behind them, in order. */\n private readonly replaying = new Map<number, ProcessEvent[]>();\n private readonly unsubscribe = this.native?.subscribe?.((event) => this.heard(event)) ?? null;\n\n /** Whether the OS gives the app processes: a desktop OS with the desktop host's module. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /** The environment variables, as the app was started with them. Empty where absent. */\n readonly env: Readonly<Record<string, string>> = Object.freeze({ ...this.native?.env });\n\n /**\n * Run `program` with `args`, never through a shell. The call has to match a capability the app\n * declares in app.json; one that does not throws `UndeclaredCapabilityError`. Resolves to null\n * where processes are absent.\n *\n * const git = await processes.spawn('git', ['status', '--porcelain'], { cwd: repo });\n * git?.onStdout((chunk) => output.update((text) => text + chunk));\n * const { code } = (await git?.exit) ?? { code: null };\n */\n async spawn(\n program: string,\n args: readonly string[] = [],\n options: SpawnOptions = {},\n ): Promise<ChildProcess | null> {\n const native = this.native;\n if (!native?.spawn) return null;\n const match = matchSpawn(this.capabilities, program, args, native.resolved ?? {});\n if (!match) {\n throw new UndeclaredCapabilityError(\n `[angular-native] ${program} ${JSON.stringify(args)} matches no spawn capability. ` +\n 'Declare the program and its arguments in capabilities.spawn of the @ng-native/desktop ' +\n `plugin options in app.json, then rebuild with npm run ${this.os}.`,\n );\n }\n const env = filterEnvironment(\n options.env ?? this.env,\n native.envNames ?? Object.keys(this.env),\n );\n this.spawning++;\n let handle: number;\n try {\n handle = await native.spawn(match.path, args, options.cwd ?? null, env);\n } finally {\n this.spawning--;\n }\n const child = this.child(native, handle);\n // Nothing is waiting for the rest: they were another program's, gone before the app heard it.\n if (!this.spawning) this.early.clear();\n return child;\n }\n\n private child(native: NativeProcesses, handle: number): ChildProcess {\n const stdout = new Set<(chunk: string) => void>();\n const stderr = new Set<(chunk: string) => void>();\n let exited!: (exit: ProcessExit) => void;\n const exit = new Promise<ProcessExit>((resolve) => (exited = resolve));\n this.running.set(handle, { stdout, stderr, exited });\n const early = this.early.get(handle);\n if (early) {\n this.early.delete(handle);\n this.replaying.set(handle, early);\n // A turn later, as the host's events arrive, so the caller has listened by then.\n setTimeout(() => {\n this.replaying.delete(handle);\n early.forEach((event) => this.heard(event));\n }, 0);\n }\n const listen = (set: Set<(chunk: string) => void>, listener: (chunk: string) => void) => {\n set.add(listener);\n return () => void set.delete(listener);\n };\n return {\n exit,\n onStdout: (listener) => listen(stdout, listener),\n onStderr: (listener) => listen(stderr, listener),\n write: (data) => native.write?.(handle, data),\n end: () => native.closeStdin?.(handle),\n kill: (signal = 'SIGTERM') => native.kill?.(handle, signal),\n };\n }\n\n private heard(event: ProcessEvent): void {\n const queued = this.replaying.get(event.handle);\n if (queued) {\n queued.push(event);\n return;\n }\n const running = this.running.get(event.handle);\n if (!running) {\n if (!this.spawning) return;\n const early = this.early.get(event.handle);\n if (early) early.push(event);\n else this.early.set(event.handle, [event]);\n return;\n }\n if (event.type === 'exit') {\n this.running.delete(event.handle);\n running.exited({ code: event.code, signal: event.signal });\n return;\n }\n for (const listener of running[event.type]) listener(event.data);\n }\n\n /** Stop hearing the host, as the app goes. */\n ngOnDestroy(): void {\n this.unsubscribe?.();\n }\n}\n"]}
|
package/dist/safe-area.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ export declare class SafeArea {
|
|
|
33
33
|
private readonly current;
|
|
34
34
|
private readonly measured;
|
|
35
35
|
private readonly controls;
|
|
36
|
+
private readonly trailingControls;
|
|
36
37
|
/** What each provider still up last reported, the latest last. */
|
|
37
38
|
private readonly reports;
|
|
38
39
|
private reporter;
|
|
@@ -50,17 +51,25 @@ export declare class SafeArea {
|
|
|
50
51
|
* On macOS, how far the window's close, minimise and zoom buttons reach into the reporting
|
|
51
52
|
* pane from its leading edge: what `--safe-area-inset-titlebar-leading` holds. Their width in a
|
|
52
53
|
* window with no sidebar and in the sidebar pane under them; zero in the content pane beside a
|
|
53
|
-
* sidebar, which they do not reach
|
|
54
|
-
*
|
|
54
|
+
* sidebar, which they do not reach. On Linux, the reach of the window controls on the leading
|
|
55
|
+
* side, in a window whose content runs under its header bar; zero on every other OS. One value
|
|
56
|
+
* for the app: the latest report's, not one per pane.
|
|
55
57
|
*/
|
|
56
58
|
readonly titlebarLeading: Signal<number>;
|
|
59
|
+
/**
|
|
60
|
+
* How far a desktop window's title bar controls reach into the reporting pane from its trailing
|
|
61
|
+
* edge: what `--safe-area-inset-titlebar-trailing` holds. Zero on macOS, whose controls are on
|
|
62
|
+
* the leading side, on Linux in a window whose content stays below its header bar (the default
|
|
63
|
+
* title bar), and on every OS with no title bar. One value for the app, as `titlebarLeading` is.
|
|
64
|
+
*/
|
|
65
|
+
readonly titlebarTrailing: Signal<number>;
|
|
57
66
|
/** Whether anything has reported yet, for a layout that would rather wait than jump. */
|
|
58
67
|
readonly known: Signal<boolean>;
|
|
59
68
|
/**
|
|
60
69
|
* Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from
|
|
61
70
|
* anywhere else is a number that stops matching the screen the moment the device rotates.
|
|
62
71
|
*/
|
|
63
|
-
report(insets: Insets, frame: Frame, from?: object, titlebarLeading?: number): void;
|
|
72
|
+
report(insets: Insets, frame: Frame, from?: object, titlebarLeading?: number, titlebarTrailing?: number): void;
|
|
64
73
|
/**
|
|
65
74
|
* Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the
|
|
66
75
|
* latest, what a provider still up last reported takes its place, or nothing when none is.
|
package/dist/safe-area.js
CHANGED
|
@@ -25,6 +25,8 @@ export class SafeArea {
|
|
|
25
25
|
...(ngDevMode ? [{ debugName: "measured" }] : /* istanbul ignore next */ []));
|
|
26
26
|
controls = signal(0, /* @ts-ignore */
|
|
27
27
|
...(ngDevMode ? [{ debugName: "controls" }] : /* istanbul ignore next */ []));
|
|
28
|
+
trailingControls = signal(0, /* @ts-ignore */
|
|
29
|
+
...(ngDevMode ? [{ debugName: "trailingControls" }] : /* istanbul ignore next */ []));
|
|
28
30
|
/** What each provider still up last reported, the latest last. */
|
|
29
31
|
reports = new Map();
|
|
30
32
|
reporter = null;
|
|
@@ -42,10 +44,18 @@ export class SafeArea {
|
|
|
42
44
|
* On macOS, how far the window's close, minimise and zoom buttons reach into the reporting
|
|
43
45
|
* pane from its leading edge: what `--safe-area-inset-titlebar-leading` holds. Their width in a
|
|
44
46
|
* window with no sidebar and in the sidebar pane under them; zero in the content pane beside a
|
|
45
|
-
* sidebar, which they do not reach
|
|
46
|
-
*
|
|
47
|
+
* sidebar, which they do not reach. On Linux, the reach of the window controls on the leading
|
|
48
|
+
* side, in a window whose content runs under its header bar; zero on every other OS. One value
|
|
49
|
+
* for the app: the latest report's, not one per pane.
|
|
47
50
|
*/
|
|
48
51
|
titlebarLeading = this.controls.asReadonly();
|
|
52
|
+
/**
|
|
53
|
+
* How far a desktop window's title bar controls reach into the reporting pane from its trailing
|
|
54
|
+
* edge: what `--safe-area-inset-titlebar-trailing` holds. Zero on macOS, whose controls are on
|
|
55
|
+
* the leading side, on Linux in a window whose content stays below its header bar (the default
|
|
56
|
+
* title bar), and on every OS with no title bar. One value for the app, as `titlebarLeading` is.
|
|
57
|
+
*/
|
|
58
|
+
titlebarTrailing = this.trailingControls.asReadonly();
|
|
49
59
|
/** Whether anything has reported yet, for a layout that would rather wait than jump. */
|
|
50
60
|
known = computed(() => this.measured() !== null, /* @ts-ignore */
|
|
51
61
|
...(ngDevMode ? [{ debugName: "known" }] : /* istanbul ignore next */ []));
|
|
@@ -53,15 +63,16 @@ export class SafeArea {
|
|
|
53
63
|
* Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from
|
|
54
64
|
* anywhere else is a number that stops matching the screen the moment the device rotates.
|
|
55
65
|
*/
|
|
56
|
-
report(insets, frame, from, titlebarLeading = 0) {
|
|
66
|
+
report(insets, frame, from, titlebarLeading = 0, titlebarTrailing = 0) {
|
|
57
67
|
this.current.set(insets);
|
|
58
68
|
this.measured.set(frame);
|
|
59
69
|
this.controls.set(titlebarLeading);
|
|
70
|
+
this.trailingControls.set(titlebarTrailing);
|
|
60
71
|
this.reporter = from ?? null;
|
|
61
72
|
if (!from)
|
|
62
73
|
return;
|
|
63
74
|
this.reports.delete(from);
|
|
64
|
-
this.reports.set(from, { insets, frame, titlebarLeading });
|
|
75
|
+
this.reports.set(from, { insets, frame, titlebarLeading, titlebarTrailing });
|
|
65
76
|
}
|
|
66
77
|
/**
|
|
67
78
|
* Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the
|
|
@@ -77,6 +88,7 @@ export class SafeArea {
|
|
|
77
88
|
this.current.set(previous?.[1].insets ?? NOTHING);
|
|
78
89
|
this.measured.set(previous?.[1].frame ?? null);
|
|
79
90
|
this.controls.set(previous?.[1].titlebarLeading ?? 0);
|
|
91
|
+
this.trailingControls.set(previous?.[1].titlebarTrailing ?? 0);
|
|
80
92
|
return true;
|
|
81
93
|
}
|
|
82
94
|
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: SafeArea, deps: [], target: i0.ɵɵFactoryTarget.Service });
|
package/dist/safe-area.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"safe-area.js","sourceRoot":"","sources":["../src/safe-area.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAe,MAAM,eAAe,CAAC;;AAgBvE,MAAM,OAAO,GAAW,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AAGjE,MAAM,OAAO,QAAQ;IACnB,sFAAsF;IAC7E,SAAS,GAAoB,MAAM,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;IAE/C,OAAO,GAAG,MAAM,CAAS,OAAO;gFAAC,CAAC;IAClC,QAAQ,GAAG,MAAM,CAAe,IAAI;iFAAC,CAAC;IACtC,QAAQ,GAAG,MAAM,CAAC,CAAC;iFAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"safe-area.js","sourceRoot":"","sources":["../src/safe-area.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,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BAAgB,IAAI,CAAC,CAAC,CAAC;QAC/D,OAAO,IAAI,CAAC;IACd,CAAC;uGApFU,QAAQ;wGAAR,QAAQ;;2FAAR,QAAQ;kBADpB,OAAO","sourcesContent":["/**\n * How much of the screen belongs to the system: the notch, the status bar, the home indicator,\n * a rounded corner, and on Android the display cutout and the navigation bar.\n *\n * Unlike everything else here, this has no React Native module behind it. Insets are a property\n * of a *view*, not of the device, and the only thing that can report them is a native view inside\n * the window - `<safe-area-provider>` in `@ng-native/components`, which pushes what it\n * measures in here. That is also why the values start at zero: nothing is known until a view has\n * been laid out, which is one frame after the app mounts.\n *\n * Most layouts should not read this at all. A `<safe-area-view>` applies the insets natively,\n * without a round trip through JavaScript, and a screen in a native stack has its header do it.\n * This is for the cases neither covers: a floating button that must clear the home indicator, a\n * scroll view whose content inset is computed, a sheet drawing its own chrome.\n */\nimport { Service, computed, signal, type Signal } from '@angular/core';\n\nexport interface Insets {\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n readonly left: number;\n}\n\nexport interface Frame {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\nconst NOTHING: Insets = { top: 0, right: 0, bottom: 0, left: 0 };\n\n@Service()\nexport class SafeArea {\n /** Whether the service is here: on every OS, where it answers what the OS reports. */\n readonly available: Signal<boolean> = signal(true).asReadonly();\n\n private readonly current = signal<Insets>(NOTHING);\n private readonly measured = signal<Frame | null>(null);\n private readonly controls = signal(0);\n private readonly trailingControls = signal(0);\n /** What each provider still up last reported, the latest last. */\n private readonly reports = new Map<\n object,\n { insets: Insets; frame: Frame; titlebarLeading: number; titlebarTrailing: number }\n >();\n private reporter: object | null = null;\n\n /** What the system occupies on each edge, in points. */\n readonly insets: Signal<Insets> = this.current.asReadonly();\n\n /**\n * The provider's own frame: the area it was handed to lay out in.\n *\n * On Android 15 that includes the system bars, because the app draws behind them - which is why\n * `Screen.window` reads this rather than `Dimensions`. Null until the provider has laid out,\n * one frame after the app mounts, and again once every provider that reported is destroyed.\n */\n readonly frame: Signal<Frame | null> = this.measured.asReadonly();\n\n /**\n * On macOS, how far the window's close, minimise and zoom buttons reach into the reporting\n * pane from its leading edge: what `--safe-area-inset-titlebar-leading` holds. Their width in a\n * window with no sidebar and in the sidebar pane under them; zero in the content pane beside a\n * sidebar, which they do not reach. On Linux, the reach of the window controls on the leading\n * side, in a window whose content runs under its header bar; zero on every other OS. One value\n * for the app: the latest report's, not one per pane.\n */\n readonly titlebarLeading: Signal<number> = this.controls.asReadonly();\n\n /**\n * How far a desktop window's title bar controls reach into the reporting pane from its trailing\n * edge: what `--safe-area-inset-titlebar-trailing` holds. Zero on macOS, whose controls are on\n * the leading side, on Linux in a window whose content stays below its header bar (the default\n * title bar), and on every OS with no title bar. One value for the app, as `titlebarLeading` is.\n */\n readonly titlebarTrailing: Signal<number> = this.trailingControls.asReadonly();\n\n /** Whether anything has reported yet, for a layout that would rather wait than jump. */\n readonly known = computed(() => this.measured() !== null);\n\n /**\n * Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from\n * anywhere else is a number that stops matching the screen the moment the device rotates.\n */\n report(\n insets: Insets,\n frame: Frame,\n from?: object,\n titlebarLeading = 0,\n titlebarTrailing = 0,\n ): void {\n this.current.set(insets);\n this.measured.set(frame);\n this.controls.set(titlebarLeading);\n this.trailingControls.set(titlebarTrailing);\n this.reporter = from ?? null;\n if (!from) return;\n this.reports.delete(from);\n this.reports.set(from, { insets, frame, titlebarLeading, titlebarTrailing });\n }\n\n /**\n * Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the\n * latest, what a provider still up last reported takes its place, or nothing when none is.\n * True when the values changed.\n */\n withdraw(from: object): boolean {\n this.reports.delete(from);\n if (this.reporter !== from) return false;\n const [previous] = [...this.reports].slice(-1);\n this.reporter = previous?.[0] ?? null;\n this.current.set(previous?.[1].insets ?? NOTHING);\n this.measured.set(previous?.[1].frame ?? null);\n this.controls.set(previous?.[1].titlebarLeading ?? 0);\n this.trailingControls.set(previous?.[1].titlebarTrailing ?? 0);\n return true;\n }\n}\n"]}
|
package/dist/sharing.js
CHANGED
|
@@ -6,15 +6,16 @@
|
|
|
6
6
|
* means they changed their mind, and only the first is worth a confirmation or an analytics event.
|
|
7
7
|
*/
|
|
8
8
|
import { InjectionToken, Service, inject, signal } from '@angular/core';
|
|
9
|
+
import { isDesktopOs } from "./os.js";
|
|
9
10
|
import { reactNative } from "./react-native.js";
|
|
10
11
|
import * as i0 from "@angular/core";
|
|
11
12
|
export function sharingSource() {
|
|
12
13
|
const native = reactNative();
|
|
13
14
|
if (!native)
|
|
14
15
|
return null;
|
|
15
|
-
// React Native's Share has no
|
|
16
|
-
// share picker
|
|
17
|
-
if (native.Platform.OS
|
|
16
|
+
// React Native's Share has no desktop implementation: the desktop host's NgNativeSharing is the
|
|
17
|
+
// share picker on macOS and Linux, and without it sharing is absent.
|
|
18
|
+
if (isDesktopOs(native.Platform.OS)) {
|
|
18
19
|
return native.TurboModuleRegistry?.get('NgNativeSharing') ?? null;
|
|
19
20
|
}
|
|
20
21
|
const android = native.Platform.OS === 'android';
|
package/dist/sharing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sharing.js","sourceRoot":"","sources":["../src/sharing.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAe,MAAM,eAAe,CAAC;AACrF,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;;AAchD,MAAM,UAAU,aAAa;IAC3B,MAAM,MAAM,GAAG,WAAW,EAAE,CAAC;IAC7B,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,
|
|
1
|
+
{"version":3,"file":"sharing.js","sourceRoot":"","sources":["../src/sharing.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAe,MAAM,eAAe,CA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AAM,CAAC,CAAC;IAEjD,mFAAmF;IAC1E,SAAS,GAAoB,MAAM,CAAC,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;IAEhF;;;;;OAKG;IACH,KAAK,CAAC,KAAK,CAAC,OAAqB;QAC/B,IAAI,CAAC,IAAI,CAAC,MAAM;YAAE,OAAO,KAAK,CAAC;QAC/B,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG;YAAE,OAAO,KAAK,CAAC;QAEnD,IAAI,CAAC;YACH,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACpD,OAAO,MAAM,KAAK,cAAc,CAAC;QACnC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;uGA5BU,OAAO;wGAAP,OAAO;;2FAAP,OAAO;kBADnB,OAAO","sourcesContent":["/**\n * The system share sheet.\n *\n * `Share.share` resolves either way - dismissing the sheet is not an error - and the distinction\n * it draws is one a caller usually wants: `shared` means an app took the content, `dismissed`\n * means they changed their mind, and only the first is worth a confirmation or an analytics event.\n */\n\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { isDesktopOs } from './os.ts';\nimport { reactNative } from './react-native.ts';\n\nexport interface ShareRequest {\n /** What is being shared. At least one of these; iOS prefers `url` when both are present. */\n readonly message?: string;\n readonly url?: string;\n /** Android's dialog title, and iOS's mail subject. */\n readonly title?: string;\n}\n\nexport interface NativeSharing {\n share(request: ShareRequest): Promise<{ action: string; activityType?: string | null }>;\n}\n\nexport function sharingSource(): NativeSharing | null {\n const native = reactNative();\n if (!native) return null;\n // React Native's Share has no desktop implementation: the desktop host's NgNativeSharing is the\n // share picker on macOS and Linux, and without it sharing is absent.\n if (isDesktopOs(native.Platform.OS)) {\n return (native.TurboModuleRegistry?.get('NgNativeSharing') as NativeSharing | null) ?? null;\n }\n const android = native.Platform.OS === 'android';\n return { share: (request) => native.Share.share(android ? forAndroid(request) : request) };\n}\n\n/**\n * `Share.share` on Android reads `title` and `message` and nothing else - `url` is not a field\n * React Native's own Android module looks at, so a request built the iOS way, `{ url, title }`\n * with no `message`, opens a sheet with a title and an empty body and nothing to actually share.\n * React Native's own docs say as much: Android's `message` \"will often include a URL\". Folding it\n * in here is what makes `share({ url, title })` behave the same on both platforms, as the type\n * says it should.\n */\nfunction forAndroid(request: ShareRequest): ShareRequest {\n if (!request.url) return request;\n const message = request.message ? `${request.message}\\n${request.url}` : request.url;\n return { title: request.title, message };\n}\n\n@Service()\nexport class Sharing {\n /** Overridden in a test to answer the sheet without one opening. */\n static readonly SOURCE = new InjectionToken<NativeSharing | null>(\n 'angular-native.sharingSource',\n { factory: sharingSource },\n );\n\n private readonly native = inject(Sharing.SOURCE);\n\n /** Whether React Native's module is here. Where it is not, every call is inert. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /**\n * Open the share sheet. Resolves to whether anything took the content.\n *\n * Failures resolve to false rather than rejecting: the sheet failing to open and the user\n * closing it are the same outcome at the call site, and neither is exceptional.\n */\n async share(request: ShareRequest): Promise<boolean> {\n if (!this.native) return false;\n if (!request.message && !request.url) return false;\n\n try {\n const { action } = await this.native.share(request);\n return action === 'sharedAction';\n } catch {\n return false;\n }\n }\n}\n"]}
|
package/dist/spawn-rules.js
CHANGED
|
@@ -64,6 +64,14 @@ const REFUSED_PROGRAMS = new Set([
|
|
|
64
64
|
'pwsh',
|
|
65
65
|
'nice',
|
|
66
66
|
'nohup',
|
|
67
|
+
// Linux's: escalation (`pkexec`), a shell of its own (`busybox`), and leaving a Flatpak sandbox,
|
|
68
|
+
// the session or the mount namespace (`flatpak-spawn --host`, `systemd-run`, `nsenter`, `chroot`).
|
|
69
|
+
'pkexec',
|
|
70
|
+
'busybox',
|
|
71
|
+
'flatpak-spawn',
|
|
72
|
+
'systemd-run',
|
|
73
|
+
'nsenter',
|
|
74
|
+
'chroot',
|
|
67
75
|
]);
|
|
68
76
|
/** Windows batch files, which run through `cmd.exe` and so re-parse their arguments. */
|
|
69
77
|
const REFUSED_EXTENSIONS = ['.bat', '.cmd'];
|
package/dist/spawn-rules.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spawn-rules.js","sourceRoot":"","sources":["../src/spawn-rules.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAgCH;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAsB;IAC5C,UAAU;IACV,MAAM;IACN,WAAW;IACX,OAAO;IACP,mBAAmB;IACnB,gBAAgB;CACjB,CAAC;AAEF;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAC/B,IAAI;IACJ,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,IAAI;IACJ,KAAK;IACL,OAAO;IACP,MAAM;IACN,MAAM;IACN,IAAI;IACJ,WAAW;IACX,KAAK;IACL,YAAY;IACZ,MAAM;IACN,MAAM;IACN,OAAO;CACR,CAAC,CAAC;AAEH,wFAAwF;AACxF,MAAM,kBAAkB,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAE5C,MAAM,WAAW,GAAG,mDAAmD,CAAC;AAExE,+CAA+C;AAC/C,MAAM,OAAO,cAAe,SAAQ,KAAK;IACrB,IAAI,GAAG,gBAAgB,CAAC;CAC3C;AAED,oFAAoF;AACpF,SAAS,QAAQ,CAAC,OAAe;IAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACjD,OAAO,IAAI,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAClD,CAAC;AAED,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GAIG;AACH,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,MAAqB;IACnE,IAAI,cAAc,CAAC,OAAO,CAAC;QAAE,OAAO,IAAI,CAAC;IACzC,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;QACxC,CAAC,CAAC,CAAC,OAAO,CAAC;QACX,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,OAAO,EAAE,CAAC,CAAC;IAClD,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC;YAAE,SAAS;QAC9C,OAAO,MAAM,CAAC,MAAM,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACvD,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,2FAA2F;AAC3F,MAAM,UAAU,iBAAiB,CAC/B,GAAiD,EACjD,OAA0B;IAE1B,MAAM,QAAQ,GAA2B,EAAE,CAAC;IAC5C,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC/D,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,QAAQ,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;IACjF,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["/**\n * The rules a desktop app's declared spawn capabilities follow: which programs it may run, with\n * which arguments. Plain TypeScript with no imports, so the config plugin can check the declaration\n * at build time and `Processes` can refuse an undeclared call with a clear error before the\n * desktop host checks it again natively.\n *\n * An entry names a program and the arguments it may take:\n *\n * { program: '/usr/bin/git', args: ['clone', '{url:https://\\\\S+}', '{dir:[\\\\w.-]+}'] }\n *\n * Each argument is a literal, matched exactly, or a `{name:regex}` placeholder. A placeholder\n * followed by `...` matches zero or more arguments, each by the same rules.\n *\n * - A placeholder's pattern is anchored: it matches the whole argument, so `{branch:[a-z]+}`\n * never accepts `--upload-pack=...`.\n * - A placeholder never accepts an argument starting with `-` unless each alternative of its\n * pattern starts with one, so an option cannot be injected where a value was declared.\n * - No argument may hold a NUL character, which a C string would cut short.\n * - Shells, `env` and other programs that run their arguments as a command are refused as\n * programs, and so are Windows `.bat` and `.cmd` files, which `cmd.exe` re-parses (the BatBadBut\n * class of bug). `spawn` never goes through a shell.\n * - A program is an absolute path, or a bare name resolved once at startup on a fixed search path\n * (`SEARCH_PATH`), never the inherited `PATH`, and pinned there.\n *\n * The boundary guards against bugs and injected content, not against a hostile app.\n */\n\n/** A spawn capability as `app.json` declares it. */\nexport interface SpawnCapability {\n /** An absolute path, or a bare name resolved on `SEARCH_PATH` at startup. */\n readonly program: string;\n /** Literal arguments and `{name:regex}` placeholders, in order. */\n readonly args?: readonly string[];\n}\n\n/** One declared argument, parsed. */\nexport type ArgumentRule =\n | { readonly kind: 'literal'; readonly value: string }\n | {\n readonly kind: 'placeholder';\n readonly name: string;\n readonly pattern: RegExp;\n /** Whether each alternative of the pattern starts with `-`, so the value may be an option. */\n readonly option: boolean;\n /** `{name:regex}...`: zero or more arguments. */\n readonly repeated: boolean;\n };\n\n/** A spawn capability, checked and parsed. */\nexport interface CompiledCapability {\n readonly program: string;\n readonly args: readonly ArgumentRule[];\n}\n\n/** What a call that matched was given for each placeholder: a list for a repeated one. */\nexport type PlaceholderValues = Record<string, string | readonly string[]>;\n\n/**\n * Where a bare program name is looked for, in order: the system's directories, then Homebrew's on\n * Apple silicon and on Intel. A Finder-launched app inherits only launchd's `PATH`, so Homebrew's\n * tools would never resolve on the inherited one.\n */\nexport const SEARCH_PATH: readonly string[] = [\n '/usr/bin',\n '/bin',\n '/usr/sbin',\n '/sbin',\n '/opt/homebrew/bin',\n '/usr/local/bin',\n];\n\n/**\n * Programs refused whatever their path: shells, and programs whose job is to run their own\n * arguments as a command (`env`, `xargs`, `sudo`, `nice`, `nohup`), which would turn an argument\n * pattern into a command line.\n */\nconst REFUSED_PROGRAMS = new Set([\n 'sh',\n 'bash',\n 'zsh',\n 'dash',\n 'ksh',\n 'mksh',\n 'csh',\n 'tcsh',\n 'fish',\n 'nu',\n 'env',\n 'xargs',\n 'sudo',\n 'doas',\n 'su',\n 'osascript',\n 'cmd',\n 'powershell',\n 'pwsh',\n 'nice',\n 'nohup',\n]);\n\n/** Windows batch files, which run through `cmd.exe` and so re-parse their arguments. */\nconst REFUSED_EXTENSIONS = ['.bat', '.cmd'];\n\nconst PLACEHOLDER = /^\\{([A-Za-z_][A-Za-z0-9_]*):([\\s\\S]+)\\}(\\.\\.\\.)?$/;\n\n/** Why a declaration or a call was refused. */\nexport class SpawnRuleError extends Error {\n override readonly name = 'SpawnRuleError';\n}\n\n/** The last segment of a path, either separator, lower-cased and without `.exe`. */\nfunction baseName(program: string): string {\n const last = program.split(/[\\\\/]/).at(-1) ?? '';\n return last.toLowerCase().replace(/\\.exe$/, '');\n}\n\n/** Why `program` cannot be declared, or null when it can. */\nexport function programProblem(program: string): string | null {\n if (typeof program !== 'string' || program.length === 0) return 'a program is required';\n if (program.includes('\\0')) return 'a program cannot hold a NUL character';\n if (program !== program.trim()) return 'a program cannot start or end with white space';\n const lower = program.toLowerCase();\n if (REFUSED_EXTENSIONS.some((extension) => lower.endsWith(extension))) {\n return `${program} is a batch file, which runs through cmd.exe and re-parses its arguments`;\n }\n const name = baseName(program);\n if (REFUSED_PROGRAMS.has(name)) {\n return `${program} runs its arguments as a command, so it cannot be declared`;\n }\n if (program.startsWith('/')) {\n const segments = program.split('/').slice(1);\n if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {\n return `${program} is not a normalized absolute path`;\n }\n return null;\n }\n if (/[\\\\/]/.test(program)) {\n return `${program} is a relative path: give an absolute path or a bare name`;\n }\n if (program === '.' || program === '..') return `${program} is not a program`;\n return null;\n}\n\n/** Parse one declared argument. */\nexport function parseArgument(arg: string): ArgumentRule {\n if (typeof arg !== 'string') throw new SpawnRuleError('an argument must be a string');\n if (arg.includes('\\0')) throw new SpawnRuleError('an argument cannot hold a NUL character');\n const placeholder = PLACEHOLDER.exec(arg);\n if (!placeholder) return { kind: 'literal', value: arg };\n const [, name, source, dots] = placeholder as unknown as [string, string, string, string?];\n if (hasLookbehindOrNamedGroup(source)) {\n throw new SpawnRuleError(\n `{${name}} has a (?< named group or lookbehind, which the desktop's native rules cannot compile`,\n );\n }\n let pattern: RegExp;\n try {\n // On its own first: a pattern that compiles alone has balanced groups, so one such as\n // `a)|(.*` cannot close the anchoring group early and escape it.\n new RegExp(source);\n // Anchored as a whole, so an alternation cannot escape it: `{x:a|b}` is `^(?:a|b)$`.\n pattern = new RegExp(`^(?:${source})$`);\n } catch (error) {\n throw new SpawnRuleError(`{${name}} has a pattern that does not compile: ${String(error)}`);\n }\n const option = alternatives(source).every((one) => /^\\^?\\\\?-/.test(one));\n return { kind: 'placeholder', name, pattern, option, repeated: dots !== undefined };\n}\n\n/**\n * Whether a pattern opens a `(?<` group (a named group or a lookbehind) outside an escape or a\n * class. JavaScript compiles one, but the native rules' ECMAScript `std::regex` does not, and a\n * declaration it cannot compile would be dropped there with no error.\n */\nfunction hasLookbehindOrNamedGroup(source: string): boolean {\n let inClass = false;\n for (let at = 0; at < source.length; at++) {\n const char = source[at];\n if (char === '\\\\') at++;\n else if (inClass) inClass = char !== ']';\n else if (char === '[') inClass = true;\n else if (source.startsWith('(?<', at)) return true;\n }\n return false;\n}\n\n/**\n * A pattern's top-level alternatives: `-v|.*` is `-v` and `.*`. A `|` in a group, in a class or\n * escaped is not one. The pattern has compiled, so its groups and classes are balanced.\n */\nfunction alternatives(source: string): string[] {\n const found: string[] = [];\n let depth = 0;\n let inClass = false;\n let start = 0;\n for (let at = 0; at < source.length; at++) {\n const char = source[at];\n if (char === '\\\\') at++;\n else if (inClass) inClass = char !== ']';\n else if (char === '[') inClass = true;\n else if (char === '(') depth++;\n else if (char === ')') depth--;\n else if (char === '|' && depth === 0) {\n found.push(source.slice(start, at));\n start = at + 1;\n }\n }\n found.push(source.slice(start));\n return found;\n}\n\n/** Check and parse one declared capability. Throws `SpawnRuleError` on a bad declaration. */\nexport function compileCapability(capability: SpawnCapability): CompiledCapability {\n const problem = programProblem(capability?.program);\n if (problem) throw new SpawnRuleError(problem);\n if (capability.args !== undefined && !Array.isArray(capability.args)) {\n throw new SpawnRuleError(`${capability.program}: args must be a list`);\n }\n const args = (capability.args ?? []).map(parseArgument);\n const names = new Set<string>();\n let repeated = 0;\n for (const rule of args) {\n if (rule.kind !== 'placeholder') continue;\n if (names.has(rule.name)) {\n throw new SpawnRuleError(`${capability.program}: {${rule.name}} is declared twice`);\n }\n names.add(rule.name);\n if (rule.repeated) repeated++;\n }\n // Two repeated placeholders could share the arguments between them in more than one way.\n if (repeated > 1) {\n throw new SpawnRuleError(`${capability.program}: at most one placeholder may repeat`);\n }\n return { program: capability.program, args };\n}\n\n/** Whether one argument passes a placeholder. */\nfunction passes(rule: Extract<ArgumentRule, { kind: 'placeholder' }>, arg: string): boolean {\n if (arg.startsWith('-') && !rule.option) return false;\n return rule.pattern.test(arg);\n}\n\n/** Whether one argument passes a rule. */\nfunction fits(rule: ArgumentRule, arg: string): boolean {\n return rule.kind === 'literal' ? rule.value === arg : passes(rule, arg);\n}\n\n/**\n * Whether `args` fit a capability's argument rules, and the values its placeholders took; null\n * when they do not. The rules before a repeated placeholder take the first arguments, those after\n * it the last, and it takes what is left between, each by its own pattern.\n */\nexport function matchArguments(\n rules: readonly ArgumentRule[],\n args: readonly string[],\n): PlaceholderValues | null {\n if (args.some((arg) => typeof arg !== 'string' || arg.includes('\\0'))) return null;\n const at = rules.findIndex((rule) => rule.kind === 'placeholder' && rule.repeated);\n const head = at === -1 ? rules : rules.slice(0, at);\n const tail = at === -1 ? [] : rules.slice(at + 1);\n if (at === -1 ? args.length !== rules.length : args.length < head.length + tail.length) {\n return null;\n }\n const values: Record<string, string | readonly string[]> = {};\n const take = (rule: ArgumentRule, arg: string): boolean => {\n if (!fits(rule, arg)) return false;\n if (rule.kind === 'placeholder') values[rule.name] = arg;\n return true;\n };\n for (let index = 0; index < head.length; index++) {\n if (!take(head[index]!, args[index]!)) return null;\n }\n const tailStart = args.length - tail.length;\n for (let index = 0; index < tail.length; index++) {\n if (!take(tail[index]!, args[tailStart + index]!)) return null;\n }\n if (at !== -1) {\n const rule = rules[at] as Extract<ArgumentRule, { kind: 'placeholder' }>;\n const middle = args.slice(head.length, tailStart);\n if (!middle.every((arg) => passes(rule, arg))) return null;\n values[rule.name] = middle;\n }\n return values;\n}\n\n/** What `matchSpawn` answers for a call a capability allows. */\nexport interface SpawnMatch {\n readonly capability: CompiledCapability;\n /** The program to run: the declared absolute path, or the name as it was pinned. */\n readonly path: string;\n readonly values: PlaceholderValues;\n}\n\n/**\n * The capability that allows running `program` with `args`, or null when none does. `program` is\n * the declared path or name exactly: a bare name is never looked up on any `PATH` here, and only\n * runs where `resolved` pinned it.\n *\n * @param resolved where each declared bare name was pinned at startup, by `resolveProgram`\n */\nexport function matchSpawn(\n capabilities: readonly CompiledCapability[],\n program: string,\n args: readonly string[],\n resolved: Readonly<Record<string, string | null>> = {},\n): SpawnMatch | null {\n for (const capability of capabilities) {\n const pinned = capability.program.startsWith('/')\n ? capability.program\n : (resolved[capability.program] ?? null);\n if (pinned === null) continue;\n if (program !== capability.program && program !== pinned) continue;\n const values = matchArguments(capability.args, args);\n if (values) return { capability, path: pinned, values };\n }\n return null;\n}\n\n/** What `resolveProgram` asks of the file system. */\nexport interface ProgramLookup {\n /** Whether an executable file is at `path`. */\n isExecutable(path: string): boolean;\n /**\n * Whether `path` is a developer tool stub that only runs `xcrun`, with no Command Line Tools\n * installed to run. Such a tool reports absent.\n */\n isStub?(path: string): boolean;\n}\n\n/**\n * Where a declared program runs from, pinned once at startup, or null when it is absent: not\n * found, or an `xcrun` stub without the Command Line Tools. A bare name is looked for on\n * `SEARCH_PATH` alone.\n */\nexport function resolveProgram(program: string, lookup: ProgramLookup): string | null {\n if (programProblem(program)) return null;\n const candidates = program.startsWith('/')\n ? [program]\n : SEARCH_PATH.map((dir) => `${dir}/${program}`);\n for (const candidate of candidates) {\n if (!lookup.isExecutable(candidate)) continue;\n return lookup.isStub?.(candidate) ? null : candidate;\n }\n return null;\n}\n\n/** The environment a spawned program gets: only the variables declared, of those given. */\nexport function filterEnvironment(\n env: Readonly<Record<string, string | undefined>>,\n allowed: readonly string[],\n): Record<string, string> {\n const filtered: Record<string, string> = {};\n for (const name of allowed) {\n const value = Object.hasOwn(env, name) ? env[name] : undefined;\n if (typeof value === 'string' && !value.includes('\\0')) filtered[name] = value;\n }\n return filtered;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"spawn-rules.js","sourceRoot":"","sources":["../src/spawn-rules.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAgCH;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAsB;IAC5C,UAAU;IACV,MAAM;IACN,WAAW;IACX,OAAO;IACP,mBAAmB;IACnB,gBAAgB;CACjB,CAAC;AAEF;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAC/B,IAAI;IACJ,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,IAAI;IACJ,KAAK;IACL,OAAO;IACP,MAAM;IACN,MAAM;IACN,IAAI;IACJ,WAAW;IACX,KAAK;IACL,YAAY;IACZ,MAAM;IACN,MAAM;IACN,OAAO;IACP,iGAAiG;IACjG,mGAAmG;IACnG,QAAQ;IACR,SAAS;IACT,eAAe;IACf,aAAa;IACb,SAAS;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,OAAO,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC/D,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,QAAQ,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;IACjF,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["/**\n * The rules a desktop app's declared spawn capabilities follow: which programs it may run, with\n * which arguments. Plain TypeScript with no imports, so the config plugin can check the declaration\n * at build time and `Processes` can refuse an undeclared call with a clear error before the\n * desktop host checks it again natively.\n *\n * An entry names a program and the arguments it may take:\n *\n * { program: '/usr/bin/git', args: ['clone', '{url:https://\\\\S+}', '{dir:[\\\\w.-]+}'] }\n *\n * Each argument is a literal, matched exactly, or a `{name:regex}` placeholder. A placeholder\n * followed by `...` matches zero or more arguments, each by the same rules.\n *\n * - A placeholder's pattern is anchored: it matches the whole argument, so `{branch:[a-z]+}`\n * never accepts `--upload-pack=...`.\n * - A placeholder never accepts an argument starting with `-` unless each alternative of its\n * pattern starts with one, so an option cannot be injected where a value was declared.\n * - No argument may hold a NUL character, which a C string would cut short.\n * - Shells, `env` and other programs that run their arguments as a command are refused as\n * programs, and so are Windows `.bat` and `.cmd` files, which `cmd.exe` re-parses (the BatBadBut\n * class of bug). `spawn` never goes through a shell.\n * - A program is an absolute path, or a bare name resolved once at startup on a fixed search path\n * (`SEARCH_PATH`), never the inherited `PATH`, and pinned there.\n *\n * The boundary guards against bugs and injected content, not against a hostile app.\n */\n\n/** A spawn capability as `app.json` declares it. */\nexport interface SpawnCapability {\n /** An absolute path, or a bare name resolved on `SEARCH_PATH` at startup. */\n readonly program: string;\n /** Literal arguments and `{name:regex}` placeholders, in order. */\n readonly args?: readonly string[];\n}\n\n/** One declared argument, parsed. */\nexport type ArgumentRule =\n | { readonly kind: 'literal'; readonly value: string }\n | {\n readonly kind: 'placeholder';\n readonly name: string;\n readonly pattern: RegExp;\n /** Whether each alternative of the pattern starts with `-`, so the value may be an option. */\n readonly option: boolean;\n /** `{name:regex}...`: zero or more arguments. */\n readonly repeated: boolean;\n };\n\n/** A spawn capability, checked and parsed. */\nexport interface CompiledCapability {\n readonly program: string;\n readonly args: readonly ArgumentRule[];\n}\n\n/** What a call that matched was given for each placeholder: a list for a repeated one. */\nexport type PlaceholderValues = Record<string, string | readonly string[]>;\n\n/**\n * Where a bare program name is looked for, in order: the system's directories, then Homebrew's on\n * Apple silicon and on Intel. A Finder-launched app inherits only launchd's `PATH`, so Homebrew's\n * tools would never resolve on the inherited one.\n */\nexport const SEARCH_PATH: readonly string[] = [\n '/usr/bin',\n '/bin',\n '/usr/sbin',\n '/sbin',\n '/opt/homebrew/bin',\n '/usr/local/bin',\n];\n\n/**\n * Programs refused whatever their path: shells, and programs whose job is to run their own\n * arguments as a command (`env`, `xargs`, `sudo`, `nice`, `nohup`), which would turn an argument\n * pattern into a command line.\n */\nconst REFUSED_PROGRAMS = new Set([\n 'sh',\n 'bash',\n 'zsh',\n 'dash',\n 'ksh',\n 'mksh',\n 'csh',\n 'tcsh',\n 'fish',\n 'nu',\n 'env',\n 'xargs',\n 'sudo',\n 'doas',\n 'su',\n 'osascript',\n 'cmd',\n 'powershell',\n 'pwsh',\n 'nice',\n 'nohup',\n // Linux's: escalation (`pkexec`), a shell of its own (`busybox`), and leaving a Flatpak sandbox,\n // the session or the mount namespace (`flatpak-spawn --host`, `systemd-run`, `nsenter`, `chroot`).\n 'pkexec',\n 'busybox',\n 'flatpak-spawn',\n 'systemd-run',\n 'nsenter',\n 'chroot',\n]);\n\n/** Windows batch files, which run through `cmd.exe` and so re-parse their arguments. */\nconst REFUSED_EXTENSIONS = ['.bat', '.cmd'];\n\nconst PLACEHOLDER = /^\\{([A-Za-z_][A-Za-z0-9_]*):([\\s\\S]+)\\}(\\.\\.\\.)?$/;\n\n/** Why a declaration or a call was refused. */\nexport class SpawnRuleError extends Error {\n override readonly name = 'SpawnRuleError';\n}\n\n/** The last segment of a path, either separator, lower-cased and without `.exe`. */\nfunction baseName(program: string): string {\n const last = program.split(/[\\\\/]/).at(-1) ?? '';\n return last.toLowerCase().replace(/\\.exe$/, '');\n}\n\n/** Why `program` cannot be declared, or null when it can. */\nexport function programProblem(program: string): string | null {\n if (typeof program !== 'string' || program.length === 0) return 'a program is required';\n if (program.includes('\\0')) return 'a program cannot hold a NUL character';\n if (program !== program.trim()) return 'a program cannot start or end with white space';\n const lower = program.toLowerCase();\n if (REFUSED_EXTENSIONS.some((extension) => lower.endsWith(extension))) {\n return `${program} is a batch file, which runs through cmd.exe and re-parses its arguments`;\n }\n const name = baseName(program);\n if (REFUSED_PROGRAMS.has(name)) {\n return `${program} runs its arguments as a command, so it cannot be declared`;\n }\n if (program.startsWith('/')) {\n const segments = program.split('/').slice(1);\n if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {\n return `${program} is not a normalized absolute path`;\n }\n return null;\n }\n if (/[\\\\/]/.test(program)) {\n return `${program} is a relative path: give an absolute path or a bare name`;\n }\n if (program === '.' || program === '..') return `${program} is not a program`;\n return null;\n}\n\n/** Parse one declared argument. */\nexport function parseArgument(arg: string): ArgumentRule {\n if (typeof arg !== 'string') throw new SpawnRuleError('an argument must be a string');\n if (arg.includes('\\0')) throw new SpawnRuleError('an argument cannot hold a NUL character');\n const placeholder = PLACEHOLDER.exec(arg);\n if (!placeholder) return { kind: 'literal', value: arg };\n const [, name, source, dots] = placeholder as unknown as [string, string, string, string?];\n if (hasLookbehindOrNamedGroup(source)) {\n throw new SpawnRuleError(\n `{${name}} has a (?< named group or lookbehind, which the desktop's native rules cannot compile`,\n );\n }\n let pattern: RegExp;\n try {\n // On its own first: a pattern that compiles alone has balanced groups, so one such as\n // `a)|(.*` cannot close the anchoring group early and escape it.\n new RegExp(source);\n // Anchored as a whole, so an alternation cannot escape it: `{x:a|b}` is `^(?:a|b)$`.\n pattern = new RegExp(`^(?:${source})$`);\n } catch (error) {\n throw new SpawnRuleError(`{${name}} has a pattern that does not compile: ${String(error)}`);\n }\n const option = alternatives(source).every((one) => /^\\^?\\\\?-/.test(one));\n return { kind: 'placeholder', name, pattern, option, repeated: dots !== undefined };\n}\n\n/**\n * Whether a pattern opens a `(?<` group (a named group or a lookbehind) outside an escape or a\n * class. JavaScript compiles one, but the native rules' ECMAScript `std::regex` does not, and a\n * declaration it cannot compile would be dropped there with no error.\n */\nfunction hasLookbehindOrNamedGroup(source: string): boolean {\n let inClass = false;\n for (let at = 0; at < source.length; at++) {\n const char = source[at];\n if (char === '\\\\') at++;\n else if (inClass) inClass = char !== ']';\n else if (char === '[') inClass = true;\n else if (source.startsWith('(?<', at)) return true;\n }\n return false;\n}\n\n/**\n * A pattern's top-level alternatives: `-v|.*` is `-v` and `.*`. A `|` in a group, in a class or\n * escaped is not one. The pattern has compiled, so its groups and classes are balanced.\n */\nfunction alternatives(source: string): string[] {\n const found: string[] = [];\n let depth = 0;\n let inClass = false;\n let start = 0;\n for (let at = 0; at < source.length; at++) {\n const char = source[at];\n if (char === '\\\\') at++;\n else if (inClass) inClass = char !== ']';\n else if (char === '[') inClass = true;\n else if (char === '(') depth++;\n else if (char === ')') depth--;\n else if (char === '|' && depth === 0) {\n found.push(source.slice(start, at));\n start = at + 1;\n }\n }\n found.push(source.slice(start));\n return found;\n}\n\n/** Check and parse one declared capability. Throws `SpawnRuleError` on a bad declaration. */\nexport function compileCapability(capability: SpawnCapability): CompiledCapability {\n const problem = programProblem(capability?.program);\n if (problem) throw new SpawnRuleError(problem);\n if (capability.args !== undefined && !Array.isArray(capability.args)) {\n throw new SpawnRuleError(`${capability.program}: args must be a list`);\n }\n const args = (capability.args ?? []).map(parseArgument);\n const names = new Set<string>();\n let repeated = 0;\n for (const rule of args) {\n if (rule.kind !== 'placeholder') continue;\n if (names.has(rule.name)) {\n throw new SpawnRuleError(`${capability.program}: {${rule.name}} is declared twice`);\n }\n names.add(rule.name);\n if (rule.repeated) repeated++;\n }\n // Two repeated placeholders could share the arguments between them in more than one way.\n if (repeated > 1) {\n throw new SpawnRuleError(`${capability.program}: at most one placeholder may repeat`);\n }\n return { program: capability.program, args };\n}\n\n/** Whether one argument passes a placeholder. */\nfunction passes(rule: Extract<ArgumentRule, { kind: 'placeholder' }>, arg: string): boolean {\n if (arg.startsWith('-') && !rule.option) return false;\n return rule.pattern.test(arg);\n}\n\n/** Whether one argument passes a rule. */\nfunction fits(rule: ArgumentRule, arg: string): boolean {\n return rule.kind === 'literal' ? rule.value === arg : passes(rule, arg);\n}\n\n/**\n * Whether `args` fit a capability's argument rules, and the values its placeholders took; null\n * when they do not. The rules before a repeated placeholder take the first arguments, those after\n * it the last, and it takes what is left between, each by its own pattern.\n */\nexport function matchArguments(\n rules: readonly ArgumentRule[],\n args: readonly string[],\n): PlaceholderValues | null {\n if (args.some((arg) => typeof arg !== 'string' || arg.includes('\\0'))) return null;\n const at = rules.findIndex((rule) => rule.kind === 'placeholder' && rule.repeated);\n const head = at === -1 ? rules : rules.slice(0, at);\n const tail = at === -1 ? [] : rules.slice(at + 1);\n if (at === -1 ? args.length !== rules.length : args.length < head.length + tail.length) {\n return null;\n }\n const values: Record<string, string | readonly string[]> = {};\n const take = (rule: ArgumentRule, arg: string): boolean => {\n if (!fits(rule, arg)) return false;\n if (rule.kind === 'placeholder') values[rule.name] = arg;\n return true;\n };\n for (let index = 0; index < head.length; index++) {\n if (!take(head[index]!, args[index]!)) return null;\n }\n const tailStart = args.length - tail.length;\n for (let index = 0; index < tail.length; index++) {\n if (!take(tail[index]!, args[tailStart + index]!)) return null;\n }\n if (at !== -1) {\n const rule = rules[at] as Extract<ArgumentRule, { kind: 'placeholder' }>;\n const middle = args.slice(head.length, tailStart);\n if (!middle.every((arg) => passes(rule, arg))) return null;\n values[rule.name] = middle;\n }\n return values;\n}\n\n/** What `matchSpawn` answers for a call a capability allows. */\nexport interface SpawnMatch {\n readonly capability: CompiledCapability;\n /** The program to run: the declared absolute path, or the name as it was pinned. */\n readonly path: string;\n readonly values: PlaceholderValues;\n}\n\n/**\n * The capability that allows running `program` with `args`, or null when none does. `program` is\n * the declared path or name exactly: a bare name is never looked up on any `PATH` here, and only\n * runs where `resolved` pinned it.\n *\n * @param resolved where each declared bare name was pinned at startup, by `resolveProgram`\n */\nexport function matchSpawn(\n capabilities: readonly CompiledCapability[],\n program: string,\n args: readonly string[],\n resolved: Readonly<Record<string, string | null>> = {},\n): SpawnMatch | null {\n for (const capability of capabilities) {\n const pinned = capability.program.startsWith('/')\n ? capability.program\n : (resolved[capability.program] ?? null);\n if (pinned === null) continue;\n if (program !== capability.program && program !== pinned) continue;\n const values = matchArguments(capability.args, args);\n if (values) return { capability, path: pinned, values };\n }\n return null;\n}\n\n/** What `resolveProgram` asks of the file system. */\nexport interface ProgramLookup {\n /** Whether an executable file is at `path`. */\n isExecutable(path: string): boolean;\n /**\n * Whether `path` is a developer tool stub that only runs `xcrun`, with no Command Line Tools\n * installed to run. Such a tool reports absent.\n */\n isStub?(path: string): boolean;\n}\n\n/**\n * Where a declared program runs from, pinned once at startup, or null when it is absent: not\n * found, or an `xcrun` stub without the Command Line Tools. A bare name is looked for on\n * `SEARCH_PATH` alone.\n */\nexport function resolveProgram(program: string, lookup: ProgramLookup): string | null {\n if (programProblem(program)) return null;\n const candidates = program.startsWith('/')\n ? [program]\n : SEARCH_PATH.map((dir) => `${dir}/${program}`);\n for (const candidate of candidates) {\n if (!lookup.isExecutable(candidate)) continue;\n return lookup.isStub?.(candidate) ? null : candidate;\n }\n return null;\n}\n\n/** The environment a spawned program gets: only the variables declared, of those given. */\nexport function filterEnvironment(\n env: Readonly<Record<string, string | undefined>>,\n allowed: readonly string[],\n): Record<string, string> {\n const filtered: Record<string, string> = {};\n for (const name of allowed) {\n const value = Object.hasOwn(env, name) ? env[name] : undefined;\n if (typeof value === 'string' && !value.includes('\\0')) filtered[name] = value;\n }\n return filtered;\n}\n"]}
|
package/dist/tray.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Icons in the macOS menu bar's status area,
|
|
3
|
-
* in `@ng-native/components` registers here. Absent on
|
|
2
|
+
* Icons in the macOS menu bar's status area, or a Linux panel's as StatusNotifierItems, each with
|
|
3
|
+
* a menu or a press of its own. `<tray-icon>` in `@ng-native/components` registers here. Absent on
|
|
4
|
+
* iOS and Android, and on a Linux desktop with no StatusNotifierWatcher, where nothing is drawn.
|
|
4
5
|
*
|
|
5
6
|
* The host contract, on the `NgNativeTray` module: `setIcons(icons)` takes every icon each time one
|
|
6
7
|
* changes, as `{ id, title, sfSymbol, image, tooltip, menu }`, `menu` as `serializeMenu` makes it
|
|
@@ -47,9 +48,11 @@ export declare class Tray {
|
|
|
47
48
|
/** Overridden in a test with a fake host. */
|
|
48
49
|
static readonly SOURCE: InjectionToken<NativeTray | null>;
|
|
49
50
|
private readonly native;
|
|
51
|
+
/** The desktop OS whose shortcuts the menus show: Linux's own, else a Mac's. */
|
|
52
|
+
private readonly menuOs;
|
|
50
53
|
private readonly icons;
|
|
51
54
|
private next;
|
|
52
|
-
/** Whether the OS has a status area for the app: macOS. */
|
|
55
|
+
/** Whether the OS has a status area for the app: macOS, and Linux with a StatusNotifierWatcher. */
|
|
53
56
|
readonly available: Signal<boolean>;
|
|
54
57
|
private readonly sent;
|
|
55
58
|
private readonly unsubscribe;
|
package/dist/tray.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Icons in the macOS menu bar's status area,
|
|
3
|
-
* in `@ng-native/components` registers here. Absent on
|
|
2
|
+
* Icons in the macOS menu bar's status area, or a Linux panel's as StatusNotifierItems, each with
|
|
3
|
+
* a menu or a press of its own. `<tray-icon>` in `@ng-native/components` registers here. Absent on
|
|
4
|
+
* iOS and Android, and on a Linux desktop with no StatusNotifierWatcher, where nothing is drawn.
|
|
4
5
|
*
|
|
5
6
|
* The host contract, on the `NgNativeTray` module: `setIcons(icons)` takes every icon each time one
|
|
6
7
|
* changes, as `{ id, title, sfSymbol, image, tooltip, menu }`, `menu` as `serializeMenu` makes it
|
|
@@ -9,6 +10,7 @@
|
|
|
9
10
|
*/
|
|
10
11
|
import { InjectionToken, Service, computed, effect, inject, signal, } from '@angular/core';
|
|
11
12
|
import { serializeMenu } from "./menus.js";
|
|
13
|
+
import { injectOs } from "./os.js";
|
|
12
14
|
import { reactNative } from "./react-native.js";
|
|
13
15
|
import * as i0 from "@angular/core";
|
|
14
16
|
function traySource() {
|
|
@@ -30,14 +32,16 @@ export class Tray {
|
|
|
30
32
|
factory: traySource,
|
|
31
33
|
});
|
|
32
34
|
native = inject(Tray.SOURCE);
|
|
35
|
+
/** The desktop OS whose shortcuts the menus show: Linux's own, else a Mac's. */
|
|
36
|
+
menuOs = injectOs() === 'linux' ? 'linux' : 'macos';
|
|
33
37
|
icons = signal([], /* @ts-ignore */
|
|
34
38
|
...(ngDevMode ? [{ debugName: "icons" }] : /* istanbul ignore next */ []));
|
|
35
39
|
next = 0;
|
|
36
|
-
/** Whether the OS has a status area for the app: macOS. */
|
|
40
|
+
/** Whether the OS has a status area for the app: macOS, and Linux with a StatusNotifierWatcher. */
|
|
37
41
|
available = signal(this.native !== null).asReadonly();
|
|
38
42
|
sent = computed(() => this.icons().map(({ id, model }) => {
|
|
39
43
|
const { menu, press, ...icon } = model();
|
|
40
|
-
const serialized = serializeMenu(menu,
|
|
44
|
+
const serialized = serializeMenu(menu, this.menuOs);
|
|
41
45
|
return {
|
|
42
46
|
icon: { id, ...icon, menu: serialized.entries.length ? serialized.entries : null },
|
|
43
47
|
actions: serialized.actions,
|
package/dist/tray.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tray.js","sourceRoot":"","sources":["../src/tray.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"tray.js","source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,IAAI,CAAC,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;QACjD,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;QAC1C,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC;IAC9E,CAAC;IAEO,QAAQ,CAAC,KAAsB;QACrC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,KAAK,KAAK,CAAC,IAAI,CAAC,CAAC;QACnE,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;YAAE,IAAI,EAAE,KAAK,EAAE,CAAC;;YACrC,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;IACvC,CAAC;IAED,WAAW;QACT,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;IACvB,CAAC;uGAjDU,IAAI;wGAAJ,IAAI;;2FAAJ,IAAI;kBADhB,OAAO","sourcesContent":["/**\n * Icons in the macOS menu bar's status area, or a Linux panel's as StatusNotifierItems, each with\n * a menu or a press of its own. `<tray-icon>` in `@ng-native/components` registers here. Absent on\n * iOS and Android, and on a Linux desktop with no StatusNotifierWatcher, where nothing is drawn.\n *\n * The host contract, on the `NgNativeTray` module: `setIcons(icons)` takes every icon each time one\n * changes, as `{ id, title, sfSymbol, image, tooltip, menu }`, `menu` as `serializeMenu` makes it\n * (null for an icon with a press instead). It sends `{ type: 'press', icon }` and\n * `{ type: 'menuSelect', icon, id }` on `ngNativeTray`.\n */\nimport {\n InjectionToken,\n Service,\n computed,\n effect,\n inject,\n signal,\n type Signal,\n} from '@angular/core';\nimport type { MenuEntry } from './menu-model.ts';\nimport { serializeMenu, type NativeMenuEntry } from './menus.ts';\nimport { injectOs } from './os.ts';\nimport { reactNative } from './react-native.ts';\n\n/** One icon as an app describes it. */\nexport interface TrayIconModel {\n readonly title?: string;\n /** An SF Symbol, drawn as a template image that follows the menu bar's appearance. */\n readonly sfSymbol?: string;\n /** An image asset's name, for an icon of the app's own. */\n readonly image?: string;\n readonly tooltip?: string;\n /** The menu a click opens; with none, a click is a press. */\n readonly menu: readonly MenuEntry[];\n readonly press: () => void;\n}\n\nexport interface NativeTrayIcon {\n readonly id: string;\n readonly title?: string;\n readonly sfSymbol?: string;\n readonly image?: string;\n readonly tooltip?: string;\n readonly menu: readonly NativeMenuEntry[] | null;\n}\n\nexport type NativeTrayEvent =\n | { readonly type: 'press'; readonly icon: string }\n | { readonly type: 'menuSelect'; readonly icon: string; readonly id: string };\n\nexport interface NativeTray {\n setIcons(icons: readonly NativeTrayIcon[]): void;\n subscribe(listener: (event: NativeTrayEvent) => void): () => void;\n}\n\ninterface TrayTurboModule {\n setIcons?(icons: readonly NativeTrayIcon[]): void;\n}\n\nfunction traySource(): NativeTray | null {\n const native = reactNative();\n const module = native?.TurboModuleRegistry?.get?.('NgNativeTray') as\n TrayTurboModule | null | undefined;\n if (!module) return null;\n return {\n setIcons: (icons) => module.setIcons?.(icons),\n subscribe: (listener) => {\n const subscription = native?.DeviceEventEmitter?.addListener('ngNativeTray', (event) =>\n listener(event as NativeTrayEvent),\n );\n return () => subscription?.remove();\n },\n };\n}\n\n@Service()\nexport class Tray {\n /** Overridden in a test with a fake host. */\n static readonly SOURCE = new InjectionToken<NativeTray | null>('angular-native.traySource', {\n factory: traySource,\n });\n\n private readonly native = inject(Tray.SOURCE);\n /** The desktop OS whose shortcuts the menus show: Linux's own, else a Mac's. */\n private readonly menuOs = injectOs() === 'linux' ? 'linux' : 'macos';\n private readonly icons = signal<readonly { id: string; model: Signal<TrayIconModel> }[]>([]);\n private next = 0;\n\n /** Whether the OS has a status area for the app: macOS, and Linux with a StatusNotifierWatcher. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n private readonly sent = computed(() =>\n this.icons().map(({ id, model }) => {\n const { menu, press, ...icon } = model();\n const serialized = serializeMenu(menu, this.menuOs);\n return {\n icon: { id, ...icon, menu: serialized.entries.length ? serialized.entries : null },\n actions: serialized.actions,\n press,\n };\n }),\n );\n\n private readonly unsubscribe = this.native?.subscribe((event) => this.hostSaid(event)) ?? null;\n\n constructor() {\n const native = this.native;\n if (native) effect(() => native.setIcons(this.sent().map((one) => one.icon)));\n }\n\n /** Show an icon for as long as the function answered is not called. */\n add(model: Signal<TrayIconModel>): () => void {\n const one = { id: `tray-${this.next++}`, model };\n this.icons.update((all) => [...all, one]);\n return () => this.icons.update((all) => all.filter((each) => each !== one));\n }\n\n private hostSaid(event: NativeTrayEvent): void {\n const icon = this.sent().find((one) => one.icon.id === event.icon);\n if (event.type === 'press') icon?.press();\n else icon?.actions.get(event.id)?.();\n }\n\n ngOnDestroy(): void {\n this.unsubscribe?.();\n }\n}\n"]}
|
package/dist/vibration.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare class Vibration {
|
|
|
8
8
|
/** Overridden in a test to record a buzz without one happening. */
|
|
9
9
|
static readonly SOURCE: InjectionToken<NativeVibration | null>;
|
|
10
10
|
private readonly native;
|
|
11
|
-
/** Whether the device can vibrate: absent on a
|
|
11
|
+
/** Whether the device can vibrate: absent on a desktop OS, which has no motor to drive. */
|
|
12
12
|
readonly available: Signal<boolean>;
|
|
13
13
|
/** A single buzz. The duration is Android's; iOS vibrates for its own fixed length. */
|
|
14
14
|
buzz(durationMs?: number): void;
|
package/dist/vibration.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* over, because a pattern designed on Android does not feel the same on iOS and nothing here can
|
|
12
12
|
* make it.
|
|
13
13
|
*/
|
|
14
|
-
import { injectOs } from "./os.js";
|
|
14
|
+
import { injectOs, isDesktopOs } from "./os.js";
|
|
15
15
|
import { InjectionToken, Service, inject, signal } from '@angular/core';
|
|
16
16
|
import { reactNative } from "./react-native.js";
|
|
17
17
|
import * as i0 from "@angular/core";
|
|
@@ -19,8 +19,8 @@ export class Vibration {
|
|
|
19
19
|
/** Overridden in a test to record a buzz without one happening. */
|
|
20
20
|
static SOURCE = new InjectionToken('angular-native.vibrationSource', { factory: () => reactNative()?.Vibration ?? null });
|
|
21
21
|
native = inject(Vibration.SOURCE);
|
|
22
|
-
/** Whether the device can vibrate: absent on a
|
|
23
|
-
available = signal(this.native !== null && injectOs()
|
|
22
|
+
/** Whether the device can vibrate: absent on a desktop OS, which has no motor to drive. */
|
|
23
|
+
available = signal(this.native !== null && !isDesktopOs(injectOs())).asReadonly();
|
|
24
24
|
/** A single buzz. The duration is Android's; iOS vibrates for its own fixed length. */
|
|
25
25
|
buzz(durationMs = 400) {
|
|
26
26
|
this.native?.vibrate(durationMs);
|
package/dist/vibration.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vibration.js","sourceRoot":"","sources":["../src/vibration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"vibration.js","sourceRoot":"","sources":["../src/vibration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAe,MAAM,eAAe,CAAC;AACrF,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;;AAQhD,MAAM,OAAO,SAAS;IACpB,mEAAmE;IACnE,MAAM,CAAU,MAAM,GAAG,IAAI,cAAc,CACzC,gCAAgC,EAChC,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,WAAW,EAAE,EAAE,SAAS,IAAI,IAAI,EAAE,CACpD,CAAC;IAEe,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAEnD,2FAA2F;IAClF,SAAS,GAAoB,MAAM,CAC1C,IAAI,CAAC,MAAM,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CACjD,CAAC,UAAU,EAAE,CAAC;IAEf,uFAAuF;IACvF,IAAI,CAAC,UAAU,GAAG,GAAG;QACnB,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;IACnC,CAAC;IAED;;;;;OAKG;IACH,OAAO,CAAC,MAAyB,EAAE,UAAgC,EAAE;QACnE,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,MAAM,CAAC,EAAE,OAAO,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC;IAC7D,CAAC;IAED,IAAI;QACF,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC;IACxB,CAAC;uGA/BU,SAAS;wGAAT,SAAS;;2FAAT,SAAS;kBADrB,OAAO","sourcesContent":["/**\n * Vibration, which is not haptics.\n *\n * `Haptics` is the Taptic Engine: a tap, a nudge, a success chime you feel rather than hear, tied\n * to something the user just did. This is the motor - a buzz of a stated length, or a pattern -\n * and it is what an alarm, a timer or an incoming call uses. An app that wants feedback for a\n * button press wants the other one.\n *\n * iOS has one duration and ignores the number, so a pattern there is on and off at a fixed\n * strength; Android takes the milliseconds as written. Both are said plainly rather than papered\n * over, because a pattern designed on Android does not feel the same on iOS and nothing here can\n * make it.\n */\n\nimport { injectOs, isDesktopOs } from './os.ts';\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { reactNative } from './react-native.ts';\n\nexport interface NativeVibration {\n vibrate(pattern?: number | number[], repeat?: boolean): void;\n cancel(): void;\n}\n\n@Service()\nexport class Vibration {\n /** Overridden in a test to record a buzz without one happening. */\n static readonly SOURCE = new InjectionToken<NativeVibration | null>(\n 'angular-native.vibrationSource',\n { factory: () => reactNative()?.Vibration ?? null },\n );\n\n private readonly native = inject(Vibration.SOURCE);\n\n /** Whether the device can vibrate: absent on a desktop OS, which has no motor to drive. */\n readonly available: Signal<boolean> = signal(\n this.native !== null && !isDesktopOs(injectOs()),\n ).asReadonly();\n\n /** A single buzz. The duration is Android's; iOS vibrates for its own fixed length. */\n buzz(durationMs = 400): void {\n this.native?.vibrate(durationMs);\n }\n\n /**\n * A pattern of waits and buzzes, in milliseconds, starting with a wait.\n *\n * `repeat` runs it until `stop()`, which is for something that must be answered - an alarm, a\n * call - and is a promise to call `stop` rather than a decoration.\n */\n pattern(millis: readonly number[], options: { repeat?: boolean } = {}): void {\n this.native?.vibrate([...millis], options.repeat ?? false);\n }\n\n stop(): void {\n this.native?.cancel();\n }\n}\n"]}
|