ReviewOS

also looking at this

craft-native/craft

iOS Phase 3: Tier-0 actions in Zig — 19 migrated, ratchet 105 → 86

#85
Merged glennmichael123 wants to merge feat/ios-phase3-tier0 into main
16 files +5086 -78

Review threads live on the whole diff, not on one commit, so none are shown here - a thread's line means something in the branch's final form, and painting it into an intermediate step would put it on code it is not about.

packages/ios/fixtures/zig-slice/build-and-run.shmodified+12-1
Changes to packages/ios/fixtures/zig-slice/build-and-run.sh
@@ -66,7 +66,7 @@ LAUNCH_PID=$!
6666# The round trip is fast, but a cold simulator is not. Poll rather than sleep a
6767# fixed amount, so a slow boot does not read as a failure.
6868for _ in $(seq 1 60); do
69 if grep -q 'i=5' "$LOG" 2>/dev/null && grep -q 'i=3' "$LOG" 2>/dev/null; then sleep 1; break; fi
69 if grep -q 'i=7' "$LOG" 2>/dev/null && grep -q 'i=5' "$LOG" 2>/dev/null; then sleep 1; break; fi
7070 sleep 1
7171done
7272kill "$LAUNCH_PID" 2>/dev/null || true
@@ -111,4 +111,15 @@ echo "ok: unserved action reached the dispatcher (i=4 seen ${C4}x)"
111111[ "$C5" -ge 1 ] || { echo "FAIL: the host shim never answered, or its answer never reached the page"; exit 1; }
112112echo "ok: hand-off to host shim closed (i=5 seen ${C5}x)"
113113
114C6="$(count 6)"; C7="$(count 7)"
115
116[ "$C6" -ge 1 ] || { echo "FAIL: the rejecting action never reached the dispatcher"; exit 1; }
117echo "ok: rejecting action reached the dispatcher (i=6 seen ${C6}x)"
118
119# i=7 requires the page's __craftBridgeError handler to have seen error:true,
120# the HOST_DECLINED code, id 6, and a message whose backslash, quote and
121# newline survived Zig's escaping. Any of those wrong and this never fires.
122[ "$C7" -ge 1 ] || { echo "FAIL: the shim's rejection never reached the page intact"; exit 1; }
123echo "ok: error route closed with escaping intact (i=7 seen ${C7}x)"
124
114125echo "PASS"
packages/ios/fixtures/zig-slice/page.mmodified+17-0
Changes to packages/ios/fixtures/zig-slice/page.m
@@ -11,6 +11,9 @@
1111// i=3 the user script had already run when the page's own script executed
1212// i=4 the page called an action Zig does *not* serve
1313// i=5 that reply came back, having been answered by the host shim
14// i=6 the page called an action the shim answers by *rejecting*
15// i=7 the rejection arrived via __craftBridgeError with its id, code, and
16// an unmangled message — proving the error route and Zig-side escaping
1417//
1518// i=2 and i=5 are the load-bearing ones, and they prove different things.
1619// i=2 cannot be produced by a stub: only a real UIKit process reports
@@ -33,6 +36,18 @@ const char craft_slice_page[] =
3336 " bridge.postMessage({t:'mobile', a:'getDeviceInfo', i:3});\n"
3437 "}\n"
3538 "\n"
39 "var sentErrorAck = false;\n"
40 "window.__craftBridgeError = function (ctx) {\n"
41 " // The message crossed Zig's escaping with a backslash, quote, and\n"
42 " // newline intact; anything mangled and this equality fails, i=7 never\n"
43 " // fires, and the harness reports the error route broken.\n"
44 " var messageIntact = ctx && ctx.message === 'declined \\\\ \"on purpose\"\\nsecond line';\n"
45 " if (!sentErrorAck && ctx && ctx.error === true && ctx.code === 'HOST_DECLINED'\n"
46 " && ctx.id === 6 && messageIntact) {\n"
47 " sentErrorAck = true;\n"
48 " bridge.postMessage({t:'mobile', a:'getDeviceInfo', i:7});\n"
49 " }\n"
50 "};\n"
3651 "window.__craftBridgeResult = function (action, payload, id) {\n"
3752 " window.__craftSliceAck = JSON.stringify({action: action, id: id, payload: payload});\n"
3853 " document.getElementById('s').textContent = window.__craftSliceAck;\n"
@@ -58,6 +73,8 @@ const char craft_slice_page[] =
5873 " bridge.postMessage({t:'mobile', a:'getDeviceInfo', i:1});\n"
5974 " // An action Zig does not serve, so it must reach the host shim.\n"
6075 " bridge.postMessage({t:'mobile', a:'hostOnlyPing', i:4});\n"
76 " // And one the shim answers by rejecting, to prove the error route.\n"
77 " bridge.postMessage({t:'mobile', a:'hostOnlyFail', i:6});\n"
6178 "} else {\n"
6279 " document.getElementById('s').textContent = 'NO BRIDGE';\n"
6380 "}\n"
packages/ios/fixtures/zig-slice/shim.swiftmodified+61-40
Changes to packages/ios/fixtures/zig-slice/shim.swift
@@ -1,57 +1,78 @@
1// The host shim, in Swift, presenting the contract `CraftApp.swift` will.
1// The host shim, mirroring the design `CraftApp.swift`'s CraftSwiftShim uses —
2// including the part most likely to fail silently in production: discovering
3// Zig's delivery exports with `dlsym` rather than linking them.
24//
3// This replaces an Objective-C stand-in. The stand-in proved the runtime
4// mechanism — `objc_getClass` plus a message send — but not that *Swift*
5// presents that mechanism the way Zig expects: that `@objc(CraftSwiftShim)`
6// really does register under that name, that a `static func` becomes a class
7// method reachable by selector, that `String` parameters bridge from NSString,
8// and that `Bool` comes back as the ObjC BOOL Zig reads.
5// That discovery is the template's load-bearing assumption. A pure-Swift app
6// has no Zig runtime, so the template cannot use `@_silgen_name` (a hard link
7// dependency); it resolves the symbols at runtime and declines when absent.
8// Whether `dlsym(dlopen(nil, RTLD_NOW), ...)` finds a symbol that was
9// *statically linked* into the executable is exactly the kind of fact that
10// must be proven on a simulator, because if a build setting strips it from the
11// dynamic symbol table the seam degrades to "shim declines everything" with no
12// error anywhere.
913//
10// Those are exactly the assumptions the real wiring will rest on, so they are
11// worth testing against the real compiler rather than assumed from a language
12// that shares an ABI with it.
14// Two actions, proving the two reply routes:
15// hostOnlyPing -> craft_ios_deliver_result (the page's promise resolves)
16// hostOnlyFail -> craft_ios_deliver_error (the page's promise rejects)
17// The error route matters independently: delivering a rejection as a result
18// would run the app's then-branch with an error-shaped object.
1319import Foundation
1420
15// Zig owns the reply path. The shim decides *what* the answer is and hands it
16// back; the wire format, the request id and the escaping stay on the other
17// side. `@_silgen_name` reaches the exported symbol without needing a bridging
18// header, which keeps the harness to one swiftc invocation.
19@_silgen_name("craft_ios_deliver_result")
20func craft_ios_deliver_result(
21 _ action: UnsafePointer<CChar>, _ actionLen: UInt,
22 _ json: UnsafePointer<CChar>, _ jsonLen: UInt,
23 _ requestId: Int64
24)
21private typealias DeliverResultFn = @convention(c) (
22 UnsafePointer<CChar>, UInt, UnsafePointer<CChar>, UInt, Int64
23) -> Void
24private typealias DeliverErrorFn = @convention(c) (
25 UnsafePointer<CChar>, UInt, UnsafePointer<CChar>, UInt,
26 UnsafePointer<CChar>, UInt, Int64
27) -> Void
28
29private let deliverResult: DeliverResultFn? = {
30 guard let sym = dlsym(dlopen(nil, RTLD_NOW), "craft_ios_deliver_result") else { return nil }
31 return unsafeBitCast(sym, to: DeliverResultFn.self)
32}()
33
34private let deliverError: DeliverErrorFn? = {
35 guard let sym = dlsym(dlopen(nil, RTLD_NOW), "craft_ios_deliver_error") else { return nil }
36 return unsafeBitCast(sym, to: DeliverErrorFn.self)
37}()
2538
2639@objc(CraftSwiftShim)
2740public class CraftSwiftShim: NSObject {
28 // Selector: handleAction:payload:requestId: — which is what
29 // `ios_dispatch.handOffToHost` sends. A mismatch here is not a compile
30 // error on either side, so the simulator assertion is what catches it.
3141 @objc public static func handleAction(
3242 _ action: String,
3343 payload: String,
3444 requestId: Int64
3545 ) -> Bool {
36 // Exactly one action, to prove the seam. A real shim dispatches the
37 // ~105 the Swift template still owns.
38 guard action == "hostOnlyPing" else {
39 // Not ours. Zig answers UnknownAction, which is the same path a
40 // fully-migrated app with no shim at all takes.
41 return false
42 }
43
44 let json = "{\"servedBy\":\"host-shim\",\"language\":\"swift\",\"payloadBytes\":\(payload.utf8.count)}"
46 switch action {
47 case "hostOnlyPing":
48 guard let deliverResult else { return false }
49 let json = "{\"servedBy\":\"host-shim\",\"language\":\"swift\",\"payloadBytes\":\(payload.utf8.count)}"
50 action.withCString { a in
51 json.withCString { j in
52 deliverResult(a, UInt(strlen(a)), j, UInt(strlen(j)), requestId)
53 }
54 }
55 return true
4556
46 action.withCString { a in
47 json.withCString { j in
48 craft_ios_deliver_result(
49 a, UInt(strlen(a)),
50 j, UInt(strlen(j)),
51 requestId
52 )
57 case "hostOnlyFail":
58 guard let deliverError else { return false }
59 // The message deliberately contains the characters Swift's old
60 // hand-escaping mangled: a backslash, a quote, and a newline. If
61 // they reach the page intact, escaping lives on the Zig side where
62 // it belongs.
63 let message = "declined \\ \"on purpose\"\nsecond line"
64 action.withCString { a in
65 message.withCString { m in
66 "HOST_DECLINED".withCString { c in
67 deliverError(a, UInt(strlen(a)), m, UInt(strlen(m)),
68 c, UInt(strlen(c)), requestId)
69 }
70 }
5371 }
72 return true
73
74 default:
75 return false
5476 }
55 return true
5677 }
5778}
packages/ios/scripts/typecheck-template.shadded+26-0
Changes to packages/ios/scripts/typecheck-template.sh
@@ -0,0 +1,26 @@
1#!/usr/bin/env bash
2# Type-check CraftApp.swift without generating a project.
3#
4# The template cannot be compiled as-is: it carries {⁠{BUNDLE_ID}} placeholders
5# and top-level code, and it references CraftActivityAttributes from a sibling
6# template. This substitutes a dummy id, adds -parse-as-library, and includes
7# the sibling — which is exactly what the generated app does, minus xcodegen.
8#
9# Detecting failure by exit code, not by grepping for "error:": the file is
10# full of `rejectCallback(callbackId, error: ...)` argument labels, and a grep
11# happily counts those as compiler errors. That mistake already cost a cycle.
12set -euo pipefail
13
14ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
15TPL="$ROOT/packages/ios/templates"
16TMP="$(mktemp -d)"
17trap 'rm -rf "$TMP"' EXIT
18
19sed 's/{⁠{BUNDLE_ID}}/app.craft.typecheck/g' "$TPL/CraftApp.swift" > "$TMP/CraftApp.swift"
20
21SDK="$(xcrun --sdk iphonesimulator --show-sdk-path)"
22swiftc -typecheck -parse-as-library \
23 -sdk "$SDK" -target arm64-apple-ios18.0-simulator \
24 "$TMP/CraftApp.swift" "$TPL/CraftActivityAttributes.swift"
25
26echo "CraftApp.swift typechecks"
packages/ios/templates/CraftApp.swiftmodified+128-3
Changes to packages/ios/templates/CraftApp.swift
@@ -364,7 +364,12 @@ struct CraftWebView: UIViewRepresentable {
364364 func updateUIView(_ webView: WKWebView, context: Context) {}
365365
366366 func makeCoordinator() -> Coordinator {
367 Coordinator(config: config)
367 let coordinator = Coordinator(config: config)
368 // The Zig dispatcher finds CraftSwiftShim by class name; the shim finds
369 // its way back to the live coordinator through this. Weak, because
370 // SwiftUI owns the coordinator's lifetime.
371 CraftSwiftShim.coordinator = coordinator
372 return coordinator
368373 }
369374
370375 // MARK: - Coordinator (Native Bridge)
@@ -511,8 +516,19 @@ struct CraftWebView: UIViewRepresentable {
511516 guard let body = message.body as? [String: Any],
512517 let action = body["action"] as? String else { return }
513518
514 let callbackId = body["callbackId"] as? String
519 dispatch(action: action, body: body, callbackId: body["callbackId"] as? String)
520 }
515521
522 /// The action switch, reachable from two directions: the
523 /// WKScriptMessageHandler above, and `CraftSwiftShim.handleAction` when
524 /// the Zig dispatcher hands over an action it has not migrated yet.
525 ///
526 /// A hand-off call arrives with a synthetic callbackId of the form
527 /// "zig:<requestId>". The reply helpers recognise that prefix and route
528 /// the answer back through the Zig runtime's exported
529 /// `craft_ios_deliver_result` instead of evaluating JavaScript here —
530 /// one reply path, owned by whichever side received the page's message.
531 func dispatch(action: String, body: [String: Any], callbackId: String?) {
516532 switch action {
517533 case "startListening":
518534 if config.enableSpeechRecognition { startSpeechRecognition() }
@@ -2426,6 +2442,10 @@ struct CraftWebView: UIViewRepresentable {
24262442 rejectCallback(callbackId, error: "Native result could not be serialized", code: "SERIALIZATION_ERROR")
24272443 return
24282444 }
2445 // A hand-off from the Zig dispatcher replies through Zig, which
2446 // owns the wire format, the request id, and the escaping. Replying
2447 // by JavaScript here as well would give the page two answers.
2448 if CraftSwiftShim.deliverResultIfHandOff(id, json: resultStr) { return }
24292449 let script = "window.craft._resolveCallback('\(id)', \(resultStr));"
24302450 DispatchQueue.main.async { self.webView?.evaluateJavaScript(script, completionHandler: nil) }
24312451 }
@@ -2436,7 +2456,17 @@ struct CraftWebView: UIViewRepresentable {
24362456
24372457 private func rejectCallback(_ callbackId: String?, error: String, code: String = "CRAFT_ERROR") {
24382458 guard let id = callbackId else { return }
2439 let escapedError = error.replacingOccurrences(of: "'", with: "\\'").replacingOccurrences(of: "\n", with: "\\n")
2459 // A hand-off rejection goes back through Zig's error route, so the
2460 // page's promise *rejects*. Delivering it as a result would run the
2461 // app's then-branch with an error-shaped object — fabricated
2462 // success wearing a different hat.
2463 if CraftSwiftShim.deliverErrorIfHandOff(id, message: error, code: code) { return }
2464 // Backslashes first: escaping ' and \n but not \ let an error
2465 // message containing a backslash break out of the string literal.
2466 let escapedError = error
2467 .replacingOccurrences(of: "\\", with: "\\\\")
2468 .replacingOccurrences(of: "'", with: "\\'")
2469 .replacingOccurrences(of: "\n", with: "\\n")
24402470 let script = "window.craft._rejectCallback('\(id)', '\(escapedError)', '\(code)');"
24412471 DispatchQueue.main.async { self.webView?.evaluateJavaScript(script, completionHandler: nil) }
24422472 }
@@ -5159,3 +5189,98 @@ extension CraftWebView.Coordinator: WCSessionDelegate {
51595189 }
51605190 }
51615191}
5192
5193
5194// MARK: - Zig hand-off shim
5195
5196/// The seam the Zig dispatcher hands unmigrated actions through.
5197///
5198/// Discovery is symmetric and both directions are runtime-only. Zig finds this
5199/// class with `objc_getClass("CraftSwiftShim")`; this class finds Zig's
5200/// delivery exports with `dlsym`. Neither side links the other, so a
5201/// pure-Swift app (no Zig runtime) and a fully-migrated Zig app (no shim work
5202/// left) both build and run without dead dependencies.
5203///
5204/// The shim decides *what* the answer is, never *how* it reaches the page.
5205/// Replies go back through Zig's `craft_ios_deliver_result` /
5206/// `craft_ios_deliver_error`, which own the wire format, the request id, and
5207/// the escaping. Two components replying to one page by different routes is
5208/// how this codebase accumulated five envelopes.
5209@objc(CraftSwiftShim)
5210final class CraftSwiftShim: NSObject {
5211 /// The coordinator serving hand-offs. Set by `makeCoordinator`.
5212 static weak var coordinator: CraftWebView.Coordinator?
5213
5214 private typealias DeliverResultFn = @convention(c) (
5215 UnsafePointer<CChar>, UInt, UnsafePointer<CChar>, UInt, Int64
5216 ) -> Void
5217 private typealias DeliverErrorFn = @convention(c) (
5218 UnsafePointer<CChar>, UInt, UnsafePointer<CChar>, UInt,
5219 UnsafePointer<CChar>, UInt, Int64
5220 ) -> Void
5221
5222 private static let deliverResult: DeliverResultFn? = {
5223 guard let sym = dlsym(dlopen(nil, RTLD_NOW), "craft_ios_deliver_result") else { return nil }
5224 return unsafeBitCast(sym, to: DeliverResultFn.self)
5225 }()
5226
5227 private static let deliverError: DeliverErrorFn? = {
5228 guard let sym = dlsym(dlopen(nil, RTLD_NOW), "craft_ios_deliver_error") else { return nil }
5229 return unsafeBitCast(sym, to: DeliverErrorFn.self)
5230 }()
5231
5232 /// Entry point for the Zig dispatcher. Selector: handleAction:payload:requestId:
5233 ///
5234 /// Returns false when this shim cannot serve the call — no live
5235 /// coordinator, or no Zig runtime to reply through — so Zig answers the
5236 /// page with UnknownAction instead of the call vanishing.
5237 @objc static func handleAction(_ action: String, payload: String, requestId: Int64) -> Bool {
5238 guard let coordinator, deliverResult != nil else { return false }
5239
5240 let body = ((try? JSONSerialization.jsonObject(with: Data(payload.utf8))) as? [String: Any]) ?? [:]
5241
5242 // The synthetic callbackId routes this call's reply back through Zig.
5243 // It carries the action too, because the reply helpers do not otherwise
5244 // know it, and Zig's reply names the action for the page's
5245 // action-matching fallback.
5246 coordinator.dispatch(action: action, body: body, callbackId: "zig:\(requestId):\(action)")
5247 return true
5248 }
5249
5250 /// Route a resolve through Zig when the callbackId marks a hand-off.
5251 /// Returns true when the reply has been (or could only be) handled here.
5252 static func deliverResultIfHandOff(_ callbackId: String, json: String) -> Bool {
5253 guard let (requestId, action) = parseHandOffId(callbackId) else { return false }
5254 guard let deliverResult else { return true } // hand-off id but no runtime: drop, never eval JS
5255 action.withCString { a in
5256 json.withCString { j in
5257 deliverResult(a, UInt(strlen(a)), j, UInt(strlen(j)), requestId)
5258 }
5259 }
5260 return true
5261 }
5262
5263 /// Route a rejection through Zig's error path, so the page's promise
5264 /// rejects rather than resolving with an error-shaped object.
5265 static func deliverErrorIfHandOff(_ callbackId: String, message: String, code: String) -> Bool {
5266 guard let (requestId, action) = parseHandOffId(callbackId) else { return false }
5267 guard let deliverError else { return true }
5268 action.withCString { a in
5269 message.withCString { m in
5270 code.withCString { c in
5271 deliverError(a, UInt(strlen(a)), m, UInt(strlen(m)), c, UInt(strlen(c)), requestId)
5272 }
5273 }
5274 }
5275 return true
5276 }
5277
5278 /// "zig:<requestId>:<action>" -> (requestId, action). Nil for ordinary
5279 /// page-issued callback ids, which keep their JavaScript reply path.
5280 private static func parseHandOffId(_ callbackId: String) -> (Int64, String)? {
5281 guard callbackId.hasPrefix("zig:") else { return nil }
5282 let rest = callbackId.dropFirst(4)
5283 guard let sep = rest.firstIndex(of: ":"), let id = Int64(rest[..<sep]) else { return nil }
5284 return (id, String(rest[rest.index(after: sep)...]))
5285 }
5286}
packages/zig/src/bridge_mobile_clipboard.zigadded+541-0
Changes to packages/zig/src/bridge_mobile_clipboard.zig
@@ -0,0 +1,541 @@
1//! The clipboard actions of the `mobile` namespace: `clipboardRead`,
2//! `clipboardWrite`.
3//!
4//! Ported from the two inline arms in `CraftApp.swift`'s dispatcher. The Swift
5//! is eleven lines, and three of its behaviours are deliberately not carried
6//! across:
7//!
8//! 1. **It can leave the caller waiting forever.** Both arms are an `if` with
9//! no `else`, and clipboard is one of the few actions whose promise is built
10//! inline instead of through `_createCallback` — which is the only thing
11//! that installs the 30-second rejection. So a false `enableClipboard`, or a
12//! `text` that is not a string, replies with nothing at all: not resolved,
13//! not rejected, ever. Every path in this file ends in a reply or an error.
14//! 2. **`UIPasteboard.string ?? ""` conflates three different facts.** See
15//! `readClipboard`.
16//! 3. **It reports success for a write it never checked.** See `putString`.
17//!
18//! ## The payload moved, and defaulting it would erase the clipboard
19//!
20//! The Swift-injected `window.craft` posts `text` at the *top level*, a sibling
21//! of `action`. `ios_dispatch` never looks there — it hands a namespace only
22//! the stringified `d`. A page still posting the flat legacy shape therefore
23//! arrives here with `d` absent, which `payloadOf` turns into `{}`. That is why
24//! an absent `text` is `MissingData` rather than a defaulted `""`: defaulting is
25//! precisely how `craft.fs.writeFile` came to write empty files for months, and
26//! here the same mistake would silently *wipe* the user's clipboard and report
27//! success. The page-side call must be
28//! `{t:'mobile', a:'clipboardWrite', d:'{"text":"…"}', i:N}`.
29//!
30//! ## `enableClipboard` is a deliberate behaviour change, recorded here
31//!
32//! The Swift gate reads `config.enableClipboard`, which originates in
33//! TypeScript (`packages/ios/src/index.ts`, defaulting to `false`), is
34//! templated into the Swift `CraftConfig`, and never reaches Zig. Rather than
35//! guess at it or drop it, it is left plumbable: a host can call
36//! `craft_ios_set_clipboard_enabled(false)` at startup. It defaults to
37//! *enabled*, because a default of off would answer every app with
38//! PERMISSION_DENIED until a host that does not exist yet is written. This is a
39//! real change: an app that left `enableClipboard: false` now gets a working
40//! clipboard while the capability object the page reads still says
41//! `clipboard: false`.
42
43const std = @import("std");
44const builtin = @import("builtin");
45const capabilities = @import("capabilities.zig");
46const bridge_error = @import("bridge_error.zig");
47const objc_runtime = @import("objc_runtime.zig");
48
49const objc = objc_runtime.objc;
50
51/// The action names, spelled exactly as the Swift `case` labels spell them.
52///
53/// `test/ios_conformance_test.zig` matches the two lists by string, so a
54/// tidier spelling here does not read as "migrated" — it reads as "Zig serves
55/// an action the spec does not have", and the Swift arm stays live forever.
56pub const A = struct {
57 pub const clipboard_read = "clipboardRead";
58 pub const clipboard_write = "clipboardWrite";
59};
60
61/// Both `.result`. `clipboardWrite` hands nothing back but is not
62/// fire-and-forget: Swift resolves it with `true`, and `craft.clipboard.write()`
63/// returns a promise the page awaits. Declaring it `.none` would strand that
64/// caller for the whole request timeout. Desktop's `clipboard/writeText` is
65/// `.none` for a reason that does not apply here — `craft-bridge.js` posts it
66/// through `_send`, which resolves on post rather than on an answer.
67pub const capability_actions = [_]capabilities.ActionDecl{
68 .{ .name = A.clipboard_read, .reply = .result },
69 .{ .name = A.clipboard_write, .reply = .result },
70};
71
72/// The two literal replies. `clipboardRead` answers a *bare* JSON string and
73/// `clipboardWrite` a bare `true`; `formatResultJS` interpolates whatever it is
74/// given straight into `__craftBridgeResult(...)`, so neither needs wrapping.
75const reply_true = "true";
76const reply_no_text = "\"\"";
77
78/// NSUTF8StringEncoding, for `-lengthOfBytesUsingEncoding:`.
79const ns_utf8_string_encoding: usize = 4;
80
81/// Whether the app permits clipboard access — the `enableClipboard` gate the
82/// module comment describes.
83///
84/// A plain `bool`, not an atomic: WebKit delivers
85/// `userContentController:didReceiveScriptMessage:` on the main thread and
86/// `ios_dispatch.handleMessage` runs synchronously from there, so every reader
87/// is the main thread, and the only writer is a host doing this once at startup.
88var clipboard_enabled: bool = true;
89
90pub fn setEnabled(value: bool) void {
91 clipboard_enabled = value;
92}
93
94/// Startup hook for a host that wants the Swift gate back, alongside
95/// `craft_ios_deliver_result`. Turning the capability off makes the handlers
96/// *reject* with `PermissionDenied`; it must never reproduce the Swift gate's
97/// actual failure mode, which was silence.
98export fn craft_ios_set_clipboard_enabled(value: bool) callconv(.c) void {
99 clipboard_enabled = value;
100}
101
102pub const ClipboardBridge = struct {
103 allocator: std.mem.Allocator,
104
105 const Self = @This();
106
107 pub fn init(allocator: std.mem.Allocator) Self {
108 return .{ .allocator = allocator };
109 }
110
111 pub fn deinit(_: *Self) void {}
112
113 pub fn handleMessage(self: *Self, action: []const u8, data: []const u8) !void {
114 if (std.mem.eql(u8, action, A.clipboard_read)) {
115 try self.readClipboard();
116 } else if (std.mem.eql(u8, action, A.clipboard_write)) {
117 try self.writeClipboard(data);
118 } else {
119 return bridge_error.BridgeError.UnknownAction;
120 }
121 }
122
123 /// Read the pasteboard, and say *which* of the "no text" cases happened.
124 ///
125 /// The reply is a bare JSON string — `"hello"`, not `{"text":"hello"}`.
126 /// That is what the page consumes: `test-bridges.html` does
127 /// `'Clipboard: ' + await craft.clipboard.read()`, and an object reply
128 /// renders as `[object Object]`. It diverges from desktop
129 /// `clipboard/readText`, which answers `{"text":…}`; unifying the two is a
130 /// contract change the page has to be rewritten for, so it is not made here
131 /// by accident.
132 ///
133 /// `-hasStrings` is asked first because `-string` on its own cannot tell an
134 /// empty pasteboard from a refusal. On iOS 16+ reading contents another app
135 /// wrote presents a system confirmation, and a denial yields nil with no
136 /// API that reports why. So: no strings at all is answered `""`, which is
137 /// true; strings present but `-string` nil is `PermissionDenied`, because
138 /// something was there and we were not given it. Swift answered `""` to
139 /// both, and to a pasteboard holding an image.
140 ///
141 /// **This action can put an alert on the screen.** A page that calls it on
142 /// load shows the user an unexplained paste prompt. Two things I could not
143 /// verify and that want confirming on a device (the simulator never prompts,
144 /// because a same-app write never does): that `-hasStrings` is itself
145 /// prompt-free, and whether `-string` blocks until the user answers — if it
146 /// does, it blocks this whole synchronous dispatch, and the page's
147 /// 30-second request timeout can fire before the tap.
148 fn readClipboard(self: *Self) !void {
149 if (!clipboard_enabled) return bridge_error.BridgeError.PermissionDenied;
150
151 const pasteboard = try generalPasteboard();
152 if (!try hasStrings(pasteboard)) {
153 bridge_error.sendResultToJS(self.allocator, A.clipboard_read, reply_no_text);
154 return;
155 }
156
157 const text = try pasteboardString(pasteboard) orelse
158 return bridge_error.BridgeError.PermissionDenied;
159
160 const json = try quoteAsJsonString(self.allocator, text);
161 defer self.allocator.free(json);
162 bridge_error.sendResultToJS(self.allocator, A.clipboard_read, json);
163 }
164
165 /// Write `text` to the pasteboard. Requires the field; does not invent it.
166 ///
167 /// An explicitly-sent empty `text` is written and acknowledged. Clearing the
168 /// clipboard is a legitimate request, and `bridge_clipboard.zig`'s
169 /// `if (text.len == 0) return;` is a silent drop the caller cannot tell from
170 /// a success. Only an *absent* `text` is an error.
171 ///
172 /// A non-string `text` is `InvalidParameter`, not coerced. The legacy JS
173 /// posts whatever the caller passed without a `String(...)` — unlike
174 /// `craft-bridge.js:565` — so a page handing in a number reaches here, and
175 /// guessing what it meant would put a stringified guess on the user's
176 /// clipboard.
177 fn writeClipboard(self: *Self, data: []const u8) !void {
178 if (!clipboard_enabled) return bridge_error.BridgeError.PermissionDenied;
179
180 var parsed = std.json.parseFromSlice(std.json.Value, self.allocator, data, .{}) catch |err| switch (err) {
181 // An allocation failure is not a malformed payload, and telling the
182 // page INVALID_JSON about its own perfectly good JSON sends whoever
183 // debugs it to the wrong side of the bridge.
184 error.OutOfMemory => return err,
185 else => return bridge_error.BridgeError.InvalidJSON,
186 };
187 defer parsed.deinit();
188
189 const text = try requiredText(parsed.value);
190 try putString(self.allocator, text);
191 bridge_error.sendResultToJS(self.allocator, A.clipboard_write, reply_true);
192 }
193};
194
195/// The `text` field, or the reason it cannot be used. Pure, so the host tests
196/// can pin the three outcomes that the Swift `as? String` collapsed into one
197/// silent fall-through.
198fn requiredText(payload: std.json.Value) ![]const u8 {
199 const object = switch (payload) {
200 .object => |o| o,
201 else => return bridge_error.BridgeError.InvalidJSON,
202 };
203 const field = object.get("text") orelse return bridge_error.BridgeError.MissingData;
204 return switch (field) {
205 .string => |s| s,
206 else => bridge_error.BridgeError.InvalidParameter,
207 };
208}
209
210/// Render `s` as a complete JSON string literal, quotes included.
211///
212/// `bridge_error.appendJsonEscaped` rather than the hand-rolled loop in
213/// `bridge_clipboard.zig:200`, which misses every control byte below 0x20.
214/// Clipboard contents are arbitrary user bytes and this string is interpolated
215/// into JavaScript that `evaluateJavaScript:` then parses as source.
216///
217/// Allocated rather than built in a stack buffer: unlike a device description,
218/// clipboard text has no ceiling, and a fixed buffer would truncate the paste
219/// into a syntax error in the page.
220fn quoteAsJsonString(allocator: std.mem.Allocator, s: []const u8) ![]u8 {
221 var out: std.ArrayListUnmanaged(u8) = .empty;
222 errdefer out.deinit(allocator);
223
224 try out.append(allocator, '"');
225 try bridge_error.appendJsonEscaped(allocator, &out, s);
226 try out.append(allocator, '"');
227
228 return out.toOwnedSlice(allocator);
229}
230
231/// `+[UIPasteboard generalPasteboard]`.
232///
233/// Both nulls are real conditions and neither is skipped: `objc_getClass`
234/// answers null when UIKit is not in the process, and `generalPasteboard`
235/// answers nil in an app extension, where `UIPasteboard` is unavailable
236/// outright.
237fn generalPasteboard() !objc.id {
238 if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform;
239
240 const UIPasteboard = objc.objc_getClass("UIPasteboard") orelse return error.ClassNotFound;
241 const sel = objc.sel_registerName("generalPasteboard") orelse return error.SelectorNotFound;
242 const pasteboard = objc.msgSendId(UIPasteboard, sel);
243 if (pasteboard == null) return error.NoPasteboard;
244 return pasteboard;
245}
246
247/// `-[UIPasteboard hasStrings]` — whether there is any text to ask for.
248fn hasStrings(pasteboard: objc.id) !bool {
249 if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform;
250
251 const sel = objc.sel_registerName("hasStrings") orelse return error.SelectorNotFound;
252 return objc.msgSendBool(pasteboard, sel);
253}
254
255/// `-[UIPasteboard changeCount]`.
256///
257/// No helper for this in `objc_runtime.zig`, which stops at id/bool/stret, so
258/// the cast is local. `NSInteger` is 64-bit on every supported iOS target,
259/// hence `isize`.
260fn changeCount(pasteboard: objc.id) !isize {
261 if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform;
262
263 const sel = objc.sel_registerName("changeCount") orelse return error.SelectorNotFound;
264 const Fn = *const fn (objc.id, objc.SEL) callconv(.c) isize;
265 const func: Fn = @ptrCast(&objc.objc_msgSend);
266 return func(pasteboard, sel);
267}
268
269/// `-[UIPasteboard string]`, borrowed as UTF-8. Null means the pasteboard
270/// returned nil — which the caller, not this function, decides the meaning of.
271///
272/// The bytes belong to the autoreleased NSString and live until the pool drains
273/// at the end of this run-loop turn; every caller here copies or compares
274/// before returning.
275fn pasteboardString(pasteboard: objc.id) !?[]const u8 {
276 if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform;
277
278 const sel = objc.sel_registerName("string") orelse return error.SelectorNotFound;
279 const ns = objc.msgSendId(pasteboard, sel);
280 if (ns == null) return null;
281 return try nsStringUTF8(ns);
282}
283
284/// The UTF-8 bytes of an NSString.
285///
286/// The length comes from `-lengthOfBytesUsingEncoding:` rather than from
287/// scanning for the terminator: an NSString may legitimately contain U+0000,
288/// and `std.mem.span` would truncate there without saying so — the same quiet
289/// data loss as a dropped payload field, on bytes the user chose. A zero length
290/// means empty or not representable as UTF-8, and both answer `""`.
291fn nsStringUTF8(ns: objc.id) ![]const u8 {
292 if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform;
293
294 const utf8 = objc.getNSStringUTF8(ns) orelse return error.NilString;
295
296 const sel_len = objc.sel_registerName("lengthOfBytesUsingEncoding:") orelse
297 return error.SelectorNotFound;
298 const Fn = *const fn (objc.id, objc.SEL, usize) callconv(.c) usize;
299 const func: Fn = @ptrCast(&objc.objc_msgSend);
300 const len = func(ns, sel_len, ns_utf8_string_encoding);
301
302 return utf8[0..len];
303}
304
305/// `-[UIPasteboard setString:]`, then evidence that it landed.
306///
307/// `setString:` returns void, so "the call did not crash" is not evidence, and
308/// replying `true` on that alone is the fabricated success this migration
309/// exists to remove. `-changeCount` is the one real observation available: a
310/// bump means the pasteboard genuinely changed.
311///
312/// A stationary count is not immediately a failure, though. I could not confirm
313/// that writing text identical to the current contents still bumps the count,
314/// and rejecting a correct "copy pressed twice" would be its own false report —
315/// so no bump falls back to reading the contents back and comparing bytes. Only
316/// *unchanged count and contents that are not what we asked for* is reported as
317/// `NativeCallFailed`. A nil read-back counts as "there is no text on the
318/// pasteboard", which matches a request to write an empty string and nothing
319/// else.
320///
321/// The fallback read can itself raise the iOS 16+ paste prompt, in the one case
322/// where it runs: the write appears not to have landed, so another app may
323/// still own the contents. That is rare enough to be worth the certainty, and
324/// the alternative is answering with a guess.
325fn putString(allocator: std.mem.Allocator, text: []const u8) !void {
326 if (!builtin.target.os.tag.isDarwin()) return error.UnsupportedPlatform;
327
328 const pasteboard = try generalPasteboard();
329 const before = try changeCount(pasteboard);
330
331 // Autoreleased by `+stringWithUTF8String:`; releasing it here would
332 // over-release something the pasteboard has retained.
333 const ns_text = try objc.createNSString(text, allocator);
334 const sel_set = objc.sel_registerName("setString:") orelse return error.SelectorNotFound;
335 objc.msgSendVoid1(pasteboard, sel_set, ns_text);
336
337 if (try changeCount(pasteboard) != before) return;
338
339 const current = try pasteboardString(pasteboard);
340 const landed = if (current) |c| std.mem.eql(u8, c, text) else text.len == 0;
341 if (!landed) return bridge_error.BridgeError.NativeCallFailed;
342}
343
344const testing = std.testing;
345
346test "the declared actions are the ones the handler serves" {
347 try testing.expectEqual(@as(usize, 2), capability_actions.len);
348 try testing.expectEqualStrings(A.clipboard_read, capability_actions[0].name);
349 try testing.expectEqualStrings(A.clipboard_write, capability_actions[1].name);
350
351 // `.result` for both, including the write. A `.none` write would let a
352 // page's `await craft.clipboard.write(x)` sit until the request timeout.
353 for (capability_actions) |decl| {
354 try testing.expectEqual(capabilities.Reply.result, decl.reply);
355 try testing.expectEqual(capabilities.ActionStatus.live, decl.status);
356 }
357}
358
359test "the action names match the Swift case labels exactly" {
360 // The conformance ratchet compares these strings against the labels in
361 // `CraftApp.swift`. A prettier spelling here would leave the Swift arm live
362 // and register the migration as having served an action nobody asked for.
363 try testing.expectEqualStrings("clipboardRead", A.clipboard_read);
364 try testing.expectEqualStrings("clipboardWrite", A.clipboard_write);
365}
366
367test "every declared action dispatches to something" {
368 // It may well fail for want of UIKit on the host — that is fine and is not
369 // what this asserts. What it rules out is a name in the table that
370 // `handleMessage` does not compare against, which is the drift the
371 // capabilities mechanism exists to prevent.
372 var bridge = ClipboardBridge.init(testing.allocator);
373 defer bridge.deinit();
374
375 for (capability_actions) |decl| {
376 bridge.handleMessage(decl.name, "{}") catch |err| {
377 try testing.expect(err != bridge_error.BridgeError.UnknownAction);
378 };
379 }
380}
381
382test "an action the namespace does not serve is reported, not ignored" {
383 var bridge = ClipboardBridge.init(testing.allocator);
384 defer bridge.deinit();
385
386 try testing.expectError(
387 bridge_error.BridgeError.UnknownAction,
388 bridge.handleMessage("clipboardClear", "{}"),
389 );
390 // Near-misses too: the desktop spelling is a different action on a
391 // different namespace and must not be quietly accepted here.
392 try testing.expectError(
393 bridge_error.BridgeError.UnknownAction,
394 bridge.handleMessage("writeText", "{\"text\":\"x\"}"),
395 );
396}
397
398test "an absent text field is refused rather than defaulted to empty" {
399 // The single highest-risk case in this migration: a page still posting the
400 // flat legacy shape (`text` beside `action`, no `d`) arrives as `{}`. A
401 // default would wipe the user's clipboard and report success.
402 const allocator = testing.allocator;
403 var parsed = try std.json.parseFromSlice(std.json.Value, allocator, "{}", .{});
404 defer parsed.deinit();
405
406 try testing.expectError(bridge_error.BridgeError.MissingData, requiredText(parsed.value));
407}
408
409test "a legacy top-level text field does not count as the payload" {
410 const allocator = testing.allocator;
411 var parsed = try std.json.parseFromSlice(
412 std.json.Value,
413 allocator,
414 "{\"action\":\"clipboardWrite\",\"callbackId\":\"cb_1\"}",
415 .{},
416 );
417 defer parsed.deinit();
418
419 try testing.expectError(bridge_error.BridgeError.MissingData, requiredText(parsed.value));
420}
421
422test "text is read from the field the page actually sends" {
423 const allocator = testing.allocator;
424 var parsed = try std.json.parseFromSlice(
425 std.json.Value,
426 allocator,
427 "{\"text\":\"hello \\\"world\\\"\"}",
428 .{},
429 );
430 defer parsed.deinit();
431
432 try testing.expectEqualStrings("hello \"world\"", try requiredText(parsed.value));
433}
434
435test "an explicitly empty text is a value, not a missing field" {
436 // Clearing the clipboard is a legitimate request. `bridge_clipboard.zig`
437 // returns early on a zero-length string and acknowledges nothing, which the
438 // caller cannot tell from success.
439 const allocator = testing.allocator;
440 var parsed = try std.json.parseFromSlice(std.json.Value, allocator, "{\"text\":\"\"}", .{});
441 defer parsed.deinit();
442
443 try testing.expectEqualStrings("", try requiredText(parsed.value));
444}
445
446test "a non-string text is refused rather than coerced" {
447 // The legacy JS posts whatever the caller passed, with no `String(...)`.
448 const allocator = testing.allocator;
449 for ([_][]const u8{
450 "{\"text\":42}",
451 "{\"text\":null}",
452 "{\"text\":true}",
453 "{\"text\":{\"a\":1}}",
454 "{\"text\":[\"a\"]}",
455 }) |payload| {
456 var parsed = try std.json.parseFromSlice(std.json.Value, allocator, payload, .{});
457 defer parsed.deinit();
458 try testing.expectError(bridge_error.BridgeError.InvalidParameter, requiredText(parsed.value));
459 }
460}
461
462test "a payload that is not an object is refused" {
463 const allocator = testing.allocator;
464 var parsed = try std.json.parseFromSlice(std.json.Value, allocator, "\"hello\"", .{});
465 defer parsed.deinit();
466
467 try testing.expectError(bridge_error.BridgeError.InvalidJSON, requiredText(parsed.value));
468}
469
470test "malformed payload JSON is reported as such, not as a missing field" {
471 var bridge = ClipboardBridge.init(testing.allocator);
472 defer bridge.deinit();
473
474 try testing.expectError(
475 bridge_error.BridgeError.InvalidJSON,
476 bridge.handleMessage(A.clipboard_write, "{\"text\":"),
477 );
478}
479
480test "the read reply is a bare JSON string, not an object" {
481 // `test-bridges.html` concatenates the result: `'Clipboard: ' + result`.
482 // An object would render as `[object Object]`.
483 const allocator = testing.allocator;
484 const json = try quoteAsJsonString(allocator, "hello");
485 defer allocator.free(json);
486 try testing.expectEqualStrings("\"hello\"", json);
487}
488
489test "read replies survive quotes, backslashes, newlines, and control bytes" {
490 // Clipboard contents are arbitrary user bytes and this lands inside
491 // JavaScript source. The escape loop in `bridge_clipboard.zig` passes
492 // control bytes through untouched, which produces invalid JSON.
493 const allocator = testing.allocator;
494 const json = try quoteAsJsonString(allocator, "a\"b\\c\nd\te\x01f");
495 defer allocator.free(json);
496 try testing.expectEqualStrings("\"a\\\"b\\\\c\\nd\\te\\u0001f\"", json);
497
498 // And it is still parseable as the string it started as.
499 var parsed = try std.json.parseFromSlice(std.json.Value, allocator, json, .{});
500 defer parsed.deinit();
501 try testing.expectEqualStrings("a\"b\\c\nd\te\x01f", parsed.value.string);
502}
503
504test "an empty clipboard is reported as an empty string, and it parses" {
505 const allocator = testing.allocator;
506 var parsed = try std.json.parseFromSlice(std.json.Value, allocator, reply_no_text, .{});
507 defer parsed.deinit();
508 try testing.expectEqualStrings("", parsed.value.string);
509}
510
511test "the write reply is bare true, which is what the page resolves with" {
512 const allocator = testing.allocator;
513 var parsed = try std.json.parseFromSlice(std.json.Value, allocator, reply_true, .{});
514 defer parsed.deinit();
515 try testing.expect(parsed.value.bool);
516}
517
518test "a disabled clipboard rejects both actions rather than falling silent" {
519 // The Swift gate's failure mode was a promise that never settled. Whatever
520 // is decided about `enableClipboard`, that must not come back.
521 var bridge = ClipboardBridge.init(testing.allocator);
522 defer bridge.deinit();
523
524 setEnabled(false);
525 defer setEnabled(true);
526
527 try testing.expectError(
528 bridge_error.BridgeError.PermissionDenied,
529 bridge.handleMessage(A.clipboard_read, "{}"),
530 );
531 try testing.expectError(
532 bridge_error.BridgeError.PermissionDenied,
533 bridge.handleMessage(A.clipboard_write, "{\"text\":\"x\"}"),
534 );
535}
536
537test "UIKit work is refused explicitly off Darwin instead of being skipped" {
538 if (builtin.target.os.tag.isDarwin()) return error.SkipZigTest;
539 try testing.expectError(error.UnsupportedPlatform, generalPasteboard());
540 try testing.expectError(error.UnsupportedPlatform, putString(testing.allocator, "x"));
541}
packages/zig/src/ios_dispatch.zigmodified+92-0
Changes to packages/zig/src/ios_dispatch.zig
@@ -259,6 +259,74 @@ export fn craft_ios_deliver_result(
259259 bridge_error.sendResultToJS(std.heap.c_allocator, action, json);
260260}
261261
262/// Deliver an error the host shim produced.
263///
264/// A separate export from `craft_ios_deliver_result` because results and
265/// errors reach the page by different routes — `__craftBridgeResult` resolves
266/// the pending promise, `__craftBridgeError` rejects it. Delivering a shim
267/// rejection as a result would make the caller's promise *resolve* with an
268/// error-shaped object, which is the fabricated-success bug wearing a
269/// different hat: the catch block the app wrote never runs.
270///
271/// The message and code are free text from the shim, escaped here with the
272/// same `appendJsonEscaped` every native error already goes through — the
273/// Swift side must not hand-escape (its own attempt replaced only `'` and
274/// let backslashes break out of the string literal).
275export fn craft_ios_deliver_error(
276 action_ptr: [*]const u8,
277 action_len: usize,
278 message_ptr: [*]const u8,
279 message_len: usize,
280 code_ptr: [*]const u8,
281 code_len: usize,
282 request_id: i64,
283) callconv(.c) void {
284 const allocator = std.heap.c_allocator;
285 const action = action_ptr[0..action_len];
286 const message = message_ptr[0..message_len];
287 const code = code_ptr[0..code_len];
288
289 var json: std.ArrayListUnmanaged(u8) = .empty;
290 defer json.deinit(allocator);
291
292 buildShimError(allocator, &json, action, message, code, request_id) catch return;
293
294 const js = std.fmt.allocPrint(
295 allocator,
296 "if(window.__craftBridgeError)window.__craftBridgeError({s});",
297 .{json.items},
298 ) catch return;
299 defer allocator.free(js);
300
301 evalJS(js) catch |err| {
302 std.log.warn("ios bridge: could not deliver shim error for '{s}': {}", .{ action, err });
303 };
304}
305
306/// The `__craftBridgeError` payload for a shim-raised error. Split out so the
307/// host tests can pin the exact shape without a webview.
308fn buildShimError(
309 allocator: std.mem.Allocator,
310 out: *std.ArrayListUnmanaged(u8),
311 action: []const u8,
312 message: []const u8,
313 code: []const u8,
314 request_id: i64,
315) !void {
316 try out.appendSlice(allocator, "{\"error\":true,\"code\":\"");
317 try bridge_error.appendJsonEscaped(allocator, out, code);
318 try out.appendSlice(allocator, "\",\"action\":\"");
319 try bridge_error.appendJsonEscaped(allocator, out, action);
320 try out.appendSlice(allocator, "\",\"message\":\"");
321 try bridge_error.appendJsonEscaped(allocator, out, message);
322 try out.append(allocator, '"');
323 if (request_id >= 0) {
324 try out.appendSlice(allocator, ",\"id\":");
325 try out.print(allocator, "{d}", .{request_id});
326 }
327 try out.append(allocator, '}');
328}
329
262330const testing = std.testing;
263331
264332test "an envelope without a type is rejected" {
@@ -376,3 +444,27 @@ test "a request id survives the trip out to the host and back" {
376444 defer request_context.pop();
377445 try testing.expectEqual(@as(?u64, 7), request_context.current());
378446}
447
448test "a shim error carries its code, message, and id, correctly escaped" {
449 var out: std.ArrayListUnmanaged(u8) = .empty;
450 defer out.deinit(testing.allocator);
451
452 // The message contains the three characters Swift's hand-escaping got
453 // wrong: a backslash, a quote, and a newline.
454 try buildShimError(testing.allocator, &out, "share", "path \\ \"x\"\ngone", "NOT_FOUND", 9);
455 try testing.expectEqualStrings(
456 "{\"error\":true,\"code\":\"NOT_FOUND\",\"action\":\"share\",\"message\":\"path \\\\ \\\"x\\\"\\ngone\",\"id\":9}",
457 out.items,
458 );
459}
460
461test "a shim error with no request id omits the id field entirely" {
462 // Omitted, not null or -1: the page's error handler treats a present id as
463 // a promise to reject, and a sentinel would reject nothing — or worse,
464 // someone else's call.
465 var out: std.ArrayListUnmanaged(u8) = .empty;
466 defer out.deinit(testing.allocator);
467
468 try buildShimError(testing.allocator, &out, "share", "m", "E", -1);
469 try testing.expect(std.mem.indexOf(u8, out.items, "\"id\"") == null);
470}