Skip to content

About

No description, website, or topics provided.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

objcjs-types

TypeScript type declarations for macOS Objective-C frameworks. Auto-generated from Apple SDK headers via clang -ast-dump=json.

Designed for use with objc-js and Bun.

Coverage

~5,700 classes, ~1,100 protocols, ~2,900 enums, and ~100 structs across 156 frameworks including Foundation, AppKit, WebKit, Metal, AVFoundation, CoreData, and more.

Install

bun add objcjs-types objc-js

Requires objc-js 1.6 or later.

Usage

Import frameworks by name:

import { NSApplication, NSWindow, NSWindowStyleMask } from "objcjs-types/AppKit";
import { NSString } from "objcjs-types/Foundation";
import { CGRect } from "objcjs-types";
import { options } from "objcjs-types/helpers";

Create a window:

const rect = CGRect(100, 100, 800, 600);

const styleMask = options(
  NSWindowStyleMask.Titled,
  NSWindowStyleMask.Closable,
  NSWindowStyleMask.Miniaturizable,
  NSWindowStyleMask.Resizable
);

const window = NSWindow.alloc().initWithContentRect$styleMask$backing$defer$(
  rect,
  styleMask,
  2, // NSBackingStoreBuffered
  false
);

const title = NSString.stringWithUTF8String$("Hello from Bun");
if (!title) throw new Error("Failed to create title");
window.setTitle$(title);
window.makeKeyAndOrderFront$(null as any);

Type-safe delegates

createDelegate infers method names and parameter types from the protocol name:

import { createDelegate } from "objcjs-types";

const delegate = createDelegate("NSWindowDelegate", {
  windowDidResize$(notification) {
    console.log("Window resized!");
  },
  windowWillClose$(notification) {
    app.terminate$(null as any);
  }
});

window.setDelegate$(delegate);

instanceof narrowing

Class constants have Symbol.hasInstance patched so that instanceof works with ObjC objects, using the runtime's isKindOfClass: check:

import {
  ASAuthorizationAppleIDCredential,
  ASPasswordCredential,
  type _ASAuthorization
} from "objcjs-types/AuthenticationServices";

declare const auth: _ASAuthorization;
const cred = auth.credential();

if (cred instanceof ASAuthorizationAppleIDCredential) {
  cred.user(); // narrowed to _ASAuthorizationAppleIDCredential
  cred.email();
} else if (cred instanceof ASPasswordCredential) {
  cred.user();
  cred.password();
}

There's also an isKindOfClass type guard for explicit narrowing with a generic type parameter:

import { isKindOfClass } from "objcjs-types/helpers";
import {
  ASAuthorizationAppleIDCredential,
  type _ASAuthorizationAppleIDCredential
} from "objcjs-types/AuthenticationServices";

if (isKindOfClass<_ASAuthorizationAppleIDCredential>(cred, ASAuthorizationAppleIDCredential)) {
  cred.user(); // narrowed
}

Both instanceof and isKindOfClass cache results per (object, class) pair so repeated checks skip the native boundary.

Typed block wrappers

Methods that accept block (closure) parameters require Objective-C type encodings at runtime. The blocks submodule provides pre-generated wrapper functions that handle this automatically:

import { NSArray, NSString } from "objcjs-types/Foundation";
import { enumerateObjectsUsingBlock$Block_0, sortedArrayUsingComparator$Block } from "objcjs-types/Foundation/blocks";

const array = NSArray.arrayWithObjects$count$(
  [
    NSString.stringWithUTF8String$("banana"),
    NSString.stringWithUTF8String$("apple"),
    NSString.stringWithUTF8String$("cherry")
  ],
  3
);

// Enumerate with typed block wrapper
array.enumerateObjectsUsingBlock$(
  enumerateObjectsUsingBlock$Block_0((obj, idx, stop) => {
    console.log(`Item ${idx}:`, obj.description().UTF8String());
  })
);

// Sort with comparator block
const sorted = array.sortedArrayUsingComparator$(
  sortedArrayUsingComparator$Block((a, b) => {
    return a.compare$(b);
  })
);

Block wrappers are named <selector>Block with numeric suffixes (_0, _1) when different classes use the same selector with different signatures. Nullable block parameters are handled automatically.

Subclassing

defineSubclass wraps NobjcClass.define() with type safety — self is typed as the superclass, protocol method names get autocomplete, and the returned class supports alloc/init and instanceof:

import { NSObject } from "objcjs-types/Foundation";
import { defineSubclass, callSuper } from "objcjs-types/subclass";

const MyDelegate = defineSubclass(NSObject, {
  name: "MyDelegate",
  protocols: ["NSWindowDelegate"],
  methods: {
    windowDidResize$: {
      types: "v@:@",
      implementation(self, notification) {
        console.log("Resized!");
      }
    },
    init: {
      types: "@@:",
      implementation(self) {
        return callSuper(self, "init");
      }
    }
  }
});

const instance = MyDelegate.alloc().init();
window.setDelegate$(instance);

Use callSuper inside method implementations to invoke the superclass version of a method.

Releasing objects

A wrapper keeps its Objective-C object alive until the wrapper is garbage collected. dispose() drops that reference immediately. Use it for objects that hold JavaScript callbacks, such as event monitors, notification observers, and delegates.

import { dispose } from "objcjs-types";
import { NSEvent } from "objcjs-types/AppKit";

NSEvent.removeMonitor$(monitor);
dispose(monitor);

Calling a method on a disposed wrapper, or passing it to Objective-C, throws. Disposing the same wrapper again does nothing. retain, release, autorelease, and dealloc remain manual reference-counting methods and should not be called.

NS_OPTIONS

Use options() to combine bitmask flags with type safety:

import { options } from "objcjs-types/helpers";
import { NSWindowStyleMask } from "objcjs-types/AppKit";

const mask = options(NSWindowStyleMask.Titled, NSWindowStyleMask.Closable, NSWindowStyleMask.Resizable);

Plain numeric expressions like 1 | 2 | 8 also work -- NS_OPTIONS types accept any number.

Structs

Structs are plain objects with factory functions:

import { CGRect, CGPoint, CGSize } from "objcjs-types";

const rect = CGRect(0, 0, 800, 600);
const point: CGPoint = { x: 100, y: 200 };
const size: CGSize = { width: 800, height: 600 };

NSData conversion (objcjs-types/nsdata)

Utilities for converting between NSData and JavaScript Buffers:

import { NSDataFromBuffer, bufferFromNSData, NSDataFromBase64, base64FromNSData } from "objcjs-types/nsdata";

const nsData = NSDataFromBuffer(Buffer.from("hello"));
const buffer = bufferFromNSData(nsData);
const b64 = base64FromNSData(nsData);

OS version detection (objcjs-types/osversion)

Cached macOS version queries with named release constants:

import { getOSVersion, isAtLeast, macOS, formatVersion } from "objcjs-types/osversion";

console.log(formatVersion(getOSVersion())); // "15.3.1"

if (isAtLeast(macOS.Sequoia)) {
  // Sequoia+ only APIs
}

Helpers (objcjs-types/helpers)

import {
  NSStringFromString,
  NSArrayFromObjects,
  NSDictionaryFromKeysAndValues,
  options,
  isKindOfClass
} from "objcjs-types/helpers";

const nsStr = NSStringFromString("hello");

Subpath exports

Import path Contents
objcjs-types Structs, createDelegate, defineSubclass, callSuper, dispose
objcjs-types/helpers NSStringFromString, options, isKindOfClass, etc.
objcjs-types/subclass defineSubclass, callSuper
objcjs-types/nsdata NSData/Buffer conversion utilities
objcjs-types/osversion macOS version detection and comparison
objcjs-types/delegates createDelegate and ProtocolMap type
objcjs-types/<Framework> Framework exports (e.g. objcjs-types/AppKit)
objcjs-types/<Framework>/blocks Typed block wrappers (e.g. objcjs-types/Foundation/blocks)

ObjC selector naming

Objective-C selectors are mapped using $ as the separator:

ObjC TypeScript
init init()
initWithFrame: initWithFrame$(frame)
initWithContentRect:styleMask:backing:defer: initWithContentRect$styleMask$backing$defer$(...)

Properties emit getters and setters:

window.title(); // getter
window.setTitle$(value); // setter

Available frameworks

All 156 frameworks

Accessibility, AccessoryAccess, AccessorySetupKit, Accounts, AddressBook, AdServices, AdSupport, AppKit, AppleScriptKit, AppTrackingTransparency, AudioToolbox, AudioVideoBridging, AuthenticationServices, AutomaticAssessmentConfiguration, Automator, AVFAudio, AVFoundation, AVKit, AVRouting, BackgroundAssets, BackgroundTasks, BrowserEngineCore, BrowserEngineKit, BusinessChat, CalendarStore, CallKit, Cinematic, ClassKit, CloudKit, Collaboration, Contacts, ContactsUI, CoreAudio, CoreAudioKit, CoreBluetooth, CoreData, CoreHaptics, CoreImage, CoreLocation, CoreMediaIO, CoreMIDI, CoreML, CoreMotion, CoreSpotlight, CoreTelephony, CoreText, CoreWLAN, CryptoTokenKit, DataDetection, DeviceCheck, DeviceDiscoveryExtension, DiscRecording, DiscRecordingUI, EventKit, ExceptionHandling, ExecutionPolicy, ExtensionKit, ExternalAccessory, FileProvider, FileProviderUI, FinderSync, Foundation, FSKit, GameController, GameKit, GameplayKit, GameSave, GLKit, HealthKit, IdentityLookup, ImageCaptureCore, InputMethodKit, InstallerPlugins, InstantMessage, Intents, IntentsUI, IOSurface, IOUSBHost, iTunesLibrary, JavaRuntimeSupport, JavaScriptCore, Kernel, LinkPresentation, LinkSecurity, LocalAuthentication, LocalAuthenticationEmbeddedUI, MailKit, MapKit, Matter, MediaAccessibility, MediaExtension, MediaLibrary, MediaPlayer, Metal, MetalFX, MetalKit, MetalPerformanceShaders, MetalPerformanceShadersGraph, MetricKit, MLCompute, ModelIO, MultipeerConnectivity, NaturalLanguage, NearbyInteraction, NetworkExtension, NotificationCenter, OpenDirectory, OSAKit, OSLog, ParavirtualizedGraphics, PassKit, PDFKit, PencilKit, PHASE, Photos, PhotosUI, PreferencePanes, PushKit, QuartzCore, QuickLookThumbnailing, QuickLookUI, ReplayKit, SafariServices, SafetyKit, SceneKit, ScreenCaptureKit, ScreenSaver, ScreenTime, ScriptingBridge, SecurityFoundation, SecurityInterface, SecurityUI, SensitiveContentAnalysis, SensorKit, ServiceManagement, SharedWithYou, SharedWithYouCore, ShazamKit, Social, SoundAnalysis, Speech, SpriteKit, StateReporting, StoreKit, Symbols, SyncServices, SystemExtensions, ThreadNetwork, UniformTypeIdentifiers, UserNotifications, UserNotificationsUI, VideoSubscriberAccount, VideoToolbox, Virtualization, Vision, WebKit

Regenerating types

Requires macOS with Xcode installed.

bun run build    # generate from SDK headers + compile to dist/

License

MIT

About

No description, website, or topics provided.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages