Skip to content

Apple-js is the extension of osascript as javascript , run applescript from javascript

Notifications You must be signed in to change notification settings

Next-Dev-Saif/apple-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

11 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🍎 apple-js v1.0.6

The Ultimate macOS Automation Library for Node.js.

apple-js is a high-performance, production-ready framework that bridges JavaScript and AppleScript. It allows you to automate every aspect of macOS β€” from browser DOM manipulation and application control to system events and file operations β€” using modern, type-safe JavaScript.

This document serves as the Master Specification for the library, including every available namespace and production feature.


πŸš€ Key Features

  • ⚑ Persistent Worker Engine: Uses a single, low-latency background subprocess (via stdin) to execute commands instantly without the overhead of spawning new processes.
  • πŸ›‘οΈ Industrial-Strength Error Handling: Returns structured error objects (TimeoutError, PermissionError, AppNotFoundError) instead of raw strings.
  • 🧩 Extensible Plugin Architecture: Easily register custom AppleScript namespaces at runtime.
  • πŸ“ Workflow Templates: Pre-configured complex automations like "Focus Mode", "Pomodoro", and "Clean Desktop".
  • πŸ“ž Voice Fallback Safety: Automated try-catch voice selection. If a requested voice is missing, it falls back to the system default gracefully.
  • πŸ’» Cross-Runtime CLI: Full-featured CLI tool for controlling your Mac from shell scripts or CI/CD.
  • πŸ“˜ TypeScript First: 100% type definitions covering 150+ methods with rich JSDoc.

πŸ“ Architecture Overview

The Worker Pattern

Traditional AppleScript libraries in Node.js use exec("osascript -e '...' "). This is slow and prone to escaping issues. apple-js spawns a persistent worker thread that stays open. Commands are sent as a stream to stdin, and result data/errors are piped back. This allows for queued execution and state persistence (if implemented in script blocks).

Error Classification

The engine intelligently parses stderr from macOS to identify:

  • Permission Issues: When Accessibility or Automation permissions are missing.
  • App Missing: When an application "X" target is not installed.
  • Timeouts: Configurable per-command to prevent script hangs.

οΏ½ Installation & Setup

npm install apple-js-stable

Requirements

  • macOS: 10.15 (Catalina) or higher.
  • Node.js: v18.0.0+.
  • Permissions: Grant "Accessibility" and "Automation" to your Terminal or IDE in System Settings > Privacy & Security.

🧠 Core Engine (Osascript Class)

The engine orchestrates the background worker and exposes the command library.

const { Osascript } = require('apple-js-stable');

const script = new Osascript({
  logLevel: 'info',      // 'debug' | 'info' | 'warn' | 'error' | 'silent'
  timeout: 120000,       // Default 2-minute timeout
  maxRestartAttempts: 5  // Automatic worker recovery
});

Instance Methods

  • executeScript(commands[], timeout?): Run multiple commands in sequence. Set timeout to null for infinite duration.
  • healthCheck(): Verify worker responsiveness.
  • use(plugin): Inject new functionality.
  • close() / restart(): Manage worker lifecycle.
  • getQueueSize(): Monitor pending tasks.

οΏ½ Exhaustive API Reference (script.appleCommands)

The command library is organized into 22+ logical namespaces. Every method returns a valid AppleScript string.

1. πŸ—οΈ Core Logic

Basic building blocks for AppleScript.

  • set(var, val): Variable assignment.
  • if(condition, lines[]) / ifElse(...): Logic flow.
  • repeatWith(var, from, to, lines[]): Loops.
  • repeatWhile(condition, lines[]): Conditional loops.
  • delay(seconds): Pause execution.
  • shell(command): Execute standard shell scripts.
  • activateApp(name) / quit(name): App lifecycle.

2. πŸ–₯️ System Control

Manage hardware and global settings.

  • setVolume(0-100) / toggleMute(bool): Audio.
  • setBrightness(0.0-1.0): (Requires 'brightness' CLI tool).
  • screenshotToDesktop(): Take a full capture.
  • toggleDarkMode() / enableDarkMode() / disableDarkMode(): Appearance.
  • lockScreen() / sleepMac() / shutdown() / restart(): Power.
  • getBatteryLevel() / getPowerSource(): Energy info.
  • getScreenResolution() / getMacOSVersion(): Hardware info.
  • toggleNightShift(): Blue light filter.

3. 🌐 Browser Automation

Native Safari support and basic Chrome control.

  • openInSafari(url) / openInChrome(url) / openInDefaultBrowser(url)
  • getCurrentURLFromSafari(): URL extraction.
  • newSafariTab(url?): Tab management.
  • activateSafari(): Focus browser.

4. πŸ”— DOM Injection (Web Control)

Inject and run JavaScript inside active tabs.

  • dom.run(jsCode, app): Execute raw JS in Safari/Chrome.
  • dom.click(selector): UI interaction.
  • dom.type(selector, text): Form filling.
  • dom.setContent(selector, val, isHtml): Update text/HTML.
  • dom.scrollBy(x, y) / dom.scrollTo(pos): Navigation.
  • dom.injectCSS(css) / dom.injectScript(url): Real-time modifications.

5. οΏ½ Finder & File Operations

File system interaction via the macOS Desktop.

  • finder.openFolder(path) / finder.revealInFinder(path)
  • finder.createFolder(path, name) / finder.moveToTrash(path)
  • finder.setDesktopWallpaper(path): Visual customization.
  • fileOps.read(path) / fileOps.write(path, data): Low-level file I/O.
  • fileOps.exists(path) / fileOps.getSize(path): Attributes.
  • fileOps.ls(dir) / fileOps.mkdir(dir): Directory management.

6. 🧠 AI & Fun Assistants

Speech and integrated workflow utilities.

  • speak(text, voice): Smart speech with auto-fallback.
  • ai.introduceYourself() / ai.tellJoke(): Social logic.
  • ai.motivateUser() / ai.dailyAffirmation(): Productivity.
  • ai.startMeditation(): Guided mindfulness workflow.
  • ai.askSiri(question): Automation-to-Siri bridge.
  • ai.askChatGPT(prompt): Browser-based GPT automation.
  • fun.screenFlash(): Visual camera-flash effect.
  • fun.playSosumi(): Classic alert sound.

7. �️ UI Automation

Simulate keyboard and mouse events.

  • ui.typeText(text, delay): Simulate keystrokes.
  • ui.clickAt(x, y) / ui.doubleClickAt(x, y): Coordinates.
  • ui.pressHotkey(key, modifiers[]): Global shortcuts (e.g., ["command", "shift"]).
  • ui.copy() / ui.paste() / ui.selectAll(): Generic edits.
  • ui.resizeFrontWindow(w, h) / ui.moveWindow(x, y): Window positioning.

8. πŸ“‹ Clipboard Management

  • clipboard.copy(text) / clipboard.get()
  • clipboard.clear(): Security.
  • clipboard.copyFile(path): Binary copy.

9. πŸ”” Notifications & Dialogs

  • notifications.banner(msg): Native system banners.
  • notifications.alertWithSound(title, msg, sound): High-priority.
  • advancedNotifications.withButtons(title, msg, buttons[]): Get user input.
  • advancedNotifications.progress(msg, total): Show progress bars in Script Editor.

10. πŸ“… Calendar & Reminders

  • calendar.createEvent(title, start, end, location, notes)
  • calendar.getTodayEvents(): Schedule parsing.
  • reminders.create(title, notes, dueDate)
  • reminders.complete(name) / reminders.getAll(list)

11. πŸ›°οΈ Network & Monitoring

  • network.getWiFiName() / network.getIPAddress() / network.getPublicIP()
  • network.testConnection(host): Internet verification.
  • process.list() / process.kill(name): Task management.
  • process.cpuUsage(name) / process.memoryUsage(name): Performance tracking.

12. πŸ› οΈ Siri Shortcuts

  • shortcuts.run(name) / shortcuts.runWithInput(name, input)
  • shortcuts.list(): Retrieve local shortcuts.

13. ⏱️ Time & Date

  • time.now() / time.getDate(format) / time.getTimeInZone(tz)
  • time.sleep(seconds): Alias for delay.

14. πŸ”¨ Workspace (Bonus)

  • workspace.openInVSCode(path)
  • workspace.openInTerminal(path)
  • workspace.searchMDN(query) / workspace.searchStackOverflow(query)

🧩 Templates & Plugins

Using Templates

Built-in composite workflows.

await script.templates.pomodoro({ duration: 25, breakDuration: 5 });
await script.templates.websiteScreenshot(url, path);
await script.templates.cleanDesktop();

Using Plugins

Example Spotify integration:

const spotifyPlugin = require('apple-js/plugins/spotify');
script.use(spotifyPlugin);
await script.spotify.play("Jazz");

⌨️ CLI Tool (apple-js)

Control your machine without using Node.js directly.

Command Usage
apple-js speak "Hello" Smart speech output.
apple-js open Safari Launch any application.
apple-js notify "Title" "Msg" Quick custom alerts.
apple-js screenshot [path] Instant screen capture.
apple-js volume 50 Volume control.
apple-js mute / apple-js dark-mode / apple-js lock Toggle system states.

🀝 Contributing

For bug reports or feature requests, visit the GitHub repository.

πŸ“„ License

MIT Β© 2026 – Next-Dev-Saif πŸš€ Transform your macOS into a programmable powerhouse.

About

Apple-js is the extension of osascript as javascript , run applescript from javascript

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages