@moku-labs/native 0.1.0 → 0.2.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/README.md CHANGED
@@ -14,7 +14,7 @@
14
14
 
15
15
  <br/>
16
16
 
17
- [Quick start](#quick-start) · [Two apps, one contract](#two-apps-one-contract) · [Plugins](#plugins) · [Configuration](#configuration) · [Events](#events) · [Docs](#docs)
17
+ [Quick start](#quick-start) · [Two apps, one contract](#two-apps-one-contract) · [Plugins](#plugins) · [Configuration](#configuration) · [Signing and store builds](#signing-and-store-builds) · [iOS simulator](#ios-simulator) · [Events](#events) · [Docs](#docs)
18
18
 
19
19
  ---
20
20
 
@@ -49,18 +49,21 @@ import { systemPlugins } from "./system";
49
49
 
50
50
  export const native = createApp({
51
51
  config: {
52
- app: { name: "MyApp", identifier: "com.example.myapp" },
52
+ app: { name: "MyApp", identifier: "com.example.myapp", icon: "assets/icon.png" },
53
53
  web: {
54
54
  build: "bun run build",
55
- dev: { command: "bun run dev", url: "http://localhost:5173" },
55
+ devCommand: "bun run dev", devUrl: "http://localhost:5173",
56
56
  dist: "dist"
57
57
  },
58
58
  system: systemPlugins,
59
- capabilities: { "deep-link": { mode: "scheme", scheme: "myapp" } }
59
+ capabilities: { "deep-link": { mode: "scheme", scheme: "myapp" } },
60
+ targets: ["macos", "ios"] // default: the host's own desktop target — mobile is opt-in
60
61
  }
61
62
  });
62
63
  ```
63
64
 
65
+ `app.icon` is a 1024×1024 PNG. Leave it out and a placeholder is generated, so a brand-new app packages before anyone has drawn an icon.
66
+
64
67
  ```ts
65
68
  // scripts/native-build.ts — one thin script per verb
66
69
  import { native } from "../src/native";
@@ -131,13 +134,13 @@ Your project runs **two `createApp`s side by side**: the web/node app you alread
131
134
 
132
135
  | Plugin | Tier | Key API | Responsibility |
133
136
  |---|---|---|---|
134
- | [`project`](./src/plugins/project/README.md) | Complex | `generate` · `completeness` · `patchMobile` · `clean` · `resolve` | Capability registry + `.moku/tauri` generators + write-if-changed writer + mobile init-once-then-patch. Owns the generated tree as *files*; never spawns. |
135
- | [`tauri`](./src/plugins/tauri/README.md) | Standard | `icon` · `build` · `mobileInit` · `dev` · `version` | The framework's **only** subprocess seam: `@tauri-apps/cli` argv builders, injectable spawn, process-group dev lifecycle, error taxonomy, secret scrubbing. |
136
- | [`build`](./src/plugins/build/README.md) | Standard | `run` · `runAll` | Sequential per-target phase pipeline; emits `native:phase`/`native:complete`; owns the `collect` phase (bundle-location table → `dist-native/<target>/`). |
137
+ | [`project`](./src/plugins/project/README.md) | Complex | `generate` · `completeness` · `patchMobile` · `ensureIconSource` · `clean` · `resolve` | Capability registry + `.moku/tauri` generators + write-if-changed writer + mobile init-once-then-patch. Owns the generated tree as *files*; never spawns. |
138
+ | [`tauri`](./src/plugins/tauri/README.md) | Standard | `icon` · `build` · `mobileInit` · `dev` · `version` · `runner` | The framework's **only** subprocess seam: `@tauri-apps/cli` argv builders, injectable spawn, process-group dev lifecycle, error taxonomy, secret scrubbing. |
139
+ | [`build`](./src/plugins/build/README.md) | Standard | `prepare` · `run` · `runAll` | Sequential per-target phase pipeline; emits `native:phase`/`native:complete`; owns the `collect` phase (bundle-location table → `dist-native/<target>/`). |
137
140
  | [`doctor`](./src/plugins/doctor/README.md) | Complex | `run` | Per-target toolchain/completeness/version-skew diagnosis via a `checks/` registry, run in parallel — one broken check never sinks the report. |
138
141
  | [`cli`](./src/plugins/cli/README.md) | Standard | `build` · `dev` · `doctor` · `clean` | Typed verb surface — no argv parsing. Branded rendering (`@moku-labs/common/cli`), live progress via event hooks. |
139
142
 
140
- Every lower-level surface stays reachable on the composed app: `native.project.generate(…)`, `native.tauri.version()`, `native.build.runAll()`, `native.doctor.run()` — `cli` is convenience, not a gate.
143
+ Every lower-level surface stays reachable on the composed app: `native.project.generate(…)`, `native.tauri.getVersion()`, `native.build.runAll()`, `native.doctor.run()` — `cli` is convenience, not a gate.
141
144
 
142
145
  ## Configuration
143
146
 
@@ -145,24 +148,132 @@ The substantive surface is **global** `Config` — every plugin reads it via `ct
145
148
 
146
149
  | Field | Type | Default | Notes |
147
150
  |---|---|---|---|
148
- | `app` | `{ name: string; identifier: string; version?: string }` | `{ name: "", identifier: "" }` | Required — validated at composition time: non-empty `name`, reverse-DNS `identifier`. |
149
- | `web` | `{ build: string; dev: { command: string; url: string }; dist: string; cwd?: string }` | `build: "bun run build"`, `dev.command: "bun run dev"`, `dev.url: "http://localhost:5173"`, `dist: "dist"` | Web build/dev wiring codegenned into `tauri.conf.json`; `cwd` for monorepo layouts. |
151
+ | `app.name` | `string` | `""` | Display name (`productName`). Required — validated at composition time. |
152
+ | `app.identifier` | `string` | `""` | Reverse-DNS bundle id. Required — validated at composition time. |
153
+ | `app.version` | `string?` | unset → `"0.1.0"` | Marketing version. |
154
+ | `app.icon` | `string?` | unset | 1024×1024 PNG, relative to cwd. Unset → a placeholder PNG is generated. |
155
+ | `app.category` | `string?` | unset | Store category → `bundle.category`. |
156
+ | `app.buildNumber` | `string?` | unset | Store build number → `bundle.{iOS,macOS}.bundleVersion`. |
157
+ | `web.build` | `string` | `"bun run build"` | Runs before a build, in `web.cwd`. |
158
+ | `web.devCommand` | `string` | `"bun run dev"` | Runs before `dev`, in `web.cwd`. |
159
+ | `web.devUrl` | `string` | `"http://localhost:5173"` | Dev server URL — also the `DevHandle.url` and the readiness-poll target. |
160
+ | `web.dist` | `string` | `"dist"` | Web build output, resolved from `web.cwd` and rebased onto `src-tauri`. |
161
+ | `web.cwd` | `string?` | unset → the process cwd | Root of the web package — monorepo layouts. Everything web-shaped resolves from here. |
150
162
  | `system` | `ReadonlyArray<{ name: string }>` | `[]` | The composed system plugins — the shared cross-team contract. Unknown names throw at init. |
151
163
  | `capabilities` | `Partial<CapabilityConfigMap>` | `{}` | Per-capability packaging parameters. `deep-link` requires `{ mode: "scheme", scheme: string }`. |
152
- | `targets` | `readonly Target[]` | all five (`macos`, `windows`, `linux`, `ios`, `android`) | Which targets this app ships; the `runAll`/`doctor` default scope. |
164
+ | `targets` | `readonly Target[]` | `hostTargets(process.platform)` | The host's own desktop target (`darwin`→`macos`, `win32`→`windows`, `linux`→`linux`). **Mobile is opt-in**: name `ios`/`android` explicitly. |
153
165
  | `projectDir` | `string` | `".moku/tauri"` | Generated Tauri project root (contains `src-tauri/`). Gitignored build output. |
154
166
  | `outDir` | `string` | `"dist-native"` | Installer delivery root — `collect` copies finished artifacts to `outDir/<target>/`. |
155
- | `signing` | `SigningConfig` | `{}` | Env-var **references** and config-safe identifiers only — never raw secrets. `android: { keystorePath?, keystorePasswordEnv?, keyAlias? }`, `windows: { certificateThumbprint? }`. |
167
+ | `signing.apple` | `AppleSigning?` | unset | `teamId`, `signingIdentity`, `providerShortName`, `entitlements`, `appStore`, `exportMethod`, `macosMinimumSystemVersion`, `iosMinimumSystemVersion` — see [Signing and store builds](#signing-and-store-builds). |
168
+ | `signing.android` | `{ keystorePath?, keystorePasswordEnv?, keyPasswordEnv?, keyAlias? }` | unset | Env-var **names**, never secrets. `keyPasswordEnv` falls back to `keystorePasswordEnv`. |
169
+ | `signing.windows` | `{ certificateThumbprint? }` | unset | Windows signing certificate thumbprint. |
156
170
 
157
171
  Per-plugin knobs, overridable via `createApp({ pluginConfigs })`:
158
172
 
159
173
  | Plugin | Knob | Default | Purpose |
160
174
  |---|---|---|---|
161
175
  | `tauri` | `spawnImpl` / `nodePath` | `undefined` / `undefined` | Test seam / explicit `node` path (default: real process-group spawn, PATH-walked node). |
176
+ | `tauri` | `arch` | `undefined` | Host arch the iOS simulator slice is derived from (default: `process.arch`). `x64` → `--target x86_64`, anything else → `--target <arch>-sim`. Pin it in tests so an argv assertion does not depend on the machine running it. |
162
177
  | `tauri` | `readiness` | `{ intervalMs: 250, timeoutMs: 60_000 }` | `dev()`'s devUrl readiness poll — there is no stdout "ready" marker. |
163
178
  | `doctor` | `probeImpl` | `undefined` | Test seam for binary probes (default: real `which`/`--version` subprocesses). |
179
+ | `doctor` | `probeTimeoutMs` | `10_000` | Per-check budget. A check that outruns it becomes a `warn`, never a `fail`. |
164
180
  | `cli` | `renderImpl` / `confirmImpl` | `undefined` / `undefined` | Test seams (default: branded console + styled confirm from `@moku-labs/common/cli`). |
165
181
 
182
+ Three behaviours worth knowing before the first build:
183
+
184
+ - **Placeholder icon.** `project.ensureIconSource()` returns `path.resolve(app.icon)` and throws a `[native]` fix-it when that file is missing. With `app.icon` unset it writes an embedded 1024×1024 PNG to `<projectDir>/placeholder-icon.png` and returns that. The icons phase reports `generated`, `placeholder`, or `up to date`.
185
+ - **`tray` is a cargo feature, not a plugin.** Composing `{ name: "tray" }` adds `tray-icon` to the `tauri` dependency's features in the generated `Cargo.toml` — no crate, no npm package, no Rust init line. Every other registry row is a real plugin, so `RegistryRow.npmPackage`/`crate` are optional and consumers of `getRegistryRows()` null-check them. Its permission list is `core:tray:default`, `core:menu:default`, `core:image:default`, `core:resources:default`, `core:app:allow-default-window-icon` — the last one matters, because `@moku-labs/system` defaults the tray icon to `defaultWindowIcon()` and `core:default` does not grant that command, so without it a real macOS shell fails with `Command plugin:app|default_window_icon not allowed by ACL`.
186
+ - **`clean()` refuses anything that is not derived state.** The rule is positive containment, not a blacklist: `projectDir` must resolve strictly *inside* the **project anchor** (or a usable OS temp root, where test workspaces live) and must not be — or contain — the anchor, the cwd or the home directory, nor be a filesystem root. The anchor is the nearest ancestor of the cwd carrying a `.git` entry or a `workspaces` `package.json`, stopping before `$HOME` and the filesystem root — so an absolute `projectDir` at a monorepo root still validates when the script runs from `packages/app`. A temp root that is a filesystem root, or that is/contains `$HOME`, grants nothing (`os.tmpdir()` follows `TMPDIR`). Symlinks are resolved with `realpath`, and comparison is case-insensitive on macOS/Windows. `assertCleanableRoot` throws before any path is computed, and `createApp` rejects the same `projectDir` up front:
187
+
188
+ ```
189
+ [native] Refusing to clean projectDir "<root>".
190
+ Set config.projectDir to a dedicated subdirectory such as ".moku/tauri".
191
+ ```
192
+
193
+ - **`outDir` gets the looser rule.** It is written into and replaced file by file, never recursively cleaned, so a CI cache mount or a shared artifacts volume outside the checkout is legitimate. `createApp` refuses only a filesystem root, `$HOME` itself, and any ancestor of the cwd or of `$HOME`. The `collect` phase then resolves both `outDir` and each destination to their **real** paths before removing anything, so a symlinked `<outDir>/<target>` pointing into another tree is refused rather than wiped.
194
+
195
+ > [!IMPORTANT]
196
+ > **Do not replace `pluginConfigs.env.providers`.** The framework seeds `[workerSafeProcessEnv()]` in `src/config.ts` so `ctx.env.get("PATH")` resolves. Core-plugin config is a **shallow merge**, so passing your own `providers` array replaces that list instead of extending it — `PATH` goes `undefined` and every build dies with `[native] Could not locate a \`node\` binary on PATH.` If you override it, re-add the provider: `providers: [workerSafeProcessEnv(), yourProvider]`. (The typed `createApp({ pluginConfigs })` map covers the framework's own plugins only, so reaching `env` at Layer 3 takes a cast — the kernel still merges it at runtime.)
197
+
198
+ ## Signing and store builds
199
+
200
+ The split is absolute: **config holds identifiers and env-var names, the environment holds secrets.** Tauri reads the credentials itself, so nothing secret is ever written to `tauri.conf.json`, to Gradle, or to a log line (every subprocess line is scrubbed first).
201
+
202
+ ```ts
203
+ signing: {
204
+ apple: {
205
+ teamId: "ABCDE12345", // bundle.iOS.developmentTeam
206
+ signingIdentity: "Developer ID Application: ACME (ABCDE12345)", // "-" = ad-hoc
207
+ providerShortName: "ACME", // multi-team notarization
208
+ entitlements: "build/App.entitlements", // your plist, relative to cwd
209
+ appStore: true, // no entitlements? generate a sandbox plist for macOS
210
+ exportMethod: "app-store-connect", // tauri ios build --export-method
211
+ macosMinimumSystemVersion: "12.0",
212
+ iosMinimumSystemVersion: "15.0"
213
+ },
214
+ android: {
215
+ keystorePath: "release.jks",
216
+ keystorePasswordEnv: "ANDROID_KEYSTORE_PASSWORD",
217
+ keyPasswordEnv: "ANDROID_KEY_PASSWORD", // falls back to keystorePasswordEnv
218
+ keyAlias: "release"
219
+ }
220
+ }
221
+ ```
222
+
223
+ In the environment (never in config) — Tauri reads these directly:
224
+
225
+ | Variable(s) | Used for |
226
+ |---|---|
227
+ | `APPLE_ID` + `APPLE_PASSWORD` + `APPLE_TEAM_ID` | Notarization with an app-specific password. |
228
+ | `APPLE_API_KEY` + `APPLE_API_ISSUER` + `APPLE_API_KEY_PATH` | Notarization with an App Store Connect API key. Either set is enough. |
229
+ | `APPLE_CERTIFICATE` + `APPLE_CERTIFICATE_PASSWORD` | Base64 signing certificate imported into a CI keychain. |
230
+ | `<keystorePasswordEnv>` / `<keyPasswordEnv>` | Android release signing — Gradle reads them via `System.getenv` at build time. |
231
+
232
+ What each piece does:
233
+
234
+ - **`teamId`** goes into `bundle.iOS.developmentTeam`; `doctor` warns on an iOS target without it.
235
+ - **`signingIdentity`** goes into `bundle.macOS.signingIdentity`; `"-"` means ad-hoc. When it is a real identity, `doctor` probes the keychain for a **count** of codesigning identities (never the names), and skips that probe when `APPLE_CERTIFICATE` is set.
236
+ - **`appStore: true`** with no `entitlements` generates `src-tauri/Entitlements.plist` (app sandbox + network client) for macOS and points `bundle.macOS.entitlements` at it.
237
+ - **`exportMethod`** is forwarded to `tauri ios build --export-method` on device archives. A simulator build ignores it.
238
+ - **Android**: `patchMobile` maintains a `// MOKU-SIGNING-START … END` block in `gen/android/app/build.gradle.kts`. Dropping `keystorePath` removes it again. No `keystore.properties` is written.
239
+
240
+ > [!NOTE]
241
+ > **Unsigned dev builds and iOS simulator builds need none of this.** `doctor`'s signing check is warn-only for exactly that reason — a missing credential never fails a build, and never flips `report.ok`.
242
+
243
+ ## iOS simulator
244
+
245
+ ```ts
246
+ await native.cli.build({ target: "ios", simulator: true });
247
+ // unsigned <Product Name>.app -> dist-native/ios/
248
+ ```
249
+
250
+ `simulator: true` builds `--target aarch64-sim` (`x86_64` on an Intel host — Tauri's Intel simulator slice carries no `-sim` suffix), never exports an archive, and collects the `.app` **directory** instead of an `.ipa`, from `gen/apple/build/*-sim/` or `gen/apple/build/x86_64/`. Prerequisites, all checked by `native doctor`:
251
+
252
+ | Need | Install | Doctor check |
253
+ |---|---|---|
254
+ | Rust targets `aarch64-apple-ios`, `aarch64-apple-ios-sim` | `rustup target add aarch64-apple-ios aarch64-apple-ios-sim` | `ios-tools` (fail) |
255
+ | `xcodegen` | `brew install xcodegen` | `ios-tools` (fail) |
256
+ | `pod` (CocoaPods) | `brew install cocoapods` | `ios-tools` (fail) |
257
+ | An installed iOS platform + simulator runtime | `xcodebuild -downloadPlatform iOS` | `ios-platform` (warn) |
258
+
259
+ The first iOS build also runs `tauri ios init` once, then rewrites the build phase Tauri baked into the generated Xcode project: it calls whichever runner Tauri *detected* (`node tauri`, `bun tauri`, …), and none of those resolve inside Xcode. `project.patchMobile({ target, runner: tauri.getRunner() })` replaces it with the absolute `<node> <tauri.js>` pair this framework spawns with. The pass is idempotent.
260
+
261
+ ## When a build fails
262
+
263
+ A non-zero `@tauri-apps/cli` exit throws a `TauriError` carrying `kind`, `exitCode` and a scrubbed `stderrTail` (the last cause lines first, then the raw tail — `cli` prints it in a branded box above the error line, each line truncated to the branded console's width minus the box chrome). Classification runs over the *cause* lines of both streams only, most specific first, so one incidental `CodeSign` line in a 50k-line xcodebuild log cannot decide the taxonomy:
264
+
265
+ | `kind` | Means |
266
+ |---|---|
267
+ | `xcode-script-failed` | The Xcode "Build Rust Code" phase failed — check the runner line in `gen/apple/project.yml`. |
268
+ | `signing-failed` | codesign / provisioning profile / notarization / keychain / signtool / jarsigner / keystore. |
269
+ | `toolchain-missing` | `command not found`, `xcode-select`, `ANDROID_HOME`, missing NDK, `rustup`. |
270
+ | `platform-missing` | The iOS platform is not installed — `xcodebuild -downloadPlatform iOS`. |
271
+ | `device-unavailable` | No device or booted simulator. |
272
+ | `config-invalid` | Tauri could not parse/read the generated `tauri.conf.json`. |
273
+ | `compile-failed` | Rust compile errors. |
274
+ | `cancelled` | Signal-terminated (exit code `null`) with no pattern match — Ctrl-C. |
275
+ | `unknown` | Nothing matched; read the tail. |
276
+
166
277
  ## Events
167
278
 
168
279
  Two **global framework events** are declared in `src/config.ts` — emitted by `build`, hooked by `cli`, hookable by any plugin without a depends edge:
@@ -192,6 +303,16 @@ One **per-plugin event** is declared by `doctor` (hookable via a `depends: [doct
192
303
  > [!TIP]
193
304
  > Compile progress details carry real crate counts parsed from cargo output — never a synthesized percentage.
194
305
 
306
+ ## Breaking changes in this release
307
+
308
+ | What breaks | Migration |
309
+ |---|---|
310
+ | `web.dev.command`, `web.dev.url` | Use the flat `web.devCommand`, `web.devUrl` (config is shallow-merged, so a nested `dev` object could never merge cleanly). |
311
+ | `tauri.mobileInit({ platform })` | `tauri.mobileInit({ target })`. |
312
+ | `Build`, `Cli`, `Doctor`, `Project`, `Tauri` are type-only namespaces | Import the one runtime value by name: `import { TauriError } from "@moku-labs/native"`. |
313
+ | Default `targets` is no longer all five | It is now the host's own desktop target. Set `targets` explicitly to build `ios`/`android`. |
314
+ | `Project.RegistryRow` plugin fields are optional | Null-check `npmPackage`/`crate`/`rustInit` — the `tray` row is a cargo feature and carries none of them. |
315
+
195
316
  ## Scripts
196
317
 
197
318
  ```sh
@@ -199,24 +320,25 @@ bun run build # Build with tsdown
199
320
  bun run lint # Biome check + ESLint
200
321
  bun run lint:fix # Auto-fix lint issues
201
322
  bun run format # Format with Biome
202
- bun run test # Run all tests (vitest)
323
+ bun run test # Unit + integration (vitest) — never the smoke project
203
324
  bun run test:unit # Unit tests only
204
325
  bun run test:integration # Integration tests only
205
- bun run test:coverage # Tests with coverage (90% threshold)
326
+ bun run test:coverage # Unit + integration with coverage (90% threshold)
327
+ bun run test:smoke # Real toolchain: a genuine tauri build in a temp dir (opt-in, slow)
206
328
  bun run validate # publint + are-the-types-wrong (publish readiness)
207
329
  ```
208
330
 
209
331
  ## Development
210
332
 
211
333
  - **Adding a plugin** — create `src/plugins/<name>/` with `index.ts` (the `createPlugin` call), `types.ts`, and an API factory; register the instance in `src/index.ts`'s plugin array and re-export it from `src/plugins/index.ts`. Consumer apps can also author their own plugins with the exported `createPlugin` and pass them to `createApp({ plugins: [...] })`.
212
- - **Tests** — plugin-specific tests are colocated (`src/plugins/<name>/__tests__/unit/` and `__tests__/integration/`); root `tests/` holds framework-level integration only. All subprocess/render/probe seams are injectable, so the suite runs without any native toolchain.
334
+ - **Tests** — plugin-specific tests are colocated (`src/plugins/<name>/__tests__/unit/` and `__tests__/integration/`); root `tests/` holds framework-level integration only. All subprocess/render/probe seams are injectable, so `bun run test` runs without any native toolchain. `tests/smoke/` is the one exception — `bun run test:smoke` packages a real macOS `.app` and a real iOS simulator `.app` inside a fresh `mkdtemp` workspace, and is never part of `bun run test`. It composes all five capabilities and launches the built macOS binary for a few seconds (a window flashes on screen), because a generated config Tauri cannot deserialize builds fine and only aborts on the first frame.
213
335
 
214
336
  ## Requirements
215
337
 
216
338
  - **Node `>= 24`** and **Bun `>= 1.3.14`** — use `bun` exclusively (never npm/yarn/pnpm). A real `node` binary must also be on PATH for `@tauri-apps/cli`.
217
339
  - **TypeScript** in strict mode, with `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess`.
218
340
  - **[`@moku-labs/core`](https://github.com/moku-labs/core)** — the micro-kernel this framework is built on (direct dependency).
219
- - Native toolchains (Rust, Xcode, Android SDK/NDK) only for the targets you actually build — `native doctor` tells you what's missing per target.
341
+ - Native toolchains only for the targets you actually build — `native doctor` tells you what's missing per target. iOS additionally needs `xcodegen`, `cocoapods`, both iOS rust triples, and an installed iOS platform (see [iOS simulator](#ios-simulator)).
220
342
 
221
343
  ## Docs
222
344