@stacksjs/stx 0.2.493 → 0.2.495

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.
Files changed (76) hide show
  1. package/dist/{chunk-nwy97xaa.js → chunk-0adrp7qd.js} +1 -1
  2. package/dist/{chunk-zxkzdbcv.js → chunk-15w4adyd.js} +1 -1
  3. package/dist/{chunk-nf9fhj10.js → chunk-2gr5zcm3.js} +1 -1
  4. package/dist/chunk-2wvezjd5.js +33 -0
  5. package/dist/{chunk-q21e52cb.js → chunk-33snwgdy.js} +1 -1
  6. package/dist/chunk-379nn8yc.js +2 -0
  7. package/dist/{chunk-jnf8vt18.js → chunk-40jd0b4h.js} +1 -1
  8. package/dist/{chunk-nfd56dgj.js → chunk-4mrgy3ve.js} +1 -1
  9. package/dist/{chunk-djwms13g.js → chunk-4rmdngzw.js} +1 -1
  10. package/dist/{chunk-4tb1mqr8.js → chunk-4ssg2hn4.js} +1 -1
  11. package/dist/chunk-52saa2nj.js +2 -0
  12. package/dist/{chunk-z26ty1t1.js → chunk-6v3p6cx1.js} +1 -1
  13. package/dist/{chunk-e43ckdk2.js → chunk-78vfptph.js} +1 -1
  14. package/dist/{chunk-b6xrqx6w.js → chunk-7e6sxdp6.js} +1 -1
  15. package/dist/{chunk-kzg3h5wg.js → chunk-81t6zr3m.js} +1 -1
  16. package/dist/{chunk-ze9vhhvc.js → chunk-8qdvhbv7.js} +2 -2
  17. package/dist/{chunk-2b1zg7xp.js → chunk-93sr9q8g.js} +1 -1
  18. package/dist/{chunk-sdxq5ej9.js → chunk-9mh1qq3g.js} +1 -1
  19. package/dist/{chunk-ft6k76e4.js → chunk-b5mcvm6y.js} +1 -1
  20. package/dist/{chunk-z7bqn398.js → chunk-b90y5phw.js} +5 -5
  21. package/dist/{chunk-7c18zqdc.js → chunk-dve4q9tg.js} +1 -1
  22. package/dist/{chunk-0zs1fd9z.js → chunk-fxppbahx.js} +1 -1
  23. package/dist/{chunk-c0jedy4d.js → chunk-gvkfydq5.js} +1 -1
  24. package/dist/{chunk-jaghd4j0.js → chunk-h0sd5cda.js} +2 -2
  25. package/dist/{chunk-bay6snzz.js → chunk-hhj1txvj.js} +1 -1
  26. package/dist/{chunk-j1d4aemv.js → chunk-jh385m2w.js} +1 -1
  27. package/dist/chunk-kxg9q64a.js +2 -0
  28. package/dist/{chunk-jws8btr5.js → chunk-m9nr12a1.js} +40 -40
  29. package/dist/{chunk-dnq9fhwf.js → chunk-mdfrm5hv.js} +1 -1
  30. package/dist/{chunk-fzwy4nny.js → chunk-mq7vvaf4.js} +1 -1
  31. package/dist/{chunk-cfj3c9ss.js → chunk-nfffn3s0.js} +1 -1
  32. package/dist/{chunk-0acycggt.js → chunk-nw7qvyek.js} +1 -1
  33. package/dist/{chunk-perp76wy.js → chunk-ny64ezsj.js} +1 -1
  34. package/dist/{chunk-f324yttz.js → chunk-qhnpc3ac.js} +1 -1
  35. package/dist/{chunk-1x4b64mx.js → chunk-qjba655t.js} +1 -1
  36. package/dist/{chunk-gparzn81.js → chunk-qjxxd4a0.js} +1 -1
  37. package/dist/{chunk-fh3r97cq.js → chunk-qsy7phd4.js} +1 -1
  38. package/dist/{chunk-vbthtg0x.js → chunk-rfq1jfhf.js} +1 -1
  39. package/dist/{chunk-fh7w72xm.js → chunk-rr41gk8b.js} +1 -1
  40. package/dist/{chunk-aertsqje.js → chunk-snyq0jj6.js} +1 -1
  41. package/dist/{chunk-52fcqzmc.js → chunk-stvqwzen.js} +1 -1
  42. package/dist/{chunk-6mqb6vf7.js → chunk-tdetcthb.js} +1 -1
  43. package/dist/{chunk-gwvg2c50.js → chunk-v8m2khkq.js} +1 -1
  44. package/dist/{chunk-g3hn7ncc.js → chunk-vtn0gmen.js} +2 -2
  45. package/dist/{chunk-emx5wsaa.js → chunk-xk2mwk61.js} +1 -1
  46. package/dist/{chunk-86vgttef.js → chunk-yvt8zszz.js} +1 -1
  47. package/dist/{chunk-nnqjjtqz.js → chunk-zbzmfqmk.js} +1 -1
  48. package/dist/{chunk-bt58m9y8.js → chunk-zqxqdns1.js} +1 -1
  49. package/dist/cli.js +7 -7
  50. package/dist/component-renderer.js +15 -1
  51. package/dist/craft-entry.js +1 -1
  52. package/dist/craft.js +1 -1
  53. package/dist/native/bridge/protocol.d.ts +6 -1
  54. package/dist/native/compiler/component-mapping.js +1 -0
  55. package/dist/native/compiler/html-to-ir.js +26 -5
  56. package/dist/native/compiler/icons.d.ts +15 -0
  57. package/dist/native/compiler/icons.js +15 -0
  58. package/dist/native/compiler/ir.d.ts +1 -0
  59. package/dist/native/components/primitives.d.ts +48 -1
  60. package/dist/native/components/primitives.js +3 -0
  61. package/dist/native/primitives/Video.stx +5 -0
  62. package/dist/native/prop-names.d.ts +6 -0
  63. package/dist/native/prop-names.js +34 -1
  64. package/dist/native/runtime/craft-bridge.js +293 -36
  65. package/dist/native/runtime/craft.d.ts +85 -1
  66. package/dist/native/runtime/event-stream.d.ts +31 -0
  67. package/dist/native/runtime/event-stream.js +232 -0
  68. package/dist/native/runtime/jsc-globals.d.ts +23 -0
  69. package/dist/native/runtime/jsc-globals.js +60 -0
  70. package/dist/pwa.js +1 -1
  71. package/dist/ssg.js +2 -2
  72. package/package.json +5 -5
  73. package/dist/chunk-0gx8he4p.js +0 -33
  74. package/dist/chunk-af944jrx.js +0 -2
  75. package/dist/chunk-q9w7sb6r.js +0 -2
  76. package/dist/chunk-qnyfg99e.js +0 -2
@@ -1,27 +1,34 @@
1
1
  import { STXBridge } from "../bridge/protocol.js";
2
+ import { createEventSourceClass, createStreamingBody } from "./event-stream.js";
3
+ import { abortError } from "./jsc-globals.js";
2
4
  function capabilityFlags(capabilities) {
3
5
  return {
4
6
  haptics: capabilities.has("haptics"),
5
7
  speechRecognition: !1,
6
- share: !1,
8
+ share: capabilities.has("share"),
7
9
  camera: !1,
8
10
  biometric: capabilities.has("biometric"),
9
- pushNotifications: !1,
11
+ pushNotifications: capabilities.has("push"),
10
12
  secureStorage: capabilities.has("secureStorage"),
11
13
  storage: capabilities.has("storage"),
12
14
  localDatabase: capabilities.has("database"),
13
15
  lifecycle: capabilities.has("lifecycle"),
14
- geolocation: !1,
16
+ geolocation: capabilities.has("geolocation"),
15
17
  clipboard: capabilities.has("clipboard"),
16
18
  contacts: !1,
17
19
  calendar: !1,
18
20
  localNotifications: capabilities.has("notifications"),
19
21
  inAppPurchase: !1,
20
- keepAwake: !1,
22
+ keepAwake: capabilities.has("keepAwake"),
23
+ brightness: capabilities.has("brightness"),
24
+ statusBar: capabilities.has("statusBar"),
21
25
  orientationLock: !1,
22
26
  deepLinks: capabilities.has("deepLinks"),
23
27
  flashlight: !1,
24
- speech: !1,
28
+ speech: capabilities.has("speech"),
29
+ audio: capabilities.has("audio"),
30
+ eventStream: capabilities.has("eventStream"),
31
+ linking: capabilities.has("linking"),
25
32
  network: !1,
26
33
  deviceInfo: capabilities.has("device"),
27
34
  fetch: capabilities.has("fetch"),
@@ -43,14 +50,31 @@ function platformUserAgent(platform) {
43
50
  export function installCraftBridge(protocol, nativeBridge, target = globalThis, options = {}) {
44
51
  const craft = target.craft = target.craft || {}, capabilities = new Set(nativeBridge.capabilities || []), request = (module, method, args) => protocol.callNativeAPI(module, method, ...args), ask = (module, method, args) => protocol.callPersonFacingAPI(module, method, ...args);
45
52
  let appState = nativeBridge.initialAppState || "active", initialDeepLinkClaimed = !1;
46
- const appStateHandlers = new Set, deepLinkHandlers = new Set, navButtonHandlers = new Set, navButtonPresses = new Map, routeName = options.routeName || "main", routeNames = options.routeNames || [routeName];
53
+ const appStateHandlers = new Set, deepLinkHandlers = new Set, navButtonHandlers = new Set, navButtonPresses = new Map, appearHandlers = new Set, disappearHandlers = new Set;
54
+ let focused = !0;
55
+ const routeName = options.routeName || "main", routeNames = options.routeNames || [routeName];
47
56
  craft.platform = nativeBridge.platform || "unknown";
48
57
  const navigatorObject = target.navigator = target.navigator || {};
49
58
  if (typeof navigatorObject.userAgent !== "string")
50
59
  navigatorObject.userAgent = platformUserAgent(craft.platform);
51
60
  craft.capabilityProtocolVersion = Number(nativeBridge.capabilityProtocolVersion || 0);
52
61
  craft.capabilities = capabilityFlags(capabilities);
62
+ const paramsHandlers = new Set;
53
63
  craft.route = { name: routeName, params: target.__stxNativeParams || {} };
64
+ Object.defineProperty(craft.route, "onParams", {
65
+ value: (callback) => {
66
+ if (typeof callback !== "function")
67
+ throw TypeError("route.onParams needs a function");
68
+ paramsHandlers.add(callback);
69
+ return () => paramsHandlers.delete(callback);
70
+ }
71
+ });
72
+ protocol.on("ROUTE_PARAMS", ({ payload }) => {
73
+ const previous = craft.route.params, params = payload?.params && typeof payload.params === "object" ? payload.params : {};
74
+ craft.route.params = params;
75
+ target.__stxNativeParams = params;
76
+ paramsHandlers.forEach((handler) => handler(params, previous));
77
+ });
54
78
  craft.appearance = { colorScheme: () => nativeBridge.colorScheme === "dark" ? "dark" : "light" };
55
79
  craft.device = { getInfo: () => request("Device", "getInfo", []) };
56
80
  craft.clipboard = {
@@ -121,6 +145,154 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
121
145
  craft.browser = { open: (url, options = {}) => ask("Browser", "open", [url, options]) };
122
146
  if (capabilities.has("appleSignIn"))
123
147
  craft.signInWithApple = (options = {}) => ask("Auth", "signInWithApple", [options]);
148
+ if (capabilities.has("linking")) {
149
+ craft.linking = {
150
+ openURL: (url) => request("Linking", "openURL", [String(url)]).then(Boolean),
151
+ canOpenURL: (url) => request("Linking", "canOpenURL", [String(url)]).then(Boolean)
152
+ };
153
+ craft.openURL = craft.linking.openURL;
154
+ }
155
+ if (capabilities.has("share")) {
156
+ const share = (options = {}) => ask("Share", "share", [options]).then(Boolean);
157
+ craft.share = Object.assign(share, { share });
158
+ }
159
+ if (capabilities.has("speech"))
160
+ craft.speech = {
161
+ speak: (text, options = {}) => {
162
+ if (typeof text !== "string" || !text.trim())
163
+ return Promise.reject(Object.assign(TypeError("speech.speak needs some text to say"), { code: "INVALID_ARGUMENT" }));
164
+ return ask("Speech", "speak", [text, options]).then((spoken) => spoken === !0);
165
+ },
166
+ stop: () => request("Speech", "stop", []).then(() => {
167
+ return;
168
+ })
169
+ };
170
+ if (capabilities.has("audio")) {
171
+ let nextSound = 0;
172
+ const soundHandlers = new Map, done = () => {
173
+ return;
174
+ }, handle = (id) => {
175
+ const handlers = { end: new Set, error: new Set };
176
+ soundHandlers.set(id, handlers);
177
+ return {
178
+ id,
179
+ pause: () => request("Audio", "pause", [id]).then(done),
180
+ resume: () => request("Audio", "resume", [id]).then(done),
181
+ stop: (options = {}) => request("Audio", "stop", [id, options]).then(done),
182
+ setVolume: (volume, options = {}) => request("Audio", "setVolume", [id, Number(volume), options]).then(done),
183
+ onEnd: (callback) => {
184
+ handlers.end.add(callback);
185
+ return () => handlers.end.delete(callback);
186
+ },
187
+ onError: (callback) => {
188
+ handlers.error.add(callback);
189
+ return () => handlers.error.delete(callback);
190
+ }
191
+ };
192
+ };
193
+ craft.audio = {
194
+ play: (url, options = {}) => {
195
+ if (typeof url !== "string" || !url)
196
+ return Promise.reject(TypeError("audio.play needs a URL"));
197
+ const id = `sound-${++nextSound}`, sound = handle(id);
198
+ return request("Audio", "play", [id, url, options]).then(() => sound, (error) => {
199
+ soundHandlers.delete(id);
200
+ throw error;
201
+ });
202
+ },
203
+ stopAll: (options = {}) => request("Audio", "stopAll", [options]).then(done)
204
+ };
205
+ protocol.on("SOUND_EVENT", ({ payload }) => {
206
+ const handlers = soundHandlers.get(String(payload?.id));
207
+ if (!handlers)
208
+ return;
209
+ soundHandlers.delete(String(payload?.id));
210
+ if (payload?.event === "ended")
211
+ handlers.end.forEach((handler) => handler());
212
+ else
213
+ handlers.error.forEach((handler) => handler(String(payload?.message || "The sound could not be played")));
214
+ });
215
+ }
216
+ if (capabilities.has("keepAwake"))
217
+ craft.setKeepAwake = (enabled) => request("KeepAwake", "set", [enabled !== !1]);
218
+ if (capabilities.has("brightness")) {
219
+ craft.getBrightness = () => request("Brightness", "get", []);
220
+ craft.setBrightness = (level) => request("Brightness", "set", [Number(level)]);
221
+ }
222
+ if (capabilities.has("statusBar"))
223
+ craft.statusBar = { setStyle: (style) => request("StatusBar", "setStyle", [style]) };
224
+ if (capabilities.has("geolocation")) {
225
+ const watchers = new Map;
226
+ let nextWatch = 0;
227
+ const unwatched = () => {
228
+ if (watchers.size === 0)
229
+ request("Location", "clearWatch", []).catch(() => {});
230
+ };
231
+ craft.location = {
232
+ getCurrentPosition: (options = {}) => ask("Location", "getCurrentPosition", [options]),
233
+ watchPosition: (callback, options = {}) => {
234
+ if (typeof callback !== "function")
235
+ throw TypeError("location.watchPosition needs a function");
236
+ const id = ++nextWatch, first = watchers.size === 0;
237
+ watchers.set(id, callback);
238
+ if (first)
239
+ ask("Location", "watchPosition", [options]).catch(() => {});
240
+ return id;
241
+ },
242
+ clearWatch: (id) => {
243
+ if (id === void 0)
244
+ watchers.clear();
245
+ else if (!watchers.delete(id))
246
+ return;
247
+ unwatched();
248
+ },
249
+ startRecording: (options = {}) => ask("Location", "startRecording", [options]),
250
+ pauseRecording: () => request("Location", "pauseRecording", []),
251
+ resumeRecording: () => request("Location", "resumeRecording", []),
252
+ stopRecording: () => request("Location", "stopRecording", []),
253
+ getRecordingState: () => request("Location", "getRecordingState", []),
254
+ readRecording: () => request("Location", "readRecording", [])
255
+ };
256
+ target.addEventListener?.("craftLocationUpdate", (event) => {
257
+ watchers.forEach((callback) => callback(event?.detail));
258
+ });
259
+ }
260
+ protocol.on("CRAFT_EVENT", ({ payload }) => {
261
+ if (typeof payload?.event !== "string" || typeof target.dispatchEvent !== "function" || typeof target.CustomEvent !== "function")
262
+ return;
263
+ target.dispatchEvent(new target.CustomEvent(payload.event, { detail: payload.detail ?? {} }));
264
+ });
265
+ if (capabilities.has("push")) {
266
+ const tokenHandlers = new Set;
267
+ craft.push = {
268
+ getPermissionStatus: () => request("Push", "getPermissionStatus", []),
269
+ requestPermission: () => ask("Push", "requestPermission", []),
270
+ register: () => ask("Push", "register", []).then(String),
271
+ onToken: (callback) => {
272
+ if (typeof callback !== "function")
273
+ throw TypeError("push.onToken needs a function");
274
+ tokenHandlers.add(callback);
275
+ return () => tokenHandlers.delete(callback);
276
+ },
277
+ openSettings: () => request("Push", "openSettings", []).then(Boolean)
278
+ };
279
+ craft.registerPush = craft.push.register;
280
+ craft.permissions = Object.assign({}, craft.permissions, {
281
+ check: (permission) => permission === "notifications" ? craft.push.getPermissionStatus() : Promise.resolve("undetermined"),
282
+ request: (permission) => permission === "notifications" ? craft.push.requestPermission() : Promise.resolve("undetermined"),
283
+ openSettings: () => craft.push.openSettings().then(() => {
284
+ return;
285
+ })
286
+ });
287
+ protocol.on("PUSH_TOKEN", ({ payload }) => {
288
+ const token = String(payload?.token || "");
289
+ if (!token)
290
+ return;
291
+ tokenHandlers.forEach((handler) => handler(token));
292
+ if (typeof target.dispatchEvent === "function" && typeof target.CustomEvent === "function")
293
+ target.dispatchEvent(new target.CustomEvent("craftPushToken", { detail: { token } }));
294
+ });
295
+ }
124
296
  if (capabilities.has("health"))
125
297
  craft.health = {
126
298
  requestAuthorization: (types, options = {}) => ask("Health", "requestAuthorization", [types, options]),
@@ -173,7 +345,24 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
173
345
  throw TypeError("navigation.onButton needs a function");
174
346
  navButtonHandlers.add(callback);
175
347
  return () => navButtonHandlers.delete(callback);
176
- }
348
+ },
349
+ onAppear: (callback) => {
350
+ if (typeof callback !== "function")
351
+ throw TypeError("navigation.onAppear needs a function");
352
+ appearHandlers.add(callback);
353
+ return () => appearHandlers.delete(callback);
354
+ },
355
+ onDisappear: (callback) => {
356
+ if (typeof callback !== "function")
357
+ throw TypeError("navigation.onDisappear needs a function");
358
+ disappearHandlers.add(callback);
359
+ return () => disappearHandlers.delete(callback);
360
+ },
361
+ isFocused: () => focused
362
+ });
363
+ protocol.on("SCREEN_FOCUS", ({ payload }) => {
364
+ focused = payload?.focused !== !1;
365
+ (focused ? appearHandlers : disappearHandlers).forEach((handler) => handler());
177
366
  });
178
367
  const onAppStateChange = (callback) => {
179
368
  if (typeof callback !== "function")
@@ -217,6 +406,57 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
217
406
  if (payload?.handlerId === "navButton" || payload?.handlerName === "navButton")
218
407
  dispatchNavButton(payload.nativeEvent || {});
219
408
  });
409
+ const streaming = capabilities.has("eventStream"), streamSinks = new Map;
410
+ let nextStream = 0;
411
+ if (streaming)
412
+ protocol.on("NETWORK_STREAM", ({ payload }) => {
413
+ const sink = streamSinks.get(String(payload?.id));
414
+ if (!sink)
415
+ return;
416
+ if (typeof payload.chunk === "string")
417
+ return sink.push(payload.chunk);
418
+ streamSinks.delete(String(payload.id));
419
+ if (payload.error)
420
+ sink.fail(payload.error);
421
+ else
422
+ sink.end();
423
+ });
424
+ const streamingFetch = (url, method, headers, body, signal) => {
425
+ const id = `stream-${++nextStream}`, encoder = new target.TextEncoder;
426
+ let settled = !1;
427
+ const stream = createStreamingBody((text) => encoder.encode(text), () => {
428
+ streamSinks.delete(id);
429
+ request("Network", "cancelStream", [id]).catch(() => {});
430
+ });
431
+ streamSinks.set(id, stream.sink);
432
+ return new Promise((resolve, reject) => {
433
+ signal?.addEventListener?.("abort", () => {
434
+ stream.body.cancel();
435
+ if (!settled) {
436
+ settled = !0;
437
+ reject(abortError(signal.reason));
438
+ }
439
+ });
440
+ request("Network", "stream", [{ id, url, method, headers, body }]).then((data) => {
441
+ if (settled)
442
+ return;
443
+ settled = !0;
444
+ resolve(response(data, { get bodyUsed() {
445
+ return stream.used();
446
+ }, text: stream.text, body: stream.body }));
447
+ }, (error) => {
448
+ streamSinks.delete(id);
449
+ if (settled)
450
+ return;
451
+ settled = !0;
452
+ try {
453
+ networkFailure(error);
454
+ } catch (failure) {
455
+ reject(failure);
456
+ }
457
+ });
458
+ });
459
+ };
220
460
  if (capabilities.has("fetch") && typeof target.fetch !== "function")
221
461
  target.fetch = (input, init = {}) => {
222
462
  const source = input && typeof input === "object" ? input : {}, url = typeof input === "string" ? input : String(source.url || input), method = String(init.method || source.method || "GET").toUpperCase(), headers = {}, inputHeaders = init.headers || source.headers, addHeader = (name, value) => {
@@ -233,40 +473,57 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
233
473
  return Promise.reject(TypeError("fetch in a native screen sends string bodies only"));
234
474
  if (body != null && (method === "GET" || method === "HEAD"))
235
475
  return Promise.reject(TypeError("A GET or HEAD request cannot have a body"));
236
- return request("Network", "fetch", [{ url, method, headers, body: body == null ? null : body }]).then((data) => {
237
- const responseHeaders = data?.headers && typeof data.headers === "object" ? data.headers : {}, responseBody = data?.body == null ? "" : String(data.body);
476
+ const signal = init.signal || source.signal;
477
+ if (signal?.aborted)
478
+ return Promise.reject(abortError(signal.reason));
479
+ if (streaming && /text\/event-stream/i.test(headers.accept || ""))
480
+ return streamingFetch(url, method, headers, body == null ? null : body, signal);
481
+ const answer = request("Network", "fetch", [{ url, method, headers, body: body == null ? null : body }]).then((data) => {
482
+ const responseBody = data?.body == null ? "" : String(data.body);
238
483
  let bodyUsed = !1;
239
- const consume = () => {
484
+ return response(data, { get bodyUsed() {
485
+ return bodyUsed;
486
+ }, text: () => {
240
487
  if (bodyUsed)
241
488
  return Promise.reject(TypeError("Body has already been consumed"));
242
489
  bodyUsed = !0;
243
490
  return Promise.resolve(responseBody);
244
- };
245
- return {
246
- type: "basic",
247
- url: data?.url || "",
248
- status: Number(data?.status) || 0,
249
- statusText: data?.statusText || "",
250
- ok: Number(data?.status) >= 200 && Number(data?.status) < 300,
251
- redirected: Boolean(data?.redirected),
252
- headers: {
253
- get: (name) => responseHeaders[String(name).toLowerCase()] == null ? null : String(responseHeaders[String(name).toLowerCase()]),
254
- has: (name) => responseHeaders[String(name).toLowerCase()] != null,
255
- forEach: (callback) => Object.keys(responseHeaders).forEach((name) => callback(String(responseHeaders[name]), name))
256
- },
257
- get bodyUsed() {
258
- return bodyUsed;
259
- },
260
- text: consume,
261
- json: () => consume().then(JSON.parse)
262
- };
263
- }, (error) => {
264
- if (error?.code === "INVALID_ARGUMENT")
265
- throw error;
266
- const failure = TypeError(error?.message || "Network request failed");
267
- failure.code = error?.code || "NETWORK_ERROR";
268
- throw failure;
269
- });
491
+ } });
492
+ }, networkFailure);
493
+ return signal ? Promise.race([answer, aborted(signal)]) : answer;
270
494
  };
495
+ if (streaming && typeof target.fetch === "function" && typeof target.EventSource !== "function")
496
+ target.EventSource = createEventSourceClass(target);
271
497
  return craft;
272
498
  }
499
+ function aborted(signal) {
500
+ return new Promise((_, reject) => signal.addEventListener?.("abort", () => reject(abortError(signal.reason))));
501
+ }
502
+ function networkFailure(error) {
503
+ if (error?.code === "INVALID_ARGUMENT")
504
+ throw error;
505
+ const failure = TypeError(error?.message || "Network request failed");
506
+ failure.code = error?.code || "NETWORK_ERROR";
507
+ throw failure;
508
+ }
509
+ function response(data, reading) {
510
+ const responseHeaders = data?.headers && typeof data.headers === "object" ? data.headers : {}, result = {
511
+ type: "basic",
512
+ url: data?.url || "",
513
+ status: Number(data?.status) || 0,
514
+ statusText: data?.statusText || "",
515
+ ok: Number(data?.status) >= 200 && Number(data?.status) < 300,
516
+ redirected: Boolean(data?.redirected),
517
+ headers: {
518
+ get: (name) => responseHeaders[String(name).toLowerCase()] == null ? null : String(responseHeaders[String(name).toLowerCase()]),
519
+ has: (name) => responseHeaders[String(name).toLowerCase()] != null,
520
+ forEach: (callback) => Object.keys(responseHeaders).forEach((name) => callback(String(responseHeaders[name]), name))
521
+ },
522
+ text: reading.text,
523
+ json: () => reading.text().then(JSON.parse)
524
+ };
525
+ Object.defineProperty(result, "bodyUsed", { enumerable: !0, get: () => reading.bodyUsed });
526
+ if (reading.body)
527
+ result.body = reading.body;
528
+ return result;
529
+ }
@@ -36,6 +36,47 @@ export declare interface NativeNavigation {
36
36
  open: (path: string) => string
37
37
  setOptions: (options: NativeNavigationOptions) => unknown
38
38
  onButton: (callback: (event: { id: string }) => unknown) => () => void
39
+ onAppear: (callback: () => unknown) => () => void
40
+ onDisappear: (callback: () => unknown) => () => void
41
+ isFocused: () => boolean
42
+ }
43
+ export declare interface NativeRoute {
44
+ name: string
45
+ params: Record<string, unknown>
46
+ onParams: (callback: (params: Record<string, unknown>, previous: Record<string, unknown>) => unknown) => () => void
47
+ }
48
+ /** A sound `craft.audio.play` started. */
49
+ export declare interface NativeSound {
50
+ id: string
51
+ pause: () => Promise<void>
52
+ resume: () => Promise<void>
53
+ stop: (options?: { fadeOut?: number }) => Promise<void>
54
+ setVolume: (volume: number, options?: { fade?: number }) => Promise<void>
55
+ onEnd: (callback: () => unknown) => () => void
56
+ onError: (callback: (message: string) => unknown) => () => void
57
+ }
58
+ export declare interface NativeLocation {
59
+ latitude: number
60
+ longitude: number
61
+ altitude?: number
62
+ accuracy?: number
63
+ altitudeAccuracy?: number
64
+ heading?: number
65
+ speed?: number
66
+ timestamp: number
67
+ }
68
+ export declare interface NativeLocationRecordingState {
69
+ id: string | null
70
+ active: boolean
71
+ paused: boolean
72
+ startedAt: number | null
73
+ }
74
+ export declare interface NativeShareOptions {
75
+ title?: string
76
+ text?: string
77
+ url?: string
78
+ files?: string[]
79
+ image?: string
39
80
  }
40
81
  export declare interface NativeStorage {
41
82
  get: <T = unknown>(key: string) => Promise<T | null>
@@ -62,7 +103,7 @@ export declare interface NativeSnapshots {
62
103
  export declare interface NativeCraft {
63
104
  platform: string
64
105
  capabilityProtocolVersion: number
65
- route: { name: string, params: Record<string, unknown> }
106
+ route: NativeRoute
66
107
  capabilities: Record<string, boolean>
67
108
  navigation: NativeNavigation
68
109
  storage: NativeStorage
@@ -98,6 +139,48 @@ export declare interface NativeCraft {
98
139
  confirm: (options?: { title?: string, message?: string, confirmLabel?: string, cancelLabel?: string, destructive?: boolean }) => Promise<boolean>
99
140
  actionSheet: (options?: { title?: string, message?: string, actions?: Array<{ id?: string, title: string, style?: 'default' | 'destructive' | 'cancel' }> }) => Promise<string | null>
100
141
  }
142
+ speech?: {
143
+ speak: (text: string, options?: { language?: string, rate?: number, interrupt?: boolean }) => Promise<boolean>
144
+ stop: () => Promise<void>
145
+ }
146
+ audio?: {
147
+ play: (url: string, options?: { loop?: boolean, volume?: number, fadeIn?: number, respectSilentSwitch?: boolean }) => Promise<NativeSound>
148
+ stopAll: (options?: { fadeOut?: number }) => Promise<void>
149
+ }
150
+ push?: {
151
+ getPermissionStatus: () => Promise<NativePermissionStatus>
152
+ requestPermission: () => Promise<NativePermissionStatus>
153
+ register: () => Promise<string>
154
+ onToken: (callback: (token: string) => unknown) => () => void
155
+ openSettings: () => Promise<boolean>
156
+ }
157
+ registerPush?: () => Promise<string>
158
+ permissions?: {
159
+ check: (permission: string) => Promise<NativePermissionStatus>
160
+ request: (permission: string) => Promise<NativePermissionStatus>
161
+ openSettings: () => Promise<void>
162
+ }
163
+ linking?: {
164
+ openURL: (url: string) => Promise<boolean>
165
+ canOpenURL: (url: string) => Promise<boolean>
166
+ }
167
+ openURL?: (url: string) => Promise<boolean>
168
+ share?: ((options: NativeShareOptions) => Promise<boolean>) & { share: (options: NativeShareOptions) => Promise<boolean> }
169
+ location?: {
170
+ getCurrentPosition: (options?: { enableHighAccuracy?: boolean, timeout?: number, maximumAge?: number }) => Promise<NativeLocation>
171
+ watchPosition: (callback: (location: NativeLocation) => unknown, options?: Record<string, unknown>) => number
172
+ clearWatch: (id?: number) => void
173
+ startRecording: (options?: Record<string, unknown>) => Promise<NativeLocationRecordingState>
174
+ pauseRecording: () => Promise<NativeLocationRecordingState>
175
+ resumeRecording: () => Promise<NativeLocationRecordingState>
176
+ stopRecording: () => Promise<NativeLocationRecordingState & { locations: NativeLocation[] }>
177
+ getRecordingState: () => Promise<NativeLocationRecordingState & { sampleCount: number }>
178
+ readRecording: () => Promise<NativeLocation[]>
179
+ }
180
+ setKeepAwake?: (enabled: boolean) => Promise<boolean>
181
+ getBrightness?: () => Promise<number>
182
+ setBrightness?: (level: number) => Promise<number>
183
+ statusBar?: { setStyle: (style: 'light' | 'dark' | 'default') => Promise<boolean> }
101
184
  health?: {
102
185
  requestAuthorization: (types: string[], options?: { write?: boolean }) => Promise<boolean>
103
186
  getData: (type: string, options?: { startDate?: number, endDate?: number }) => Promise<unknown>
@@ -121,3 +204,4 @@ export declare interface NativeCraft {
121
204
  }
122
205
  deepLinks: { getInitialURL: () => Promise<string | null>, onLink: (callback: (link: unknown) => unknown) => () => void }
123
206
  }
207
+ export type NativePermissionStatus = 'granted' | 'denied' | 'undetermined';
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A `response.body` fed by `sink`. `cancel` tells the host to stop sending;
3
+ * it runs once, whichever way the reader stops.
4
+ */
5
+ export declare function createStreamingBody(encode: (text: string) => Uint8Array, cancel: () => void): { body: AnyRecord, sink: StreamSink, text: () => Promise<string>, used: () => boolean };
6
+ /**
7
+ * `EventSource`, on the streaming `fetch`. Standard but for one addition the
8
+ * browser's lacks: `new EventSource(url, { headers })`, since a native screen
9
+ * signs its requests with a token rather than a cookie.
10
+ */
11
+ export declare function createEventSourceClass(target: AnyRecord): AnyRecord;
12
+ /** Where the host's pieces go: in order, then the end or a failure. */
13
+ export declare interface StreamSink {
14
+ push: (text: string) => void
15
+ end: () => void
16
+ fail: (message: string) => void
17
+ }
18
+ /**
19
+ * Responses read as they arrive, on a native screen.
20
+ *
21
+ * A native screen's `fetch` is one request to the host and one answer, which
22
+ * is no use for a server-sent event stream: the answer never ends. A request
23
+ * that accepts `text/event-stream` goes to the host's `Network.stream`
24
+ * instead (when it advertises `eventStream`). The host answers with the head,
25
+ * then sends every piece of the body as it comes (`NETWORK_STREAM`). Here the
26
+ * pieces become a `response.body` reader, which is all the web's stream
27
+ * readers use (`@stacksjs/stx`'s `useBroadcastStream`), and an `EventSource`
28
+ * on top of that, which can send headers (a bearer token) as the browser's
29
+ * cannot.
30
+ */
31
+ declare type AnyRecord = Record<string, any> // eslint-disable-line ts/no-explicit-any;