capacitor-apple-intelligence 1.0.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.
@@ -0,0 +1,13 @@
1
+ Pod::Spec.new do |s|
2
+ s.name = 'CapacitorAppleIntelligence'
3
+ s.version = '1.0.0'
4
+ s.summary = 'Capacitor plugin for Apple Intelligence with schema-constrained JSON generation'
5
+ s.license = 'MIT'
6
+ s.homepage = 'https://github.com/farabiabdelwahe/capacitor-apple-intelligence'
7
+ s.author = 'Farabi Abdelwahed'
8
+ s.source = { :git => 'https://github.com/farabiabdelwahe/capacitor-apple-intelligence.git', :tag => s.version.to_s }
9
+ s.source_files = 'ios/Sources/AppleIntelligencePlugin/**/*.{swift,h,m,c,cc,mm,cpp}'
10
+ s.ios.deployment_target = '14.0'
11
+ s.dependency 'Capacitor'
12
+ s.swift_version = '5.9'
13
+ end
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Farabi Abdelwahed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/Package.swift ADDED
@@ -0,0 +1,28 @@
1
+ // swift-tools-version: 5.9
2
+ import PackageDescription
3
+
4
+ let package = Package(
5
+ name: "CapacitorAppleIntelligence",
6
+ platforms: [.iOS(.v14)],
7
+ products: [
8
+ .library(
9
+ name: "CapacitorAppleIntelligence",
10
+ targets: ["AppleIntelligencePlugin"])
11
+ ],
12
+ dependencies: [
13
+ .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", branch: "8.0.0")
14
+ ],
15
+ targets: [
16
+ .target(
17
+ name: "AppleIntelligencePlugin",
18
+ dependencies: [
19
+ .product(name: "Capacitor", package: "capacitor-swift-pm"),
20
+ .product(name: "Cordova", package: "capacitor-swift-pm")
21
+ ],
22
+ path: "ios/Sources/AppleIntelligencePlugin"),
23
+ .testTarget(
24
+ name: "AppleIntelligencePluginTests",
25
+ dependencies: ["AppleIntelligencePlugin"],
26
+ path: "ios/Tests/AppleIntelligencePluginTests")
27
+ ]
28
+ )
package/README.md ADDED
@@ -0,0 +1,346 @@
1
+ # capacitor-apple-intelligence
2
+
3
+ A production-ready Capacitor v8 plugin that exposes **Apple Intelligence** with **schema-constrained JSON generation** for structured AI responses.
4
+
5
+ ## Features
6
+
7
+ - 🧠 **On-device AI** - Uses Apple's Foundation Models framework for local, private inference
8
+ - 📋 **Schema-constrained output** - Guarantees JSON output matching your provided schema
9
+ - 🔄 **Automatic retry** - Retries generation once if validation fails
10
+ - ✅ **Runtime validation** - Validates output against JSON schema before returning
11
+ - 🔒 **Privacy-first** - No network calls, all processing happens on-device
12
+ - 📱 **iOS only** - Designed specifically for Apple Intelligence on iOS 26+
13
+
14
+ ## Requirements
15
+
16
+ - **iOS 26+** (Apple Intelligence requires iOS 26 or later)
17
+ - **Capacitor 8.0+**
18
+ - **Xcode 26+**
19
+ - **Apple Silicon device** (iPhone 15 Pro or later, or M-series iPads)
20
+
21
+ > ⚠️ **Note**: Apple Intelligence must be enabled on the device for this plugin to work.
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install capacitor-apple-intelligence
27
+ npx cap sync
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ### Basic Example
33
+
34
+ ```typescript
35
+ import { AppleIntelligence } from 'capacitor-apple-intelligence';
36
+
37
+ const result = await AppleIntelligence.generate({
38
+ messages: [
39
+ { role: "user", content: "List 3 popular programming languages" }
40
+ ],
41
+ response_format: {
42
+ type: "json_schema",
43
+ schema: {
44
+ type: "array",
45
+ items: {
46
+ type: "object",
47
+ properties: {
48
+ name: { type: "string" },
49
+ paradigm: { type: "string" },
50
+ yearCreated: { type: "number" }
51
+ },
52
+ required: ["name", "paradigm", "yearCreated"]
53
+ }
54
+ }
55
+ }
56
+ });
57
+
58
+ if (result.success) {
59
+ console.log(result.data);
60
+ // [
61
+ // { name: "Python", paradigm: "Multi-paradigm", yearCreated: 1991 },
62
+ // { name: "JavaScript", paradigm: "Event-driven", yearCreated: 1995 },
63
+ // { name: "Rust", paradigm: "Systems", yearCreated: 2010 }
64
+ // ]
65
+ } else {
66
+ console.error(result.error?.code, result.error?.message);
67
+ }
68
+ ```
69
+
70
+ ### With System Prompt
71
+
72
+ ```typescript
73
+ const result = await AppleIntelligence.generate({
74
+ messages: [
75
+ {
76
+ role: "system",
77
+ content: "You are a helpful assistant that organizes tasks."
78
+ },
79
+ {
80
+ role: "user",
81
+ content: "Create a list of tasks for planning a project"
82
+ }
83
+ ],
84
+ response_format: {
85
+ type: "json_schema",
86
+ schema: {
87
+ type: "array",
88
+ items: {
89
+ type: "object",
90
+ properties: {
91
+ title: { type: "string" },
92
+ description: { type: "string" },
93
+ priority: { type: "string" },
94
+ estimatedHours: { type: "number" }
95
+ },
96
+ required: ["title", "priority"]
97
+ }
98
+ }
99
+ }
100
+ });
101
+ ```
102
+
103
+ ### Nested Object Schema
104
+
105
+ ```typescript
106
+ const result = await AppleIntelligence.generate({
107
+ messages: [
108
+ { role: "user", content: "Create a sample user profile" }
109
+ ],
110
+ response_format: {
111
+ type: "json_schema",
112
+ schema: {
113
+ type: "object",
114
+ properties: {
115
+ user: {
116
+ type: "object",
117
+ properties: {
118
+ name: { type: "string" },
119
+ email: { type: "string" },
120
+ age: { type: "number" }
121
+ },
122
+ required: ["name", "email"]
123
+ },
124
+ preferences: {
125
+ type: "object",
126
+ properties: {
127
+ theme: { type: "string" },
128
+ notifications: { type: "boolean" }
129
+ }
130
+ }
131
+ },
132
+ required: ["user"]
133
+ }
134
+ }
135
+ });
136
+ ```
137
+
138
+ ### Plain Text Generation
139
+
140
+ Generate plain text responses without JSON schema constraints:
141
+
142
+ ```typescript
143
+ const result = await AppleIntelligence.generateText({
144
+ messages: [
145
+ { role: "system", content: "You are a creative writing assistant." },
146
+ { role: "user", content: "Write a short poem about the ocean" }
147
+ ]
148
+ });
149
+
150
+ if (result.success) {
151
+ console.log(result.content);
152
+ // "Waves crash upon the shore,
153
+ // Endless depths forevermore..."
154
+ }
155
+ ```
156
+
157
+ ### Text Generation with Language
158
+
159
+ Generate text in a specific language using either language codes or full names:
160
+
161
+ ```typescript
162
+ const result = await AppleIntelligence.generateTextWithLanguage({
163
+ messages: [
164
+ { role: "user", content: "Describe a beautiful sunset" }
165
+ ],
166
+ language: "es" // or "Spanish"
167
+ });
168
+
169
+ if (result.success) {
170
+ console.log(result.content);
171
+ // "El atardecer pinta el cielo con tonos dorados y rosados..."
172
+ }
173
+ ```
174
+
175
+ Supported language codes: `en`, `es`, `fr`, `de`, `ja`, `zh`, `it`, `pt`, `ru`, `ar`, `ko`
176
+
177
+ ## API
178
+
179
+ ### `checkAvailability()`
180
+
181
+ Check if Apple Intelligence is available on the current device. **Call this first** before using other methods.
182
+
183
+ #### Response
184
+
185
+ | Property | Type | Description |
186
+ |----------|------|-------------|
187
+ | `available` | `boolean` | Whether Apple Intelligence is available |
188
+ | `error` | `GenerateError` | Error details (if unavailable) |
189
+
190
+ #### Example
191
+
192
+ ```typescript
193
+ const result = await AppleIntelligence.checkAvailability();
194
+
195
+ if (result.available) {
196
+ console.log('Apple Intelligence is ready!');
197
+ } else {
198
+ console.log('Not available:', result.error?.message);
199
+ // "Apple Intelligence requires iOS 26 or later..."
200
+ }
201
+ ```
202
+
203
+ ---
204
+
205
+ ### `generate(request)`
206
+
207
+ Generate structured JSON output using Apple Intelligence.
208
+
209
+ #### Request
210
+
211
+ | Property | Type | Description |
212
+ |----------|------|-------------|
213
+ | `messages` | `Message[]` | Array of conversation messages |
214
+ | `response_format` | `ResponseFormat` | Schema specification for the output |
215
+
216
+ #### Message
217
+
218
+ | Property | Type | Description |
219
+ |----------|------|-------------|
220
+ | `role` | `"system" \| "user"` | The role of the message sender |
221
+ | `content` | `string` | The text content of the message |
222
+
223
+ #### ResponseFormat
224
+
225
+ | Property | Type | Description |
226
+ |----------|------|-------------|
227
+ | `type` | `"json_schema"` | Must be `"json_schema"` |
228
+ | `schema` | `object` | JSON Schema specification |
229
+
230
+ #### Response
231
+
232
+ | Property | Type | Description |
233
+ |----------|------|-------------|
234
+ | `success` | `boolean` | Whether generation succeeded |
235
+ | `data` | `any` | The parsed JSON data (on success) |
236
+ | `error` | `GenerateError` | Error details (on failure) |
237
+
238
+ #### Error Codes
239
+
240
+ | Code | Description |
241
+ |------|-------------|
242
+ | `UNAVAILABLE` | iOS < 26 or Apple Intelligence not available |
243
+ | `INVALID_JSON` | Model output was not valid JSON |
244
+ | `SCHEMA_MISMATCH` | JSON valid but doesn't match schema |
245
+ | `NATIVE_ERROR` | Other Swift/Foundation Models errors |
246
+
247
+ ### `generateText(request)`
248
+
249
+ Generate plain text output using Apple Intelligence.
250
+
251
+ #### Request
252
+
253
+ | Property | Type | Description |
254
+ |----------|------|-------------|
255
+ | `messages` | `Message[]` | Array of conversation messages |
256
+
257
+ #### Response
258
+
259
+ | Property | Type | Description |
260
+ |----------|------|-------------|
261
+ | `success` | `boolean` | Whether generation succeeded |
262
+ | `content` | `string` | The generated text (on success) |
263
+ | `error` | `GenerateError` | Error details (on failure) |
264
+
265
+ ### `generateTextWithLanguage(request)`
266
+
267
+ Generate plain text output in a specific language using Apple Intelligence.
268
+
269
+ #### Request
270
+
271
+ | Property | Type | Description |
272
+ |----------|------|-------------|
273
+ | `messages` | `Message[]` | Array of conversation messages |
274
+ | `language` | `string` | Target language - supports codes ("en", "es", "de") or full names ("English", "Spanish", "German") |
275
+
276
+ #### Response
277
+
278
+ | Property | Type | Description |
279
+ |----------|------|-------------|
280
+ | `success` | `boolean` | Whether generation succeeded |
281
+ | `content` | `string` | The generated text (on success) |
282
+ | `error` | `GenerateError` | Error details (on failure) |
283
+
284
+ ## How It Works
285
+
286
+ 1. **Schema Injection**: The plugin injects your JSON schema into the system prompt with strict instructions
287
+ 2. **Generation**: Uses Apple's Foundation Models framework to generate a response
288
+ 3. **Parsing**: Parses the raw text output as JSON
289
+ 4. **Validation**: Validates the JSON against your provided schema
290
+ 5. **Retry**: If validation fails, retries once with a corrective prompt
291
+ 6. **Return**: Returns structured success/error response
292
+
293
+ ## Supported Schema Types
294
+
295
+ - `object` - With `properties` and `required` fields
296
+ - `array` - With `items` schema and optional `minItems`/`maxItems`
297
+ - `string`
298
+ - `number` / `integer`
299
+ - `boolean`
300
+ - `null`
301
+
302
+ ## Error Handling
303
+
304
+ The plugin always returns a structured response, never throws:
305
+
306
+ ```typescript
307
+ const result = await AppleIntelligence.generate({...});
308
+
309
+ if (!result.success) {
310
+ switch (result.error?.code) {
311
+ case 'UNAVAILABLE':
312
+ // Show fallback UI or use alternative
313
+ break;
314
+ case 'INVALID_JSON':
315
+ case 'SCHEMA_MISMATCH':
316
+ // Retry with different prompt or handle gracefully
317
+ break;
318
+ case 'NATIVE_ERROR':
319
+ // Log error for debugging
320
+ console.error(result.error.message);
321
+ break;
322
+ }
323
+ }
324
+ ```
325
+
326
+ ## Web Support
327
+
328
+ This plugin is iOS-only. On web platforms, it returns:
329
+
330
+ ```typescript
331
+ {
332
+ success: false,
333
+ error: {
334
+ code: 'UNAVAILABLE',
335
+ message: 'Apple Intelligence is only available on iOS 26+ devices...'
336
+ }
337
+ }
338
+ ```
339
+
340
+ ## License
341
+
342
+ MIT
343
+
344
+ ## Contributing
345
+
346
+ Contributions are welcome! Please read our contributing guidelines before submitting PRs.
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Apple Intelligence Plugin for Capacitor v8
3
+ *
4
+ * Provides schema-constrained JSON generation using Apple's on-device
5
+ * Foundation Models framework, behaving like Groq/Gemini response_format: json_object.
6
+ *
7
+ * @module capacitor-apple-intelligence
8
+ */
9
+ /**
10
+ * Message role for conversation history.
11
+ */
12
+ export type MessageRole = 'system' | 'user';
13
+ /**
14
+ * A message in the conversation.
15
+ */
16
+ export interface Message {
17
+ /**
18
+ * The role of the message sender.
19
+ * - 'system': Instructions for the AI model
20
+ * - 'user': User input/queries
21
+ */
22
+ role: MessageRole;
23
+ /**
24
+ * The text content of the message.
25
+ */
26
+ content: string;
27
+ }
28
+ /**
29
+ * JSON Schema response format specification.
30
+ */
31
+ export interface ResponseFormat {
32
+ /**
33
+ * The type of response format. Must be 'json_schema'.
34
+ */
35
+ type: 'json_schema';
36
+ /**
37
+ * The JSON schema that the model output must conform to.
38
+ * Supports standard JSON Schema properties including:
39
+ * - type: 'object' | 'array' | 'string' | 'number' | 'boolean' | 'null'
40
+ * - properties: Object defining property schemas
41
+ * - required: Array of required property names
42
+ * - items: Schema for array items
43
+ */
44
+ schema: Record<string, unknown>;
45
+ }
46
+ /**
47
+ * Request payload for the generate method.
48
+ */
49
+ export interface GenerateRequest {
50
+ /**
51
+ * Array of messages forming the conversation context.
52
+ * Should include system messages for instructions and
53
+ * user messages for the actual query.
54
+ */
55
+ messages: Message[];
56
+ /**
57
+ * Response format specification requiring JSON schema compliance.
58
+ */
59
+ response_format: ResponseFormat;
60
+ }
61
+ /**
62
+ * Error codes returned by the plugin.
63
+ */
64
+ export type ErrorCode = 'INVALID_JSON' | 'SCHEMA_MISMATCH' | 'UNAVAILABLE' | 'NATIVE_ERROR';
65
+ /**
66
+ * Structured error object returned on failure.
67
+ */
68
+ export interface GenerateError {
69
+ /**
70
+ * Error code for programmatic handling.
71
+ * - INVALID_JSON: Model output was not valid JSON
72
+ * - SCHEMA_MISMATCH: JSON valid but doesn't match provided schema
73
+ * - UNAVAILABLE: iOS version < 26 or Apple Intelligence not available
74
+ * - NATIVE_ERROR: Other Swift/Foundation Models errors
75
+ */
76
+ code: ErrorCode;
77
+ /**
78
+ * Human-readable error message.
79
+ */
80
+ message: string;
81
+ }
82
+ /**
83
+ * Response from the generate method.
84
+ */
85
+ export interface GenerateResponse {
86
+ /**
87
+ * Whether the generation was successful.
88
+ */
89
+ success: boolean;
90
+ /**
91
+ * The parsed JSON data on success.
92
+ * The structure will match the provided schema.
93
+ */
94
+ data?: unknown;
95
+ /**
96
+ * Error details on failure.
97
+ * Only present when success is false.
98
+ */
99
+ error?: GenerateError;
100
+ }
101
+ /**
102
+ * Apple Intelligence Plugin interface.
103
+ *
104
+ * Provides access to Apple's on-device Foundation Models for
105
+ * schema-constrained JSON generation.
106
+ */
107
+ export interface AppleIntelligencePlugin {
108
+ /**
109
+ * Generate structured JSON output using Apple Intelligence.
110
+ *
111
+ * This method:
112
+ * 1. Injects the JSON schema into the system prompt
113
+ * 2. Instructs the model to return ONLY valid JSON
114
+ * 3. Validates the output against the provided schema
115
+ * 4. Retries once on validation failure
116
+ *
117
+ * @param request - The generation request containing messages and schema
118
+ * @returns Promise resolving to a structured response with success/error
119
+ *
120
+ * @example
121
+ * ```typescript
122
+ * const result = await AppleIntelligence.generate({
123
+ * messages: [
124
+ * { role: "system", content: "You are a helpful assistant." },
125
+ * { role: "user", content: "List 3 fruits" }
126
+ * ],
127
+ * response_format: {
128
+ * type: "json_schema",
129
+ * schema: {
130
+ * type: "array",
131
+ * items: {
132
+ * type: "object",
133
+ * properties: {
134
+ * name: { type: "string" },
135
+ * color: { type: "string" }
136
+ * },
137
+ * required: ["name", "color"]
138
+ * }
139
+ * }
140
+ * }
141
+ * });
142
+ *
143
+ * if (result.success) {
144
+ * console.log(result.data);
145
+ * // [{ name: "Apple", color: "red" }, ...]
146
+ * }
147
+ * ```
148
+ */
149
+ generate(request: GenerateRequest): Promise<GenerateResponse>;
150
+ /**
151
+ * Generate plain text output using Apple Intelligence.
152
+ *
153
+ * @param request - The generation request containing messages
154
+ * @returns Promise resolving to a text response with success/error
155
+ */
156
+ generateText(request: GenerateTextRequest): Promise<GenerateTextResponse>;
157
+ /**
158
+ * Generate plain text output using Apple Intelligence with a specific target language.
159
+ *
160
+ * @param request - The generation request containing messages and target language
161
+ * @returns Promise resolving to a text response with success/error
162
+ */
163
+ generateTextWithLanguage(request: GenerateTextWithLanguageRequest): Promise<GenerateTextResponse>;
164
+ /**
165
+ * Check if Apple Intelligence is available on this device.
166
+ *
167
+ * @returns Promise resolving to availability status
168
+ */
169
+ checkAvailability(): Promise<AvailabilityResponse>;
170
+ }
171
+ /**
172
+ * Request payload for text generation.
173
+ */
174
+ export interface GenerateTextRequest {
175
+ /**
176
+ * Array of messages forming the conversation context.
177
+ */
178
+ messages: Message[];
179
+ }
180
+ /**
181
+ * Request payload for text generation with language.
182
+ */
183
+ export interface GenerateTextWithLanguageRequest {
184
+ /**
185
+ * Array of messages forming the conversation context.
186
+ */
187
+ messages: Message[];
188
+ /**
189
+ * Target language for the response (e.g., "English", "Spanish", "French").
190
+ */
191
+ language: string;
192
+ }
193
+ /**
194
+ * Response for text generation.
195
+ */
196
+ export interface GenerateTextResponse {
197
+ /**
198
+ * Whether the generation was successful.
199
+ */
200
+ success: boolean;
201
+ /**
202
+ * The generated text content on success.
203
+ */
204
+ content?: string;
205
+ /**
206
+ * Error details on failure.
207
+ * Only present when success is false.
208
+ */
209
+ error?: GenerateError;
210
+ }
211
+ /**
212
+ * Response for availability check.
213
+ */
214
+ export interface AvailabilityResponse {
215
+ /**
216
+ * Whether Apple Intelligence is available on this device.
217
+ */
218
+ available: boolean;
219
+ /**
220
+ * Error details if unavailable.
221
+ */
222
+ error?: GenerateError;
223
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Apple Intelligence Plugin for Capacitor v8
3
+ *
4
+ * Provides schema-constrained JSON generation using Apple's on-device
5
+ * Foundation Models framework, behaving like Groq/Gemini response_format: json_object.
6
+ *
7
+ * @module capacitor-apple-intelligence
8
+ */
9
+ export {};
10
+ //# sourceMappingURL=definitions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"}
@@ -0,0 +1,33 @@
1
+ import type { AppleIntelligencePlugin } from './definitions';
2
+ /**
3
+ * Apple Intelligence Plugin instance.
4
+ *
5
+ * Provides schema-constrained JSON generation using Apple's on-device
6
+ * Foundation Models framework.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { AppleIntelligence } from 'capacitor-apple-intelligence';
11
+ *
12
+ * const result = await AppleIntelligence.generate({
13
+ * messages: [{ role: "user", content: "Suggest 3 books" }],
14
+ * response_format: {
15
+ * type: "json_schema",
16
+ * schema: {
17
+ * type: "array",
18
+ * items: {
19
+ * type: "object",
20
+ * properties: {
21
+ * title: { type: "string" },
22
+ * author: { type: "string" }
23
+ * },
24
+ * required: ["title", "author"]
25
+ * }
26
+ * }
27
+ * }
28
+ * });
29
+ * ```
30
+ */
31
+ declare const AppleIntelligence: AppleIntelligencePlugin;
32
+ export * from './definitions';
33
+ export { AppleIntelligence };