portaki_sdk/lib.rs
1//! # Portaki module SDK
2//!
3//! Authoring toolkit for Wasm modules executed by the Portaki gateway. This crate
4//! is the **module-side contract**: typed wrappers around host imports, SDUI
5//! primitives, capability identifiers, invocation context, and proc-macros that
6//! emit `manifest.json` fragments at compile time.
7//!
8//! ## What the host guarantees
9//!
10//! - Every query, command, and surface invocation receives a fully populated
11//! [`Context`] (property, plan, locale, effective capabilities, correlation id).
12//! - Host functions (`host::kv`, `host::repo`, `host::connectors`, …) are routed
13//! through the gateway — modules never talk to Postgres, Redis, or third-party
14//! APIs directly.
15//! - Capability grants reflected in `Context::capabilities` are authoritative for
16//! the current invocation; optional manifest capabilities may be absent.
17//!
18//! ## What modules must not assume
19//!
20//! - **Secrets in Wasm**: never embed API keys. Use [`host::connectors`] for egress
21//! (the gateway injects pool/BYOK secrets at the boundary).
22//! - **Raw HTTP / SQL**: blocked by platform policy; use connectors and `host::repo`.
23//! - **Cross-invocation memory**: Wasm instances are ephemeral — persist via
24//! `host::kv` or entity storage.
25//! - **Synchronous side effects**: host calls may fail (`PortakiError`); surface
26//! renderers should degrade gracefully when optional capabilities are missing.
27//!
28//! ## Typical authoring path
29//!
30//! 1. Declare the module with `portaki_module!` and register surfaces/queries/commands
31//! via proc-macros (`surface!`, `query!`, `command!`, …).
32//! 2. Declare the host settings on a struct with `#[portaki_sdk::config]` and read them with
33//! its generated `load(&ctx)` — the platform stores, validates and gates publication on
34//! them (see [`mod@config`]).
35//! 3. Import [`prelude`] in handler modules.
36//! 4. Return [`Surface`] trees from render functions; call `host::*` for storage,
37//! connectors, and logging.
38//! 5. Gate premium behaviour with `ctx.has_capability(...)` or
39//! [`mod@capability`] constants.
40//! 6. Prefer [`ids`] newtypes and [`contracts`] for cross-boundary names
41//! (surfaces, commands, events, peer ops) instead of free string literals.
42//! 7. Keep Wasm crate folders strict: `guest/` / `host/` / `connectors` / `ids`
43//! (see repo `docs/module-layout.md`).
44//!
45//! ## Wasm target
46//!
47//! On `wasm32`, see [`wasm`] for Extism entry points (`portaki_query`,
48//! `portaki_command`) and the `portaki_host_dispatch` ABI.
49
50#![deny(missing_docs)]
51
52pub mod capability;
53pub mod config;
54pub mod context;
55pub mod contracts;
56pub mod deprecation;
57pub mod email;
58pub mod error;
59pub mod files;
60pub mod guest_shell;
61pub mod host;
62pub mod ids;
63#[doc(hidden)]
64pub mod layout;
65pub mod limits;
66pub mod manifest;
67pub mod permission;
68#[cfg(feature = "unstable")]
69pub mod resource;
70pub mod reveal;
71pub mod sdui;
72pub mod surfaces;
73pub mod vocab;
74
75pub mod wasm;
76
77/// The version of this SDK, as compiled into the crate.
78///
79/// Tooling reports it alongside its own version so a developer can see, from the
80/// outside, which SDK a build was produced against — the CLI and the SDK are
81/// released together but a module crate may pin an older one.
82pub const VERSION: &str = env!("CARGO_PKG_VERSION");
83
84/// The SDUI primitive catalogue this SDK generates its components from.
85///
86/// The same file `build.rs` reads, carried into the binary: a tool that wants to know what the
87/// host can render — `portaki catalog` — should ask the SDK it was linked against, not a path
88/// in a source tree it may not have.
89pub const SDUI_PRIMITIVES_JSON: &str = include_str!("../sdui_primitives.json");
90
91/// Re-export for `inventory::submit!` in wasm handler registration (macro-generated).
92///
93/// Module authors do not call this directly — `query!` / `command!` / `surface!`
94/// shims submit [`wasm::HandlerRegistration`] entries at link time.
95pub use inventory;
96
97/// Links the module crate under test into an integration test binary — `extern crate <lib> as _;`.
98///
99/// Not for module authors: `portaki_test_utils::conformance!` expands to it. A test binary only
100/// links the crates it names, and handler declarations of a crate that is not linked are invisible.
101#[doc(hidden)]
102pub use portaki_sdk_macros::link_module_crate as __link_module_crate;
103
104pub use capability::CapabilityId;
105pub use context::{
106 Context, DisplayPreferences, GuestContext, GuestIdentity, HostContext, PlanInfo,
107 PropertyContext, Quota, StayContext,
108};
109#[allow(deprecated)]
110pub use email::EmailContextContribution;
111pub use email::{
112 BlockRow, BlockTone, BlockType, EmailBlock, EmailBlocks, EmailContextArgs, EmailTemplateKey,
113 EmailVar, EmailVars,
114};
115pub use error::{PortakiError, Result};
116pub use ids::{EventType, FragmentId, ModuleId, OperationName, SurfaceId};
117pub use portaki_sdk_macros::{
118 bundle_text, capability, command, config, connector, connector_op, custom_connector, email,
119 email_blocks, email_vars, entity, entity_indexes, event_handler, nav, params,
120 portaki_module_decl as portaki_module, query, surface, wire,
121};
122#[cfg(feature = "unstable")]
123pub use portaki_sdk_macros::{choice, collection, item, record};
124pub use sdui::{
125 action::{json_value, Action, EmptyArgs, NavigateTarget, OverlayArgs, OverlayPresentation},
126 component::Component,
127 surface::Surface,
128};
129
130/// Commonly used imports for module handler code.
131///
132/// Pull this in once per module crate (`use portaki_sdk::prelude::*;`) to get
133/// context types, host namespaces, SDUI root types, proc-macros, and utility macros.
134///
135/// # Examples
136///
137/// ```ignore
138/// use portaki_sdk::prelude::*;
139/// use portaki_sdk::sdui::primitives::{Card, Stack, Text};
140///
141/// #[surface(guest, id = "home.card")]
142/// fn render_home(ctx: GuestContext) -> Surface {
143/// if !ctx.has_capability(capability::core::STORAGE) {
144/// return Surface::new(Text::new().text("i18n:capability.missing"));
145/// }
146/// log_info!("rendering home", surface = "home.card");
147/// Surface::new(Card::new().child(Stack::new().child(Text::new())))
148/// }
149/// ```
150pub mod prelude {
151 pub use crate::capability::{self, CapabilityId};
152 pub use crate::context::{Context, GuestContext, HostContext, StayContext};
153 pub use crate::contracts;
154 pub use crate::email::{
155 BlockTone, BlockType, EmailBlock, EmailBlocks, EmailContextArgs, EmailTemplateKey,
156 EmailVar, EmailVars,
157 };
158 pub use crate::error::{PortakiError, Result};
159 pub use crate::host;
160 pub use crate::host::email::EmailAudience;
161 pub use crate::ids::{self, EventType, FragmentId, ModuleId, OperationName, SurfaceId};
162 pub use crate::sdui::action::{
163 json_value, Action, EmptyArgs, NavigateTarget, OverlayArgs, OverlayPresentation,
164 };
165 pub use crate::sdui::common::{
166 ButtonVariant, CalendarDay, CalendarItem, ChartEmpty, ChartKind, ChartPoint,
167 ChoiceListLayout, ChoiceOption, DeltaTone, Emphasis, GeoPoint, ImageSize,
168 MapInteractionMode, MapMarker, MapMarkerKind, MapViewport, StackDirection, Swatch,
169 TempVariant, TemperatureUnit, TextVariant, Tone,
170 };
171 pub use crate::sdui::component::Component;
172 pub use crate::sdui::surface::Surface;
173 pub use crate::vocab::{
174 DesignId, EmailTrigger, GuestRole, HostFragmentId, HostPlacement, IconName, Maturity,
175 ModuleAudience, ModuleType, SkipWhen, Vocabulary,
176 };
177 pub use crate::{
178 bundle_text, command, connector, connector_op, custom_connector, define_event_types,
179 email_vars, entity, entity_indexes, event_handler, portaki_module, query, surface, wire,
180 };
181 #[allow(deprecated)]
182 pub use crate::{define_operation_names, define_surface_ids};
183 pub use crate::{log_info, t};
184 pub use chrono::{DateTime, Utc};
185 pub use serde::{Deserialize, Serialize};
186 pub use uuid::Uuid;
187}
188
189/// Resolves an i18n key through the host translation service.
190///
191/// Expands to [`host::i18n::translate`] with an empty or interpolated [`host::i18n::Vars`]
192/// map. The active locale comes from the invocation [`Context`] — do not hard-code
193/// locale strings in module UI copy.
194///
195/// Returns [`Result<String>`](crate::error::Result) because the host backend may be
196/// unavailable in unit tests without [`host::runtime::with_host`].
197///
198/// # Examples
199///
200/// ```no_run
201/// # use portaki_sdk::t;
202/// let title = t!("module.home.title")?;
203/// let greeting = t!("module.greeting", name = "Marie")?;
204/// # Ok::<(), portaki_sdk::PortakiError>(())
205/// ```
206#[macro_export]
207macro_rules! t {
208 ($key:expr) => {
209 $crate::host::i18n::translate($key, &$crate::host::i18n::Vars::new())
210 };
211 ($key:expr, $($name:ident = $value:expr),+ $(,)?) => {{
212 let mut vars = $crate::host::i18n::Vars::new();
213 $( vars.set(stringify!($name), $value); )+
214 $crate::host::i18n::translate($key, &vars)
215 }};
216}
217
218/// Emits a structured `info`-level log line to platform observability.
219///
220/// Field keys are taken from identifier tokens (`user_id = id` → `"user_id"`).
221/// Values must implement `Serialize`. Prefer stable, low-cardinality field names
222/// so logs aggregate cleanly in the gateway pipeline.
223///
224/// Silently no-ops field insertion when serialization fails for a single value.
225///
226/// # Examples
227///
228/// ```no_run
229/// # use portaki_sdk::log_info;
230/// log_info!("weather cache refreshed", property_id = "abc", ttl_secs = 300);
231/// ```
232#[macro_export]
233macro_rules! log_info {
234 ($msg:expr $(, $key:ident = $value:expr)*) => {
235 {
236 let mut fields = $crate::host::log::Fields::new();
237 $( fields.insert(stringify!($key), &$value); )*
238 $crate::host::log::info($msg, &fields);
239 }
240 };
241}