GitHub快速开始

API 参考取自源码中的 Go 文档注释,以英文书写。

package liveops

import "github.com/nsgo-dev/game/pkg/online/liveops"

概述

Package liveops holds provider-agnostic live operations primitives for NSGo games: crash reports, consent-gated analytics, a cloud-save sync interface, in-app purchases credited into the save, local re-engagement reminders, store review prompt policies, and share cards and payload-carrying invites. It links no third-party analytics, crash-reporting, ad, push or payment SDKs.

Scope (#194)

In scope for the core game module:

  • Crash reports (#195): panic recovery around game.Loop and arbitrary callbacks, with a fixed-size step ring buffer, stack trace, metadata and an optional state snapshot handed to the app's reporter.
  • Analytics (#198): a provider-agnostic, strictly opt-in event API whose consent state persists in core.Storage. Zero events are sent or buffered before explicit ConsentGranted.
  • Cloud saves (#196): the provider-agnostic CloudSync interface, PlatformCloud over NSGo's cloud package (iCloud on macOS/iOS, Google Play Games Saved Games on Android, and the in-memory store in nsgotest), DirCloud for Steam Auto-Cloud and other directory-synced stores, CloudClient (#557) for the self-hosted cloudsave service, and CloudSyncer (#539), which detects slots changed on two devices and resolves them by policy without silently losing either copy.
  • In-app purchases (#369): Purchases over NSGo's purchase services, which credits consumables into the save exactly once through a Ledger saved with them, keeps unlocks and subscriptions from the store's entitlements, restores them, follows purchases waiting for approval and hands transactions to an optional server before delivering them.
  • Local reminders (#1310): Reminders over NSGo's core.Scope.ShowNotification, declared in versioned YAML (RemindersConfig), asking permission only on first Schedule or explicit RequestPermission, honoring a persisted player setting and local-time QuietHours, and cancelling or rescheduling active reminders when the app comes to the front.
  • Store review prompts (#1767): ReviewPrompt over core.Storage and core.Scope.RequestReview, gating in-app rating prompts on minimum sessions, days since first launch, positive moments, cooldown and once-per-version rules, suppressing prompts after negative moments, and failing closed on corrupt state or unsupported platforms.
  • Share cards and invites (#1738): Invites over a small ShareHost interface (PlatformShareHost for mobile, desktop and web via core.Scope.Share, core.Scope.OnOpenLinks and core.Scope.AppURL, plus MiniGameShareHost ready for NSGo's mini-game share cards in nsgo-dev/nsgo#2672), with bounded canonical key=value payloads, optional HMAC-SHA256 signing and verification, at-most-once cold-launch and warm-resume delivery, and a 5:4 frame snapshot helper.

Pending upstream:

  • Remote push (#1310): a thin Push wrapper for device-token registration and remote payload routing waits on NSGo shipping remote push (nsgo-dev/nsgo#59) and settling its design decisions (nsgo-dev/nsgo#1323). Until then, remote push is unavailable everywhere.

Out of scope for the core game module:

  • Ads (#199): ad networks (AdMob, AppLovin and similar) require proprietary native SDKs with store-policy and privacy obligations that do not belong in the core game layer. Games that show ads embed native SDK views directly through NSGo.

索引

常量

const (
	// DefaultMaxInvitePayloadBytes is the default maximum byte length of an encoded invite query string.
	// It fits comfortably within mini-game share query limits (such as WeChat's shareAppMessage query) as well as mobile deep-link and web URLs.
	DefaultMaxInvitePayloadBytes = 1024

	// MaxInvitePayloadKeys bounds the number of key-value pairs in a single invite payload (excluding the optional signature field).
	MaxInvitePayloadKeys = 32

	// MaxInviteKeyBytes bounds the length of an individual invite payload key in bytes.
	MaxInviteKeyBytes = 64

	// MaxInviteSignatureBytes bounds the length of an encoded signature field in bytes.
	MaxInviteSignatureBytes = 128

	// InviteIDKey is the standard payload key carrying the unique invite identifier used as a server reward-grant idempotency key.
	InviteIDKey = "id"

	// InviteSigKey is the reserved payload key carrying the optional base64url raw HMAC-SHA256 signature.
	InviteSigKey = "sig"
)
const (
	// CardSnapshotAspectWidth and CardSnapshotAspectHeight define the 5:4 aspect ratio used by mini-game share cards.
	CardSnapshotAspectWidth  = 5
	CardSnapshotAspectHeight = 4

	// DefaultCardSnapshotWidth and DefaultCardSnapshotHeight are the default 5:4 share-card snapshot dimensions in pixels.
	DefaultCardSnapshotWidth  = 500
	DefaultCardSnapshotHeight = 400
)
const (
	// DefaultReviewPromptKey is the core.Storage key under which ReviewPrompt persists its versioned JSON state when ReviewPromptOptions.StorageKey is empty.
	DefaultReviewPromptKey = "liveops.review_prompt"

	// ReviewPromptStateVersion is the schema version of the JSON state persisted by ReviewPrompt.
	ReviewPromptStateVersion = 1

	// DefaultReviewMinSessions is the default minimum number of sessions before MaybeAsk may request a review.
	DefaultReviewMinSessions = 3

	// DefaultReviewMinDays is the default minimum number of days since first launch before MaybeAsk may request a review.
	DefaultReviewMinDays = 3

	// DefaultReviewMinPositiveMoments is the default minimum number of positive moments in the current app version before MaybeAsk may request a review.
	DefaultReviewMinPositiveMoments = 3

	// DefaultReviewCooldown is the default minimum duration between review requests across app versions.
	// 122 days ensures at most three prompts in any rolling 365-day window, staying within Apple's StoreKit limit.
	DefaultReviewCooldown = 122 * 24 * time.Hour
)
const CloudSaveFormat = "nsgo-cloud-save"

CloudSaveFormat is the "format" value that marks a cloud payload written by CloudSyncer. A payload without it is read as a plain save written by a game that used CloudSync directly, at revision 0.

const CloudSaveVersion = 1

CloudSaveVersion is the schema version of the cloud payload CloudSyncer writes and the newest one it reads.

const DefaultCloudPrefix = "save."

DefaultCloudPrefix is the file-name prefix PlatformCloud prepends to each save slot when PlatformCloudOptions.Prefix is empty, storing slot "main" as "save.main.json". A flat dot-separated name without slashes works in both Apple iCloud ubiquity containers and Google Play Games Saved Games snapshots, and keeps save slots separate from other files in the container.

const DefaultConsentKey = "liveops.analytics.consent"

DefaultConsentKey is the core.Storage key used by NewAnalytics when key is empty.

const DefaultHistorySize = 120

DefaultHistorySize is the number of recent steps a CrashReporter keeps when CrashOptions.HistorySize is 0 or negative.

const DefaultReminderPrefix = "liveops.reminder:"

DefaultReminderPrefix is the prefix Reminders prepends to reminder IDs passed to core.Scope.ShowNotification when RemindersOptions.Prefix is empty, keeping reminder notifications separate from the app's other notifications.

const DefaultRemindersKey = "liveops.reminders"

DefaultRemindersKey is the core.Storage key prefix under which Reminders persists the player's enabled setting, custom quiet hours and active reminder IDs when RemindersOptions.StorageKey is empty.

const DefaultSyncStateKey = "liveops.cloudsync"

DefaultSyncStateKey is the core.Storage key prefix under which CloudSyncer keeps each slot's sync state when CloudSyncOptions.StateKey is empty.

const LedgerLimit = 1024

LedgerLimit is how many transaction IDs each list of a Ledger keeps; the oldest are dropped past it to bound the save's size. A store hands a game only its unfinished transactions again, and a finished transaction is never far back in the list, so no credit repeats. A refund, though, can come weeks after its purchase: one whose ID has been dropped, after LedgerLimit newer consumables were credited, is finished without running Revoke.

const RemindersSchemaComment = "# yaml-language-server: $schema=" + RemindersSchemaURL

RemindersSchemaComment is the first line EncodeReminders writes: a YAML comment pointing a YAML language server at RemindersSchemaURL. ParseReminders ignores it like any other comment.

const RemindersSchemaURL = "https://game.nsgo.dev/schemas/reminders.v1.json"

RemindersSchemaURL is where the JSON Schema of version 1 reminders files is published. EncodeReminders writes it in a yaml-language-server comment on the first line so editors and AI tools validate and complete reminders files as they are written.

const RemindersVersion = 1

RemindersVersion is the schema version of a YAML reminders file (reminders.yaml) this package reads and writes.

变量

var (
	// ErrCorruptCloudSave reports a cloud payload marked with CloudSaveFormat that does not decode: an unknown field, a newer schema version, a hash that does not match its data, or a malformed value. The slot is left untouched on both sides.
	ErrCorruptCloudSave = errors.New("liveops: corrupt cloud save")
	// ErrCorruptSyncState reports a slot's stored sync state that does not decode. The slot is left untouched on both sides.
	ErrCorruptSyncState = errors.New("liveops: corrupt cloud sync state")
	// ErrCloudChanged reports that the cloud copy of a slot changed between CloudSyncer reading it and writing it, such as when another device uploaded at the same moment. Nothing was written; the next sync sees the new copy.
	ErrCloudChanged = errors.New("liveops: cloud save changed during sync")
	// ErrConflictChanged reports that a slot passed to CloudSyncer.Resolve no longer holds the copies of the Conflict it was given, because a save or a sync changed either side since. Nothing was written; sync again to see the current conflict, if any.
	ErrConflictChanged = errors.New("liveops: save changed since the conflict was reported")
	// ErrInvalidDevice reports a device ID that is empty, longer than 64 bytes or not made of ASCII letters, digits, '-' and '_'.
	ErrInvalidDevice = errors.New("liveops: invalid device id")
)
var (
	// ErrInvitePayloadTooLarge reports an invite payload whose encoded "key=value&..." representation exceeds the host or configured byte limit.
	ErrInvitePayloadTooLarge = errors.New("liveops: invite payload exceeds size limit")

	// ErrInvalidInvitePayload reports a malformed invite payload (invalid key, control character, duplicate key, bad percent-encoding, or too many keys).
	ErrInvalidInvitePayload = errors.New("liveops: invalid invite payload")

	// ErrInvalidInviteSignature reports an invite payload whose HMAC-SHA256 signature is missing (when required) or does not match.
	ErrInvalidInviteSignature = errors.New("liveops: invalid invite signature")

	// ErrMissingHMACKey reports InvitesOptions or InvitePayloadOptions with RequireSignature set but an empty HMACKey.
	ErrMissingHMACKey = errors.New("liveops: RequireSignature requires a non-empty HMACKey")

	// ErrInvalidInviteURL reports a malformed invite base URL or incoming link.
	ErrInvalidInviteURL = errors.New("liveops: invalid invite URL")

	// ErrInvalidCard reports a share card with invalid fields (such as conflicting InviteID/Payload["id"], control characters, or conflicting Signature/HMACKey).
	ErrInvalidCard = errors.New("liveops: invalid share card")

	// ErrShareUnavailable reports that the current platform or host does not support sharing.
	ErrShareUnavailable = errors.New("liveops: sharing is unavailable on this platform")
)
var (
	// ErrReminderNotFound is returned by Schedule and ScheduleWith when id is not declared in RemindersConfig.
	ErrReminderNotFound = errors.New("liveops: reminder not found")
	// ErrInvalidSchedule is returned by ScheduleWith when ScheduleOptions sets both Delay and At, sets a negative Delay, or schedules a non-repeating reminder in the past.
	ErrInvalidSchedule = errors.New("liveops: invalid reminder schedule")
)
var ErrCloudConflict = errors.New("liveops: platform cloud save conflict")

ErrCloudConflict is returned by PlatformCloud when the native cloud backend (iCloud NSFileVersion or Google Play Games Saved Games) holds unresolved conflicting versions of a slot. Resolve it through PlatformCloud.OnConflict or by writing the winning payload.

var ErrCloudUnavailable = errors.New("liveops: cloud save backend unavailable")

ErrCloudUnavailable is returned by a CloudSync implementation when cloud storage is signed out, offline or unsupported on the current target.

var ErrInvalidConsent = errors.New("liveops: invalid consent state")

ErrInvalidConsent is returned by Analytics.SetConsent when given an unknown ConsentState value.

var ErrNoLedger = errors.New("liveops: purchases need a ledger")

ErrNoLedger is what Buy and every delivery answer when PurchasesOptions has no Ledger to record credits in.

var ErrSlotNotFound = errors.New("liveops: cloud save slot not found")

ErrSlotNotFound is returned by CloudSync.Load when the requested save slot does not exist.

var ErrSlotTooLarge = errors.New("liveops: cloud save slot too large")

ErrSlotTooLarge is returned by a CloudSync implementation whose backend refuses a save payload over its size limit. The slot is left as it was.

var ErrTooManySlots = errors.New("liveops: too many cloud save slots")

ErrTooManySlots is returned by a CloudSync implementation whose backend refuses a new slot because the player already has as many as it keeps. The slot is not created.

函数

func CaptureCardSnapshot(cx *core.Scope, target *core.Ref, opts CardSnapshotOptions, done func(core.ImageSource, error))

CaptureCardSnapshot captures target (or the owning surface when target is nil) through core.Scope.Capture, center-crops and scales it into a 5:4 PNG image, and returns a core.ImageSource ready for Card.Image.

func CropCardSnapshot(src image.Image, maxWidth int) (*image.RGBA, error)

CropCardSnapshot center-crops src to a 5:4 rectangle and scales it down to at most maxWidth pixels wide (DefaultCardSnapshotWidth when <= 0).

func EncodeCardSnapshotPNG(src image.Image, maxWidth int) ([]byte, error)

EncodeCardSnapshotPNG center-crops src to 5:4, scales to at most maxWidth pixels wide, and encodes the result as PNG bytes.

func EncodeCloudSave(v SaveVersion) ([]byte, error)

EncodeCloudSave returns the JSON text CloudSyncer stores in the cloud for v: format, version, revision, hash, modified time (RFC 3339, UTC), device and the save data, in that fixed order. Data that is valid UTF-8, such as a save.Store payload, is kept as a readable string; other data is base64 in data_base64. v.Hash is recomputed from v.Data and v.Summary is not stored.

func EncodeInvitePayload(payload map[string]string, opts InvitePayloadOptions) (string, error)

EncodeInvitePayload encodes payload as a deterministic, lexicographically sorted "key=value&..." string within opts.MaxBytes. When opts.HMACKey is non-empty, it appends a base64url raw HMAC-SHA256 signature under InviteSigKey ("sig") computed over the canonical unsigned query and checks the final signed length against opts.MaxBytes.

func EncodeReminders(cfg *RemindersConfig) ([]byte, error)

EncodeReminders validates cfg and writes deterministic 2-space YAML prefixed with RemindersSchemaComment that ParseReminders reads back unchanged.

func ExtractInviteQuery(rawURL string, opts InviteLinkOptions) (rawQuery string, matched bool, err error)

ExtractInviteQuery checks whether rawURL matches opts.BaseURL and extracts its raw invite payload string according to opts.Encoding. It returns matched == false with a nil error when rawURL is empty, uses a different scheme/host/path, or carries no payload.

func FormatInviteURL(baseURL, rawQuery string, encoding InviteEncoding) (string, error)

FormatInviteURL attaches rawQuery to baseURL according to encoding (InviteEncodeQuery or InviteEncodeFragment). baseURL must have a valid scheme and must not already carry a query (for InviteEncodeQuery) or fragment (for InviteEncodeFragment).

func PayloadHash(payload []byte) string

PayloadHash identifies a raw cloud payload for ConditionalCloudSync: "sha256:" followed by the lowercase hex SHA-256 of payload.

func SignInvitePayload(payload map[string]string, hmacKey []byte, maxBytes int) (string, error)

SignInvitePayload encodes payload and signs it with HMAC-SHA256 using hmacKey. It is intended for both game clients and game servers minting verifiable invite payloads.

func ValidateRemindersConfig(cfg *RemindersConfig) error

ValidateRemindersConfig checks cfg against the version 1 reminders schema.

类型

type Analytics struct {
	// contains filtered or unexported fields
}

Analytics gates event tracking on explicit player consent and optionally persists the consent choice in core.Storage.

Events tracked while Consent is ConsentUnknown or ConsentDenied are dropped immediately — they are never sent and never buffered for later replay.

func NewAnalytics(store core.Storage, key string, provider AnalyticsProvider) *Analytics

NewAnalytics returns an Analytics gate backed by store under key (DefaultConsentKey when empty) and dispatching consented events to provider. It loads any previously persisted consent choice from store immediately, failing closed to ConsentUnknown when absent or unrecognized.

func NewMemoryAnalytics(provider AnalyticsProvider) *Analytics

NewMemoryAnalytics returns an Analytics gate that keeps its consent state in memory only, starting in ConsentUnknown.

func (a *Analytics) Consent() ConsentState

Consent returns the current ConsentState. When backed by core.Storage, reading Consent inside a reactive computation subscribes it to storage changes.

func (a *Analytics) Flush() error

Flush flushes the configured provider when Consent is ConsentGranted. When consent is not granted or no provider is set, Flush is a no-op returning nil.

func (a *Analytics) SetClock(now func() time.Time)

SetClock sets the clock function used for Event.Time; time.Now is used when nil.

func (a *Analytics) SetConsent(state ConsentState) error

SetConsent updates the consent choice and persists it when backed by core.Storage. Revoking consent (ConsentDenied or ConsentUnknown) immediately stops all subsequent Track calls.

func (a *Analytics) SetProvider(provider AnalyticsProvider)

SetProvider replaces the AnalyticsProvider that receives consented events.

func (a *Analytics) Track(name string, props map[string]any) bool

Track dispatches an event to the configured provider only when Consent is ConsentGranted. When consent is ConsentUnknown or ConsentDenied, or when no provider is configured, Track drops the event immediately without buffering and returns false. When consent is granted, props is defensively copied before dispatch and Track returns whether provider.Send succeeded.

type AnalyticsProvider interface {
	Send(Event) error
	Flush() error
}

AnalyticsProvider receives analytics events after explicit opt-in consent. Provider implementations live outside the core game module so no third-party analytics SDK is linked unless chosen by the app.

type BuyResult int

BuyResult is how a Buy ended without an error.

const (
	// BuyFailed is the result that goes with an error.
	BuyFailed BuyResult = iota
	// Bought: the purchase went through and was delivered, its credit saved or its unlock owned.
	Bought
	// BuyPending: the purchase waits for approval, as Ask to Buy's does; Pending reports it until its transaction arrives through the store's updates, which deliver it as Buy would have.
	BuyPending
	// BuyCancelled: the user closed the store's sheet.
	BuyCancelled
)
func (r BuyResult) String() string

String returns "failed", "bought", "pending" or "cancelled".

type Card struct {
	// Title is the short headline shown on the share card or prepended to the native/web share message.
	Title string
	// Image is the card's image (for example a 5:4 snapshot from CaptureCardSnapshot or an embedded PNG/JPEG).
	Image core.ImageSource
	// ImageID is an optional platform-reviewed image identifier (such as WeChat mini game's imageUrlId).
	ImageID string
	// InviteID is an optional unique identifier for this invite, encoded under InviteIDKey ("id").
	// Servers use Invite.ID as the idempotency key for invite reward grants.
	InviteID string
	// Payload holds key-value parameters carried to whoever opens the game from the card (for example room or party IDs).
	// Unknown keys are preserved on decode.
	Payload map[string]string
	// Signature is an optional pre-computed base64url raw HMAC-SHA256 signature minted by a server.
	// When InvitesOptions.HMACKey is configured, Invites computes the signature itself and refuses a non-empty Card.Signature.
	Signature string
	// Anchor is the optional UI element anchoring a popover share sheet on macOS and iPadOS.
	Anchor *core.Ref
}

Card describes a share card or invite passed to Invites.Share or returned by a menu-share callback.

type CardSnapshotOptions struct {
	// MaxWidth caps the output snapshot width in pixels while preserving the 5:4 aspect ratio (height = MaxWidth * 4 / 5).
	// Values <= 0 default to DefaultCardSnapshotWidth (500, giving 500x400).
	// Snapshots narrower than MaxWidth are center-cropped to 5:4 without upscaling.
	MaxWidth int
}

CardSnapshotOptions configures CaptureCardSnapshot.

type Choice int

Choice is the answer to a Conflict under PolicyAsk.

const (
	// ChoiceDefer leaves the conflict unresolved: nothing is written on either side and the next sync asks again.
	ChoiceDefer Choice = iota
	// ChoiceLocal keeps this device's copy and overwrites (or deletes) the cloud copy.
	ChoiceLocal
	// ChoiceCloud keeps the cloud copy and overwrites (or deletes) this device's copy. SlotResult.Discarded holds the replaced copy; when it was a valid save envelope and the cloud copy exists, the local save backend also keeps it as its backup.
	ChoiceCloud
	// ChoiceBoth keeps the cloud copy in the slot and moves this device's copy into a fork slot on both sides. When one side deleted the slot it keeps the copy that exists.
	ChoiceBoth
)
func (c Choice) String() string

String returns "defer", "local", "cloud", "both" or "unknown".

type CloudChange struct {
	// Slots lists the sorted save slot names affected by this change. It may be empty on account-change or initial-sync notifications that did not enumerate individual files.
	Slots []string
	// Reason explains why the external change arrived.
	Reason cloud.ChangeReason
}

CloudChange reports save slots updated or deleted externally in platform cloud storage (such as from another device).

type CloudClient struct {
	// contains filtered or unexported fields
}

CloudClient is the CloudSync of the self-hosted cloud save service in package cloudsave, over HTTPS. It implements ConditionalCloudSync, so a CloudSyncer on it never overwrites another device's upload, and adds the service's version history: Versions, LoadVersion, Restore and Purge.

Its errors wrap the liveops sentinels: ErrSlotNotFound, ErrCloudChanged when a conditional write lost to another device, ErrSlotTooLarge (with the service's limit in the message), ErrTooManySlots, and ErrCloudUnavailable when the network, the service or the token fails, which a sync treats as offline. A done context's error is returned as it is. A CloudClient is safe for concurrent use.

func NewCloudClient(opts CloudClientOptions) (*CloudClient, error)

NewCloudClient returns a client for opts, or an error when the URL or the token source is missing or invalid.

func (c *CloudClient) Delete(ctx context.Context, slot string) error

Delete implements CloudSync. The service keeps the slot's history, so Restore can bring it back.

func (c *CloudClient) DeleteIf(ctx context.Context, slot, match string) error

DeleteIf implements ConditionalCloudSync.

func (c *CloudClient) List(ctx context.Context) ([]string, error)

List implements CloudSync: the names of the player's live slots, in byte order.

func (c *CloudClient) Load(ctx context.Context, slot string) ([]byte, error)

Load implements CloudSync. It checks the payload against the service's ETag.

func (c *CloudClient) LoadVersion(ctx context.Context, slot string, number int64) ([]byte, error)

LoadVersion returns the payload of kept version number of slot, as Load returns the current one. It returns ErrSlotNotFound when the version is not kept or is a deletion.

func (c *CloudClient) Purge(ctx context.Context, slot string) error

Purge removes slot and its whole history from the service for good; a slot that does not exist is not an error.

func (c *CloudClient) Restore(ctx context.Context, slot string, number int64) error

Restore makes kept version number the slot's current copy, as a new version written only while the slot still holds the copy Restore read (ErrCloudChanged otherwise). Restoring a deletion deletes the slot.

A payload written by CloudSyncer is re-stamped with the next revision and the current time, so every device sees the restore as the newest copy: one whose copy is unchanged since its last sync downloads it on the next sync, and one with unsynced changes gets a conflict its policy resolves. Other payloads are restored byte for byte.

func (c *CloudClient) Save(ctx context.Context, slot string, data []byte) error

Save implements CloudSync: it replaces the slot whatever it holds.

func (c *CloudClient) SaveIf(ctx context.Context, slot string, data []byte, match string) error

SaveIf implements ConditionalCloudSync.

func (c *CloudClient) Versions(ctx context.Context, slot string) ([]CloudVersion, error)

Versions lists the kept versions of slot, newest first, deletions included. It returns ErrSlotNotFound for a slot with no history.

type CloudClientOptions struct {
	// URL is the base URL of the cloud save service (package cloudsave), such as "https://saves.example.com". It must use https, except on a loopback host (localhost, 127.0.0.1, ::1) during development. Required.
	URL string
	// Token returns a current bearer token from the account service for the signed-in player and the cloud save service's audience ("cloudsave" by default: POST /v1/refresh with that audience), getting a new one when the last has expired. The token a sign-in returns is for game servers, and the service refuses it. Every device signed in to the same account reads and writes the same slots. Required.
	Token func(ctx context.Context) (string, error)
	// HTTPClient sends the requests; http.DefaultClient when nil. The client uses a copy that does not follow redirects. On the web its requests go through the browser's fetch, so the page's origin must be in the service's allowedOrigins.
	HTTPClient *http.Client
	// Now stamps payloads Restore re-writes; time.Now when nil.
	Now func() time.Time
}

CloudClientOptions configures NewCloudClient.

type CloudProvider uint8

CloudProvider names a platform cloud-save service.

const (
	// CloudProviderNone means the platform has no built-in OS cloud-save service through NSGo's cloud package (Windows, Linux, the web).
	CloudProviderNone CloudProvider = iota
	// CloudProviderICloud is Apple's iCloud ubiquity container on macOS and iOS (including iPadOS and tvOS).
	CloudProviderICloud
	// CloudProviderPlayGames is Google Play Games Saved Games on Android.
	CloudProviderPlayGames
	// CloudProviderSteam is Steam Auto-Cloud on desktop targets, which syncs a local directory (such as cx.DataDir() or a subdirectory via DirCloud).
	CloudProviderSteam
)
func CloudProviderFor(env *core.Env) CloudProvider

CloudProviderFor returns the built-in OS cloud-save service NSGo's cloud package reaches in env: CloudProviderNone when env is nil or Simulated (such as a mini program or a web build with --nsgo-os), CloudProviderICloud on native macOS and iOS, CloudProviderPlayGames on native Android, and CloudProviderNone elsewhere.

func (p CloudProvider) String() string

String returns "none", "icloud", "play-games" or "steam".

type CloudSync interface {
	// Load reads the raw bytes stored in slot, returning ErrSlotNotFound if slot does not exist.
	Load(ctx context.Context, slot string) ([]byte, error)
	// Save writes data to slot, replacing any previous contents.
	Save(ctx context.Context, slot string, data []byte) error
	// Delete removes slot if it exists.
	Delete(ctx context.Context, slot string) error
	// List returns the names of all save slots stored for the current player.
	List(ctx context.Context) ([]string, error)
}

CloudSync is the provider-agnostic cloud-save interface for NSGo games (#196).

PlatformCloud adapts NSGo's cloud package (iCloud on macOS and iOS, Google Play Games Saved Games on Android, and the in-memory store under nsgotest); DirCloud adapts a local directory synced by a desktop storefront such as Steam Auto-Cloud; CloudClient talks to the self-hosted backend in package cloudsave; and games can also supply their own backend or an in-memory mock against this interface.

type CloudSyncOptions struct {
	// Local is this device's save backend, such as save.StorageBackend or save.FileBackend. Required.
	Local save.Backend
	// Cloud is the player's cloud storage. Required.
	Cloud CloudSync
	// State holds each slot's sync state on this device, as JSON text under StateKey. Required.
	State core.Storage
	// StateKey is the key prefix CloudSyncer owns in State; DefaultSyncStateKey when empty.
	StateKey string
	// Device identifies this device in cloud payloads and fork slot names: 1 to 64 ASCII letters, digits, '-' or '_'. Required.
	Device string
	// SaveVersion is the game's save schema version (the Store.Version passed to save.NewStore). When greater than 0, a cloud copy whose save envelope version exceeds SaveVersion is never written locally and is reported as OutcomeNeedsUpdate with both versions, and an older client never overwrites or deletes a newer-version cloud copy. When 0, version gating against SaveVersion is disabled, though mixed-version conflicts still refuse to resolve in favour of the older envelope version.
	SaveVersion int
	// Policy resolves conflicts; PolicyNewest when zero.
	Policy ConflictPolicy
	// Ask answers each conflict under PolicyAsk. It is required with PolicyAsk. It runs inside the sync, on the app's thread, so it must return without waiting for the player: to ask through a dialog, keep the Conflict, return ChoiceDefer, show both summaries, and apply the answer with CloudSyncer.Resolve. An error leaves the slot untouched and is returned by the sync.
	Ask func(ctx context.Context, c Conflict) (Choice, error)
	// Summarize returns a short, player-facing description of a save payload for Conflict summaries. Optional.
	Summarize func(slot string, data []byte) string
	// Now returns the current time, used to stamp local writes made through Backend; time.Now when nil.
	Now func() time.Time
}

CloudSyncOptions configures NewCloudSyncer.

type CloudSyncer struct {
	// contains filtered or unexported fields
}

CloudSyncer reconciles a device's save slots with cloud storage, detecting slots that changed on both sides since the last sync and resolving them by policy without silently losing either copy.

It remembers, per slot, the content hash and cloud revision both sides agreed on at the last sync (the base). On each sync it compares the local copy, the cloud copy and the base: when only one side differs from the base that side is copied to the other, and when both differ (and from each other) the slot is a conflict. Cloud payloads are JSON text carrying the revision, content hash, modified time and writing device next to the save data.

Write saves through Backend so that each local write is stamped with its time for PolicyNewest and conflict summaries. A CloudSyncer is not safe for concurrent use; call Sync, SyncSlot and Resolve where the app's code runs, as core.Storage requires, or use SyncAsync, SyncSlotAsync and ResolveAsync to run cloud I/O off the engine goroutine while marshaling local storage, sync state and Ask callbacks onto cx's engine goroutine (required with PlatformCloud on Apple and Android devices, and recommended with CloudClient so network I/O does not stall frames).

Before every cloud write it reads the cloud copy again and refuses to write when it changed (ErrCloudChanged). When Cloud implements ConditionalCloudSync, as CloudClient and DirCloud do, the write itself is conditional on that copy, so an upload by another device can never be overwritten: the losing write fails with ErrCloudChanged and the next sync sees both copies as a conflict for the policy to resolve. A plain CloudSync has no conditional write, so an upload by another device that lands between the re-read and the write can still be overwritten; the window is a single Load and Save apart.

func NewCloudSyncer(opts CloudSyncOptions) (*CloudSyncer, error)

NewCloudSyncer returns a CloudSyncer for opts, or an error when a required option is missing or invalid.

func (s *CloudSyncer) Backend() save.Backend

Backend returns the local save backend wrapped so that every Write and Delete is stamped with the current time in the slot's sync state. Pass it to save.NewStore so PolicyNewest and conflict summaries know when each local copy was written. Its Unwrap method returns the local backend, so a save.SettingsStore built on it keeps settings where the local backend does.

func (s *CloudSyncer) Resolve(ctx context.Context, c Conflict, choice Choice) (SlotResult, error)

Resolve applies choice to a conflict reported earlier, typically one that Ask answered with ChoiceDefer so the game could show the player both copies outside the sync. It reads both sides again and applies choice only while they still hold the copies in c (the same existence, content hash and cloud revision); otherwise it writes nothing and returns ErrConflictChanged. ChoiceDefer writes nothing. Resolve works under every policy and does not call Ask.

func (s *CloudSyncer) ResolveAsync(cx *core.Scope, ctx context.Context, c Conflict, choice Choice, done func(SlotResult, error))

ResolveAsync runs Resolve asynchronously as SyncAsync does for Sync.

func (s *CloudSyncer) Sync(ctx context.Context) (SyncResult, error)

Sync reconciles every slot known locally, in the cloud or in the sync state, in slot-name order.

A slot that fails is skipped and its error joined into the returned error while the others still sync, except when the cloud is unavailable or ctx is done, which stops the sync.

func (s *CloudSyncer) SyncAsync(cx *core.Scope, ctx context.Context, done func(SyncResult, error))

SyncAsync runs Sync with cloud I/O off cx's engine goroutine while marshaling local backend, sync state, Summarize, Now and Ask calls onto cx's engine goroutine through cx.Post, then delivers the result to done on the engine goroutine. Use it on Apple and Android devices with PlatformCloud (whose callbacks arrive via cx.Post) and with CloudClient so network I/O does not block frames.

Concurrent SyncAsync, SyncSlotAsync and ResolveAsync calls on the same CloudSyncer are serialized in order. If a local save changes a slot while its cloud read is in flight, SyncAsync refuses to overwrite the local copy (ErrConflictChanged) so the next sync resolves both copies cleanly. Disposing cx stops the sync and skips done.

func (s *CloudSyncer) SyncSlot(ctx context.Context, slot string) (SlotResult, error)

SyncSlot reconciles one slot. On error nothing has been written for the slot, except that a failure after a conflict fork was created leaves the fork in place; the next sync uploads it and reuses it rather than creating another.

func (s *CloudSyncer) SyncSlotAsync(cx *core.Scope, ctx context.Context, slot string, done func(SlotResult, error))

SyncSlotAsync runs SyncSlot asynchronously as SyncAsync does for Sync.

type CloudVersion struct {
	// Number counts the slot's versions from 1; each write or delete adds one.
	Number int64
	// Deleted marks a version that deleted the slot.
	Deleted bool
	// Hash is the PayloadHash of the version's payload, empty for a deletion.
	Hash string
	// Size is the payload's length in bytes.
	Size int64
	// Created is when the service stored the version.
	Created time.Time
}

CloudVersion describes one kept version of a slot in the service's history.

type ConditionalCloudSync interface {
	CloudSync
	// SaveIf writes data to slot only while the slot holds the payload whose PayloadHash is match, or, when match is empty, only while the slot does not exist. Otherwise it writes nothing and returns an error wrapping ErrCloudChanged.
	SaveIf(ctx context.Context, slot string, data []byte, match string) error
	// DeleteIf removes slot only while it holds the payload whose PayloadHash is match. Otherwise it removes nothing and returns an error wrapping ErrCloudChanged. An empty match succeeds, removing nothing, while slot does not exist.
	DeleteIf(ctx context.Context, slot, match string) error
}

ConditionalCloudSync is a CloudSync whose backend can write and delete a slot only while it still holds the payload the caller last read, so two devices writing the same slot at once cannot overwrite each other. CloudSyncer uses these methods whenever its Cloud implements them; CloudClient does.

A payload is identified by PayloadHash of its raw bytes, as Load returned them.

type Conflict struct {
	// Slot is the save slot name.
	Slot string
	// Local is this device's copy.
	Local SaveVersion
	// Cloud is the copy in cloud storage.
	Cloud SaveVersion
}

Conflict is a slot whose local and cloud copies both changed since this device last synced it, passed to CloudSyncOptions.Ask under PolicyAsk and reported in SlotResult.Conflict. Pass it back to CloudSyncer.Resolve to apply the player's choice later.

type ConflictPolicy int

ConflictPolicy chooses how CloudSyncer resolves a slot whose local and cloud copies both changed since the last sync.

const (
	// PolicyNewest keeps the copy with the later modified time and overwrites the other. When either time is unknown or both are equal it keeps both, as PolicyKeepBoth does, and when one side deleted the slot and the other changed it, it keeps the changed copy. When both sides carry save envelopes of different versions, it never resolves in favour of the older envelope version and falls back to keeping both.
	PolicyNewest ConflictPolicy = iota
	// PolicyKeepBoth keeps the cloud copy in the slot and moves the local copy into a new fork slot on both sides, so neither is lost. When one side deleted the slot and the other changed it, it keeps the changed copy.
	PolicyKeepBoth
	// PolicyAsk passes each conflict, with a summary and envelope version of both copies, to CloudSyncOptions.Ask and applies the player's Choice.
	PolicyAsk
)
func (p ConflictPolicy) String() string

String returns "newest", "keep-both", "ask" or "unknown".

type ConsentState int

ConsentState represents the player's analytics consent choice.

const (
	// ConsentUnknown is the default before the player chooses. No events are sent or buffered.
	ConsentUnknown ConsentState = iota
	// ConsentDenied records that the player declined or revoked analytics. No events are sent or buffered.
	ConsentDenied
	// ConsentGranted records explicit opt-in consent. Only in this state may events be dispatched to the provider.
	ConsentGranted
)
func (s ConsentState) String() string

String returns "unknown", "denied" or "granted".

type CrashOptions struct {
	// HistorySize is how many recent steps the ring buffer keeps; DefaultHistorySize (120) when <= 0.
	HistorySize int
	// Reporter receives every CrashReport produced by a recovered panic.
	Reporter func(CrashReport)
	// CaptureState optionally returns a JSON-marshalable snapshot of the game's state when a panic is caught.
	CaptureState func() any
	// Metadata holds initial key-value pairs copied into every CrashReport (such as app version, target OS or scene name).
	Metadata map[string]string
	// Rethrow re-panics with the recovered value after Reporter returns.
	Rethrow bool
	// Now returns the clock time for CrashReport.Timestamp; time.Now when nil.
	Now func() time.Time
}

CrashOptions configures a CrashReporter.

type CrashReport = crashreport.CrashReport

CrashReport is a JSON-marshalable snapshot built when a guarded callback panics. It is an alias for crashreport.CrashReport, so headless servers build the same schema without importing liveops.

type CrashReporter struct {
	// contains filtered or unexported fields
}

CrashReporter records recent simulation steps in a fixed-size ring buffer and catches panics in guarded callbacks or game.Loop runs, building a CrashReport for the app's Reporter.

func NewCrashReporter(opts CrashOptions) *CrashReporter

NewCrashReporter returns a CrashReporter configured by opts, pre-allocating its step ring buffer so steady-state RecordStep calls perform no heap allocations.

func (c *CrashReporter) DeleteMetadata(key string)

DeleteMetadata removes a metadata key from subsequent CrashReports.

func (c *CrashReporter) GuardLoop(l *game.Loop)

GuardLoop wraps l.Update and l.Draw in place with panic recovery and step recording. If l.Update does not call RecordStep itself during a step, the guard records an "update" step automatically (including for a step that panics).

func (c *CrashReporter) LastSteps() []StepRecord

LastSteps returns a chronological copy (oldest to newest) of the buffered steps.

func (c *CrashReporter) RecordStep(dt time.Duration, summary string) uint64

RecordStep appends a step to the ring buffer and returns its monotonic step number. It allocates nothing in steady state.

func (c *CrashReporter) RecordStepData(dt time.Duration, summary string, data any) uint64

RecordStepData appends a step with optional structured data to the ring buffer and returns its monotonic step number. It allocates nothing in steady state.

func (c *CrashReporter) Reset()

Reset clears the buffered steps without reallocating the ring buffer. The monotonic step counter continues from its current value.

func (c *CrashReporter) RunSafe(fn func()) (panicked bool)

RunSafe runs fn and recovers any panic into a CrashReport passed to Reporter. It reports whether fn panicked. When CrashOptions.Rethrow is true, RunSafe re-panics with the original value after Reporter returns.

func (c *CrashReporter) SetMetadata(key, value string)

SetMetadata sets or updates a metadata key included in subsequent CrashReports.

func (c *CrashReporter) Step() uint64

Step returns the reporter's current monotonic step count.

func (c *CrashReporter) WrapLoop(l *game.Loop) *game.Loop

WrapLoop returns a new *game.Loop that delegates to l.Update and l.Draw with panic recovery and step recording. If l.Update does not call RecordStep itself during a step, the wrapper records an "update" step automatically (including for a step that panics). Returns nil when l is nil.

type DecodedInvitePayload struct {
	// ID is the value of InviteIDKey ("id") when present in Payload.
	ID string
	// Payload contains every decoded key-value pair except InviteSigKey ("sig"), preserving unknown keys.
	Payload map[string]string
	// Signature is the raw InviteSigKey ("sig") value if present in the input, empty otherwise.
	Signature string
	// Verified is true only when a non-empty HMACKey was provided and Signature matched Payload under HMAC-SHA256.
	Verified bool
}

DecodedInvitePayload is the validated result of DecodeInvitePayload or VerifyInvitePayload.

func DecodeInvitePayload(raw string, opts InvitePayloadOptions) (DecodedInvitePayload, error)

DecodeInvitePayload parses, validates and optionally verifies an encoded "key=value&..." invite payload.

Malformed percent-encoding, empty segments, missing "=" separators, duplicate keys, invalid key names, control characters, invalid UTF-8, excessive key counts and payloads exceeding opts.MaxBytes are rejected safely. Unknown keys that satisfy validation are preserved in DecodedInvitePayload.Payload.

When opts.HMACKey is non-empty:

  • a valid signature sets Verified = true;
  • a present but mismatched signature is rejected with ErrInvalidInviteSignature;
  • a missing signature is rejected with ErrInvalidInviteSignature when opts.RequireSignature is true, and otherwise returns Verified = false.
func VerifyInvitePayload(raw string, hmacKey []byte, maxBytes int) (DecodedInvitePayload, error)

VerifyInvitePayload decodes raw and requires a valid HMAC-SHA256 signature under hmacKey. A game server receiving Invite.RawQuery calls VerifyInvitePayload before granting invite rewards or honoring privileged invite payloads.

type DirCloud struct {
	// contains filtered or unexported fields
}

DirCloud implements ConditionalCloudSync over a directory on disk, storing each slot as "<slot>.json" with atomic temp-file writes and directory sync.

It is designed for desktop storefronts such as Steam Auto-Cloud, which synchronize a configured directory (such as a subdirectory of cx.DataDir()) across machines without a native cloud SDK. Pairing DirCloud with CloudSyncer gives Steam builds the same CloudSync and conflict-resolution pipeline as iCloud and Google Play Games builds; games that do not need CloudSyncer's conflict envelopes can also point Steam Auto-Cloud directly at save.FileBackend(cx.DataDir()).

DirCloud is safe for concurrent use within a process.

func NewDirCloud(dir string) (*DirCloud, error)

NewDirCloud returns a DirCloud storing slot files inside dir, or an error when dir is empty (such as cx.DataDir() on the web). The directory is created on the first write.

func (c *DirCloud) Delete(ctx context.Context, slot string) error

Delete implements CloudSync.

func (c *DirCloud) DeleteIf(ctx context.Context, slot, match string) error

DeleteIf implements ConditionalCloudSync.

func (c *DirCloud) Dir() string

Dir returns the cleaned directory path where DirCloud keeps slot files.

func (c *DirCloud) List(ctx context.Context) ([]string, error)

List implements CloudSync. It returns the sorted names of all valid save slots in the directory, or nil if the directory does not exist yet.

func (c *DirCloud) Load(ctx context.Context, slot string) ([]byte, error)

Load implements CloudSync.

func (c *DirCloud) Save(ctx context.Context, slot string, data []byte) error

Save implements CloudSync.

func (c *DirCloud) SaveIf(ctx context.Context, slot string, data []byte, match string) error

SaveIf implements ConditionalCloudSync.

type Event struct {
	Name       string         `json:"name"`
	Properties map[string]any `json:"properties,omitempty"`
	Time       time.Time      `json:"time"`
}

Event is one analytics event delivered to an AnalyticsProvider after explicit consent.

type Invite struct {
	// ID is the invite identifier from InviteIDKey ("id"), empty when not present.
	// Pass ID to the game server as the idempotency key for invite reward grants.
	ID string
	// Payload holds all decoded payload fields except InviteSigKey ("sig"), preserving unknown keys.
	Payload map[string]string
	// RawQuery is the raw "key=value&..." payload received from the host, suitable for forwarding to a game server for VerifyInvitePayload.
	RawQuery string
	// RawURL is the full URL that opened the game on native/web hosts (empty on mini games).
	RawURL string
	// Signature is the raw signature from InviteSigKey ("sig"), empty when unsigned.
	Signature string
	// Verified is true only when InvitesOptions.HMACKey was configured and Signature matched Payload under HMAC-SHA256.
	Verified bool
	// Scene is the platform launch scene code (0 when unused).
	Scene int
	// ShareTicket is the opaque group-share ticket supplied by mini-game hosts (empty otherwise).
	ShareTicket string
	// Source reports whether the invite arrived on cold launch (InviteSourceLaunch) or while running (InviteSourceResume).
	Source InviteSource
}

Invite is a decoded, validated invite received when a player opens or resumes the game from a share card or invite link.

func (inv Invite) Clone() Invite

Clone returns a copy of inv with an independent Payload map.

func (inv Invite) Get(key string) (string, bool)

Get returns the value of key from Invite.Payload.

type InviteEncoding uint8

InviteEncoding chooses where a link-based ShareHost places the encoded invite payload in a URL.

const (
	// InviteEncodeQuery places the encoded payload in the URL query component ("?k=v&...").
	InviteEncodeQuery InviteEncoding = iota
	// InviteEncodeFragment places the encoded payload in the URL fragment component ("#k=v&..."), avoiding server access logs and cache-key fragmentation on the web.
	InviteEncodeFragment
)
func (e InviteEncoding) String() string

String returns "query", "fragment" or "unknown".

type InviteLinkOptions struct {
	// BaseURL is the invite URL prefix (for example "mygame://invite" on mobile/desktop or "https://play.example.com/invite" on the web).
	// When non-empty, ExtractInviteQuery matches incoming URLs against BaseURL's scheme, host (case-insensitive) and path (ignoring trailing slashes).
	BaseURL string
	// Encoding selects query (default) or fragment encoding.
	Encoding InviteEncoding
	// AcceptFragment, when true with InviteEncodeQuery, falls back to reading the URL fragment when the query string is empty.
	AcceptFragment bool
}

InviteLinkOptions configures how invite URLs are built and matched on native and web platforms.

type InvitePayloadOptions struct {
	// MaxBytes caps the encoded "key=value&..." payload length in bytes.
	// Values <= 0 use DefaultMaxInvitePayloadBytes (1024).
	MaxBytes int
	// HMACKey, when non-empty, signs encoded payloads with HMAC-SHA256 under InviteSigKey ("sig")
	// and verifies decoded payloads in constant time.
	HMACKey []byte
	// RequireSignature, when true during decoding, rejects unsigned payloads with ErrInvalidInviteSignature.
	// Requires a non-empty HMACKey; otherwise DecodeInvitePayload returns ErrMissingHMACKey.
	RequireSignature bool
}

InvitePayloadOptions configures EncodeInvitePayload and DecodeInvitePayload.

type InviteSource uint8

InviteSource reports whether an invite reached the game at cold launch or while already running.

const (
	// InviteSourceLaunch indicates the game was cold-started from the invite.
	InviteSourceLaunch InviteSource = iota + 1
	// InviteSourceResume indicates the invite arrived while the game was already running (for example via OnOpenLinks, web URL change or mini-game onShow).
	InviteSourceResume
)
func (s InviteSource) String() string

String returns "launch", "resume" or "unknown".

type Invites struct {
	// contains filtered or unexported fields
}

Invites sends payload-carrying share cards and invites over a ShareHost and reads incoming invites back on cold launch and warm resume.

Outgoing payloads are canonically encoded as "key=value&...", bounded by the host's payload limit and refused before sharing if invalid or oversized. Incoming invites are delivered at most once: Opened consumes the cold-start invite once, and Consume / OnInvite deliver each warm resume invite once. When created with a non-nil core.Scope, Incoming, Consume and PendingCount integrate with NSGo's reactive signal graph.

func NewInvites(cx *core.Scope, opts InvitesOptions) (*Invites, error)

NewInvites creates an Invites manager backed by opts.Host (or PlatformShareHost on cx when opts.Host is nil). It reads any cold-start launch invite immediately and subscribes to warm resume invites while the scope (or manager, until Close) lives.

func (i *Invites) Close()

Close unsubscribes from the ShareHost and stops further resume invite delivery. Safe to call more than once.

func (i *Invites) Consume() (Invite, bool)

Consume reactively pops and returns the oldest unconsumed invite that arrived while the game was running, delivering each resume invite at most once. Calling Consume inside a core.Effect re-runs the effect whenever a new resume invite arrives.

func (i *Invites) Incoming() (Invite, bool)

Incoming reactively peeks at the oldest unconsumed invite that arrived while the game was running, without consuming it.

func (i *Invites) MaxPayloadBytes() int

MaxPayloadBytes returns the effective byte limit enforced on encoded invite payloads.

func (i *Invites) OnInvite(fn func(Invite)) (stop func())

OnInvite subscribes fn to invites that arrive while the game is running (warm re-open / onShow) and returns a stop function to unsubscribe.

func (i *Invites) Opened() (Invite, bool)

Opened returns the invite that cold-started the game and consumes it so subsequent calls return (Invite{}, false).

func (i *Invites) PendingCount() int

PendingCount reactively returns the number of unconsumed invites that arrived while the game was running.

func (i *Invites) PrepareCard(card Card) (PreparedCard, error)

PrepareCard validates card, encodes its payload as a canonical "key=value&..." string, signs it when HMACKey is set, and enforces MaxPayloadBytes.

func (i *Invites) SetMenuCard(fn func() Card)

SetMenuCard sets the callback supplying the card when the player uses the host's built-in share menu (such as a mini game's Forward button). Passing nil clears and disables the menu card. Each returned Card is validated, size-checked and signed before reaching the host.

func (i *Invites) Share(card Card, done func(shown bool, err error))

Share validates, encodes and optionally signs card, then asks the ShareHost to present it. Oversized or malformed cards are refused before calling the host and reported immediately to done(false, err).

type InvitesOptions struct {
	// Host is the ShareHost used to send cards and receive launch/resume invites.
	// When nil, NewInvites creates a PlatformShareHost on cx using Platform.
	Host ShareHost
	// Platform configures the default PlatformShareHost when Host is nil.
	Platform PlatformShareHostOptions
	// HMACKey, when non-empty, signs outgoing cards with HMAC-SHA256 under InviteSigKey ("sig")
	// and verifies incoming invites, setting Invite.Verified.
	HMACKey []byte
	// RequireSignature rejects incoming invites that lack a valid HMAC-SHA256 signature under HMACKey.
	// Setting RequireSignature with an empty HMACKey causes NewInvites to return ErrMissingHMACKey.
	RequireSignature bool
	// MaxPayloadBytes caps encoded invite payloads in bytes.
	// When <= 0, the host's MaxPayloadBytes() (or DefaultMaxInvitePayloadBytes) applies.
	// When larger than the host's limit, the smaller host limit still wins.
	MaxPayloadBytes int
	// OnInvite, when non-nil, runs once for each invite that arrives while the game is running.
	OnInvite func(Invite)
	// OnError, when non-nil, receives errors from malformed, oversized or unverified incoming invites or menu-card preparation failures.
	OnError func(error)
}

InvitesOptions configures NewInvites.

type LaunchInvite struct {
	// RawQuery is the encoded "key=value&..." invite payload extracted by the host.
	RawQuery string
	// RawURL is the full link that opened the game on native/web hosts (empty on mini games).
	RawURL string
	// Scene is the platform launch scene code (such as WeChat's launch/onShow scene value; 0 when unused).
	Scene int
	// ShareTicket is the opaque group-share ticket provided by mini-game hosts when opened from a group chat (empty otherwise).
	ShareTicket string
	// Source identifies whether this invite arrived on cold launch or while running.
	Source InviteSource
}

LaunchInvite is the raw invite event delivered by a ShareHost at launch or on resume.

type Ledger struct {
	// Credited are the IDs of consumable transactions credited, oldest first.
	Credited []string `json:"credited,omitempty"`
	// Revoked are the IDs of credited consumable transactions whose refund or revocation was taken back, oldest first.
	Revoked []string `json:"revoked,omitempty"`
}

Ledger records the transactions a game has credited and revoked, so each is applied once across runs. Keep it inside the state PurchasesOptions.Save writes, beside the coins, lives or other state a credit changes: the credit and its record then reach the disk in one write, so a kill before that write loses both and the store's redelivery credits it again, and a kill after it finds the record and only finishes the transaction.

func (l Ledger) HasCredited(id string) bool

HasCredited reports whether the transaction whose ID is id was credited.

func (l Ledger) HasRevoked(id string) bool

HasRevoked reports whether the refund or revocation of the transaction whose ID is id was taken back.

type MiniGameLaunchOptions struct {
	// Query is the raw "key=value&..." string. When empty and QueryMap is non-empty, MiniGameShareHost encodes QueryMap canonically.
	Query string
	// QueryMap is the decoded key-value object supplied by runtimes like WeChat mini games.
	QueryMap map[string]string
	// Scene is the platform launch/resume scene code.
	Scene int
	// ShareTicket is the opaque group-share ticket delivered when opened from a group chat with WithShareTicket enabled.
	ShareTicket string
}

MiniGameLaunchOptions mirrors a mini-game runtime's launch and onShow payloads (such as WeChat's wx.getLaunchOptionsSync and wx.onShow).

type MiniGameShareCard struct {
	Title      string
	ImageURL   string
	ImageData  []byte
	ImageURLID string
	Query      string
}

MiniGameShareCard is the share-card payload passed to a MiniGameShareDriver (matching WeChat mini game's wx.shareAppMessage and wx.onShareAppMessage fields).

type MiniGameShareDriver interface {
	// ShareAppMessage opens the mini-game forward dialog with card.
	ShareAppMessage(card MiniGameShareCard, done func(shown bool, err error))
	// ShowShareMenu enables or disables the mini-game menu's Forward item (wx.showShareMenu / wx.hideShareMenu).
	ShowShareMenu(enabled bool, withShareTicket bool)
	// OnShareAppMessage registers the handler invoked when the player taps Forward in the mini-game menu. Passing nil clears it.
	OnShareAppMessage(fn func() MiniGameShareCard)
	// LaunchOptions returns the cold-start launch options (wx.getLaunchOptionsSync).
	LaunchOptions() (MiniGameLaunchOptions, bool)
	// OnShow subscribes fn to resume events (wx.onShow) and returns an unsubscribe function.
	OnShow(fn func(MiniGameLaunchOptions)) (stop func())
}

MiniGameShareDriver is the platform runtime hook implemented by mini-game hosts (and by NSGo once nsgo-dev/nsgo#2672 adds mini-game share cards and launch options).

type MiniGameShareHost struct {
	// contains filtered or unexported fields
}

MiniGameShareHost adapts a MiniGameShareDriver to ShareHost. Passing a nil driver yields a safe unavailable host (returning ErrShareUnavailable from Share) until NSGo ships mini-game share cards (nsgo-dev/nsgo#2672).

func NewMiniGameShareHost(driver MiniGameShareDriver, opts MiniGameShareHostOptions) *MiniGameShareHost

NewMiniGameShareHost wraps driver as a ShareHost. If driver is nil, Share fails with ErrShareUnavailable and LaunchInvite/OnInvite/SetMenuCard are safe no-ops.

func (h *MiniGameShareHost) LaunchInvite() (LaunchInvite, bool)

LaunchInvite reads the mini game's cold-start LaunchOptions once.

func (h *MiniGameShareHost) MaxPayloadBytes() int

MaxPayloadBytes returns the host's maximum encoded payload size in bytes.

func (h *MiniGameShareHost) OnInvite(fn func(LaunchInvite)) (stop func())

OnInvite subscribes to MiniGameShareDriver.OnShow, ignoring ordinary foreground resumes that carry no query payload.

func (h *MiniGameShareHost) SetMenuCard(fn func() (PreparedCard, error))

SetMenuCard enables the mini-game Forward menu (ShowShareMenu + OnShareAppMessage) when fn is non-nil, or disables it when fn is nil.

func (h *MiniGameShareHost) Share(card PreparedCard, done func(shown bool, err error))

Share forwards card to MiniGameShareDriver.ShareAppMessage, or answers ErrShareUnavailable when driver is nil.

type MiniGameShareHostOptions struct {
	// WithShareTicket requests group-chat shareTicket delivery when enabling the share menu.
	WithShareTicket bool
	// MaxPayloadBytes overrides DefaultMaxInvitePayloadBytes (1024) when positive.
	MaxPayloadBytes int
	// FallbackMenuCard is returned to the mini-game menu if the game's SetMenuCard callback returns an invalid or oversized Card.
	FallbackMenuCard MiniGameShareCard
}

MiniGameShareHostOptions configures NewMiniGameShareHost.

type PlatformCloud struct {
	// contains filtered or unexported fields
}

PlatformCloud implements CloudSync over NSGo's package cloud: Apple iCloud ubiquity containers on macOS and iOS, Google Play Games Saved Games on Android, and an isolated per-app in-memory store in nsgotest. On platforms without a built-in OS cloud store (Windows, Linux, the web), every operation fails with ErrCloudUnavailable and never silently drops writes.

Each save slot is stored as "<Prefix><slot>.json" (default "save.<slot>.json") and validated with save.ValidateSlot. Errors wrap liveops's sentinels alongside package cloud's sentinels: ErrCloudUnavailable (cloud.ErrUnavailable), ErrSlotNotFound (cloud.ErrNotFound), and ErrCloudConflict (cloud.ErrConflict / *cloud.ConflictError).

On real Apple and Android targets (where cx.CloudStore() is nil), package cloud delivers its callbacks on cx's engine goroutine through cx.Post, so blocking CloudSync methods (Load, Save, Delete, List) must be called off the engine goroutine—such as through CloudSyncer.SyncAsync—or they would block the goroutine needed to deliver their answer. Under nsgotest (where cx.CloudStore() is non-nil), operations run directly against the per-app store and are safe from any goroutine, including synchronous CloudSyncer.Sync calls in tests.

func NewPlatformCloud(cx *core.Scope, opts PlatformCloudOptions) (*PlatformCloud, error)

NewPlatformCloud returns a PlatformCloud bound to cx, or an error if cx is nil or opts.Prefix is invalid. Call it on cx's engine goroutine with a scope that lives as long as cloud sync runs (such as the app's root scope).

func (c *PlatformCloud) Available() bool

Available reports whether platform cloud storage is reachable right now (cx.Env().CanUseCloudStorage() on a non-simulated host). Read in a reactive computation on the engine goroutine, it updates when availability changes.

func (c *PlatformCloud) Delete(ctx context.Context, slot string) error

Delete implements CloudSync. Deleting an absent slot succeeds when cloud storage is available and returns ErrCloudUnavailable when it is not.

func (c *PlatformCloud) FileName(slot string) (string, error)

FileName returns the platform cloud file or snapshot name for slot ("<Prefix><slot>.json"), or an error wrapping save.ErrInvalidSlot when slot is invalid.

func (c *PlatformCloud) List(ctx context.Context) ([]string, error)

List implements CloudSync. It lists the sorted names of valid save slots matching this PlatformCloud's prefix, ignoring other files in the cloud container.

func (c *PlatformCloud) Load(ctx context.Context, slot string) ([]byte, error)

Load implements CloudSync. It returns ErrSlotNotFound when slot does not exist, ErrCloudUnavailable when cloud storage is unavailable or cx is disposed, and ErrCloudConflict (also wrapping *cloud.ConflictError) when unresolved native platform conflicts exist.

func (c *PlatformCloud) OnConflict(resolve func(PlatformConflict)) (stop func())

OnConflict subscribes resolve to native platform version conflicts for slots matching this PlatformCloud's prefix. Notifications are delivered on cx's engine goroutine and stop automatically when stop is called or cx is disposed.

func (c *PlatformCloud) Prefix() string

Prefix returns the file-name prefix prepended to each slot name.

func (c *PlatformCloud) Provider() CloudProvider

Provider returns the built-in OS cloud-save service of the platform cx runs on (CloudProviderICloud, CloudProviderPlayGames, or CloudProviderNone), whether or not the player is signed in.

func (c *PlatformCloud) Save(ctx context.Context, slot string, data []byte) error

Save implements CloudSync. It writes data to slot and returns ErrCloudUnavailable rather than silently dropping writes when cloud storage is unavailable.

func (c *PlatformCloud) WatchChanges(onChange func(CloudChange)) (stop func())

WatchChanges subscribes onChange to external cloud-save changes for slots matching this PlatformCloud's prefix. Notifications are delivered on cx's engine goroutine and stop automatically when stop is called or cx is disposed. Account-change notifications (cloud.ChangeAccount) and container-wide initial-sync notifications are delivered even when the platform did not enumerate individual file names.

type PlatformCloudOptions struct {
	// Prefix is prepended to each slot name to form its cloud file or snapshot name ("<Prefix><slot>.json"); DefaultCloudPrefix ("save.") when empty. Must not start with '/' or '.', or contain "..", '\', "//" or control characters. Avoid '/' when targeting Android, where Google Play Games snapshot names do not accept path separators.
	Prefix string
}

PlatformCloudOptions configures NewPlatformCloud.

type PlatformConflict struct {
	// Slot is the save slot name.
	Slot string
	// Local holds the local cloud payload bytes (which may be a CloudSyncer JSON envelope decodable with DecodeCloudSave).
	Local []byte
	// Remote holds the conflicting remote cloud payload bytes.
	Remote []byte
	// LocalTime is the modification time reported for Local, if known.
	LocalTime time.Time
	// RemoteTime is the modification time reported for Remote, if known.
	RemoteTime time.Time
	// Resolve commits the winning payload bytes to platform cloud storage, clearing the native conflict.
	Resolve func(chosen []byte) error
}

PlatformConflict describes a version conflict reported by the native platform cloud backend (iCloud NSFileVersion or Google Play Games Saved Games) for one save slot.

type PlatformShareHost struct {
	// contains filtered or unexported fields
}

PlatformShareHost implements ShareHost on mobile (iOS, Android), desktop (macOS, Windows, Linux) and the web (core.OSWeb) using NSGo's core.Scope.Share, core.Scope.OnOpenLinks, core.Scope.AppURL and core.Scope.OnAppURLChange.

func NewPlatformShareHost(cx *core.Scope, opts PlatformShareHostOptions) (*PlatformShareHost, error)

NewPlatformShareHost creates a ShareHost backed by cx's native/web share sheet and link-opening hooks.

func (h *PlatformShareHost) LaunchInvite() (LaunchInvite, bool)

LaunchInvite inspects cx.AppURL() once for a cold-start invite link matching PlatformShareHostOptions.

func (h *PlatformShareHost) MaxPayloadBytes() int

MaxPayloadBytes returns the host's maximum encoded payload size in bytes.

func (h *PlatformShareHost) OnInvite(fn func(LaunchInvite)) (stop func())

OnInvite subscribes to incoming deep links (core.Scope.OnOpenLinks) and web address/hash changes (core.Scope.OnAppURLChange).

func (h *PlatformShareHost) SetMenuCard(func() (PreparedCard, error))

SetMenuCard is a no-op on native and web platforms, which have no host-managed Forward menu.

func (h *PlatformShareHost) Share(card PreparedCard, done func(shown bool, err error))

Share builds the invite link for card and presents it through core.Scope.Share (attaching card.Image when it carries image bytes, pixels or a local file path).

type PlatformShareHostOptions struct {
	// BaseURL is the invite URL prefix used to build shared invite links and match incoming links
	// (for example "mygame://invite" on mobile/desktop or "https://play.example.com/invite" on the web).
	// On core.OSWeb, when BaseURL is empty, NewPlatformShareHost derives it from cx.AppURL() by stripping its query and fragment.
	BaseURL string
	// Encoding chooses whether the invite payload is placed in the URL query ("?k=v", default) or fragment ("#k=v").
	Encoding InviteEncoding
	// AcceptFragment, when true with InviteEncodeQuery, also extracts payloads from the URL fragment when the query string is empty.
	AcceptFragment bool
	// MaxPayloadBytes overrides DefaultMaxInvitePayloadBytes (1024) when positive.
	MaxPayloadBytes int
	// FallbackToClipboard, when true, copies the formatted share text/link to the clipboard via cx.SetClipboard
	// if cx.Share reports core.CodeUnavailable (for example on desktop browsers without navigator.share).
	FallbackToClipboard bool
	// FormatText builds the share text from the card's title and formatted invite link.
	// When nil, non-empty title formats as "<title>\n<link>" and empty title formats as "<link>".
	FormatText func(title, link string) string
}

PlatformShareHostOptions configures NewPlatformShareHost for mobile, desktop and web targets over NSGo's core APIs.

type PreparedCard struct {
	// Title is the validated card title.
	Title string
	// Image is the card's image source.
	Image core.ImageSource
	// ImageID is the optional platform-reviewed image identifier.
	ImageID string
	// Query is the canonical encoded "key=value&..." payload (including id and sig when present), guaranteed to fit within the host's byte limit.
	Query string
	// Anchor is the optional popover anchor for native share sheets.
	Anchor *core.Ref
}

PreparedCard is a validated, payload-encoded card ready for a ShareHost to present.

type Purchases struct {
	// contains filtered or unexported fields
}

Purchases sells a game's in-app products over NSGo's purchase services: it credits consumables into the save exactly once, keeps unlocks and subscriptions from the store's entitlements, restores them, follows purchases waiting for approval and hands each transaction to an optional server before delivering it. Its methods run on the scope's goroutine, as NSGo's callbacks do.

func NewPurchases(cx *core.Scope, opts PurchasesOptions) *Purchases

NewPurchases starts selling with opts under cx: it registers for the store's transaction updates, which hand over unfinished transactions as the app starts, and reads the user's current entitlements. Call it as the app starts, before the first frame, so no update waits.

func (p *Purchases) Available() bool

Available reports whether this platform and build reach a store, core.Env.CanPurchase; read in a reactive computation, it follows it.

func (p *Purchases) Buy(product string, quantity int, done func(BuyResult, error))

Buy buys quantity of product (0 is 1) through the store's sheet and answers done once: Bought after the transaction is verified and delivered, BuyPending or BuyCancelled, or BuyFailed with the error. done may be nil.

func (p *Purchases) Entitlement(product string) (core.Transaction, bool)

Entitlement returns the latest transaction that gives the user product, and whether there is one, whatever its expiration date.

func (p *Purchases) Owned(product string) bool

Owned reports whether the user owns product now: a non-consumable or a subscription that is neither refunded nor past its expiration date at the scope's wall time. Read in a reactive computation, it follows purchases, refunds and restores.

func (p *Purchases) Pending(product string) bool

Pending reports whether a purchase of product waits for approval. Read in a reactive computation, it follows the approval. A request the approver declines produces no transaction, so Pending stays true until a transaction for product arrives, from a later Buy too, or the app restarts.

func (p *Purchases) Refresh(done func(error))

Refresh reads the user's current entitlements from the store and makes them what Owned reports, then answers done, which may be nil. An unlock delivered while the answer was on its way stays, unless the answer holds a later transaction for it, and one refunded meanwhile stays gone. NewPurchases calls it; call it again as the app returns to the foreground, which is also when Owned next notices a subscription that expired. An error goes to done, or to OnError when done is nil.

func (p *Purchases) Restore(done func(error))

Restore has the store bring the user's purchases up to date, which may ask them to sign in, then refreshes what Owned reports, and answers done, which may be nil: nil, or the store's error, core.PurchaseCancelled when the user declined to sign in. Call it only from a Restore Purchases button the user presses.

type PurchasesOptions struct {
	// Ledger is the game's record of credited transactions, which Save must persist along with the state Credit and Revoke change. It is required.
	Ledger *Ledger
	// Credit applies a consumable transaction to the game's state, tr.Quantity of tr.ProductID. It runs at most once per transaction ID, across runs too, as long as Save persists Ledger with that state.
	Credit func(tr core.Transaction)
	// Revoke takes back what a credited consumable gave when the store refunds or revokes it; nil keeps the credit. It runs at most once per transaction ID, as Credit does.
	Revoke func(tr core.Transaction)
	// Save persists the game's save, Ledger included, after Credit or Revoke changed it. A transaction is finished only once Save returns nil: after an error it stays unfinished, the store hands it to the app again at its next launch, and the ledger kept in memory or on disk keeps Credit from running twice. It is required for consumables.
	Save func() error
	// Verify hands tr, whose Signed is the store's JWS, to the game's server and calls done once with nil to accept it or an error to refuse it, from any goroutine. A refused transaction is neither delivered nor finished. nil accepts what the device verified, Transaction.Verified.
	Verify func(tr core.Transaction, done func(error))
	// AccountToken is the UUID of the game's own that each purchase carries to the store and the game's server, "" for none.
	AccountToken string
	// OnError hears failures that no Buy or Restore answers: a transaction from the store's updates refused, unsaved or not finished, or entitlements the store could not answer.
	OnError func(tr core.Transaction, err error)
}

PurchasesOptions configures NewPurchases.

type QuietHours struct {
	// Start is the inclusive local start time in 24-hour "HH:MM" form, such as "22:00".
	Start string `yaml:"start" schema:"required,minLength=5"`
	// End is the exclusive local end time in 24-hour "HH:MM" form, such as "08:00".
	End string `yaml:"end" schema:"required,minLength=5"`
}

QuietHours defines a daily local-time window [Start, End) during which reminders are not delivered. Any reminder that would fire inside QuietHours is deferred to End (on the same day, or the following morning when Start is later than End).

func (q *QuietHours) Clone() *QuietHours

Clone returns a copy of q, or nil when q is nil.

func (q QuietHours) Contains(t time.Time) bool

Contains reports whether t falls inside q's local-time window [Start, End). Returns false if q is not valid.

func (q QuietHours) NextAllowed(t time.Time) time.Time

NextAllowed returns t if t is outside QuietHours, or the local time when QuietHours ends otherwise. If q is not valid, t is returned unchanged.

func (q QuietHours) Validate() error

Validate checks that q has well-formed, distinct Start and End wall-clock times.

type ReminderDef struct {
	// ID uniquely names the reminder: 1 to 128 ASCII letters, digits, '.', '_' or '-'.
	ID string `yaml:"id" schema:"required,minLength=1"`
	// Title is the localization key for the notification title.
	Title string `yaml:"title" schema:"required,minLength=1"`
	// Body is the optional localization key for the notification body.
	Body string `yaml:"body,omitempty"`
	// Delay schedules the reminder this positive Go duration after Schedule is called, such as "4h0m0s" or "30m0s". Mutually exclusive with At.
	Delay time.Duration `yaml:"delay,omitempty"`
	// At schedules the reminder at the next occurrence of this 24-hour local wall-clock time ("HH:MM"), such as "09:00". Mutually exclusive with Delay.
	At string `yaml:"at,omitempty"`
	// Weekday restricts an At-based reminder to a specific day of the week (sunday through saturday); requires At and cannot be paired with daily repeat.
	Weekday string `yaml:"weekday,omitempty" schema:"enum=sunday|monday|tuesday|wednesday|thursday|friday|saturday"`
	// Repeat sets how often the reminder repeats after its first firing: omitted for once, "daily", or "weekly".
	Repeat ReminderRepeat `yaml:"repeat,omitempty" schema:"enum=daily|weekly"`
	// OnOpen controls what happens to this reminder when the app comes to the front: "cancel" (default when omitted), "reschedule", or "keep".
	OnOpen ReminderOnOpen `yaml:"onOpen,omitempty" schema:"enum=cancel|reschedule|keep"`
	// Silent delivers the notification without the system's sound or vibration.
	Silent bool `yaml:"silent,omitempty"`
}

ReminderDef declares one local re-engagement reminder in a RemindersConfig file.

func (d ReminderDef) EffectiveOnOpen() ReminderOnOpen

EffectiveOnOpen returns d.OnOpen, defaulting to ReminderOnOpenCancel when omitted.

type ReminderOnOpen string

ReminderOnOpen controls what happens to a scheduled reminder when the app launches or returns to the foreground.

const (
	// ReminderOnOpenCancel cancels the pending reminder when the app comes to the front (the default when omitted).
	ReminderOnOpenCancel ReminderOnOpen = "cancel"
	// ReminderOnOpenReschedule reschedules the reminder from the current wall time when the app comes to the front.
	ReminderOnOpenReschedule ReminderOnOpen = "reschedule"
	// ReminderOnOpenKeep leaves the pending reminder scheduled unchanged when the app comes to the front.
	ReminderOnOpenKeep ReminderOnOpen = "keep"
)
func (o ReminderOnOpen) Valid() bool

Valid reports whether o is a supported ReminderOnOpen value (empty, cancel, reschedule, or keep).

type ReminderPress struct {
	// ID is the reminder's ID from RemindersConfig (without RemindersOptions.Prefix).
	ID string
}

ReminderPress is the event reported to RemindersOptions.OnPress when the player presses a delivered reminder notification.

type ReminderRepeat string

ReminderRepeat describes how often a scheduled reminder fires.

const (
	// ReminderRepeatNone fires the reminder once.
	ReminderRepeatNone ReminderRepeat = ""
	// ReminderRepeatDaily fires the reminder every day at its scheduled local wall-clock time.
	ReminderRepeatDaily ReminderRepeat = "daily"
	// ReminderRepeatWeekly fires the reminder every week on its scheduled weekday and local wall-clock time.
	ReminderRepeatWeekly ReminderRepeat = "weekly"
)
func (r ReminderRepeat) Valid() bool

Valid reports whether r is a supported ReminderRepeat value (empty, daily, or weekly).

type Reminders struct {
	// contains filtered or unexported fields
}

Reminders schedules, cancels and reschedules local re-engagement notifications over NSGo's core.Scope.ShowNotification.

Reminders never asks for notification permission at launch: it requests permission only when the game first calls Schedule (or ScheduleWith) or an explicit RequestPermission. It honors a persisted player toggle (Enabled/SetEnabled), local-time QuietHours, and each reminder's OnOpen rule (cancel, reschedule or keep) when the app comes to the front.

Remote push notifications are not part of Reminders and are unavailable everywhere until NSGo ships remote push (nsgo-dev/nsgo#59, nsgo-dev/nsgo#1323).

Reminders methods run on the scope's goroutine, as NSGo's callbacks do.

func NewReminders(cx *core.Scope, opts RemindersOptions) (*Reminders, error)

NewReminders creates a local reminder manager bound to cx. It never prompts for or queries notification permission at launch; it loads persisted player settings and reconciles any previously scheduled reminders with their OnOpen rules when the app starts in the foreground.

func (r *Reminders) CanScheduleNotifications() bool

CanScheduleNotifications reports whether this platform schedules local notifications (core.Env.CanScheduleNotifications). Read in a reactive computation, it follows environment changes so games can hide reminder settings where scheduled notifications do nothing.

func (r *Reminders) Cancel(id string)

Cancel cancels the scheduled or shown notification for id and stops any in-flight Schedule call for id.

func (r *Reminders) CancelAll()

CancelAll cancels every scheduled or shown reminder notification tracked by Reminders or declared in RemindersConfig, and stops any in-flight Schedule calls. Unrelated notifications belonging to other parts of the app are left untouched.

func (r *Reminders) Definition(id string) (ReminderDef, bool)

Definition returns the declared ReminderDef for id.

func (r *Reminders) Enabled() bool

Enabled reports whether the player's in-game reminder setting is turned on. Read in a reactive computation, it follows SetEnabled.

func (r *Reminders) IsScheduled(id string) bool

IsScheduled reports whether id is currently scheduled (and, for a one-shot reminder scheduled in this run, still in the future). Read in a reactive computation, it follows Schedule, Cancel, CancelAll and foreground reconciliation.

func (r *Reminders) NextFireTime(id string) (time.Time, bool)

NextFireTime returns the scheduled wall-clock fire time for id when scheduled during this run. Read in a reactive computation, it follows Schedule, Cancel, SetQuietHours and foreground reconciliation.

func (r *Reminders) Permission() core.NotificationPermission

Permission returns the last notification permission status observed by RequestPermission or Schedule. It starts at core.NotificationsNotAsked without querying the OS at launch. Read in a reactive computation, it updates when permission changes.

func (r *Reminders) QuietHours() *QuietHours

QuietHours returns a copy of the active local-time quiet hours window, or nil when quiet hours are disabled. Read in a reactive computation, it follows SetQuietHours.

func (r *Reminders) RequestPermission(done func(core.NotificationPermission))

RequestPermission explicitly asks the OS for notification permission through core.Scope.RequestNotificationPermission and answers done with the result. Concurrent calls share a single permission request. done may be nil.

func (r *Reminders) Schedule(id string, done func(scheduled bool)) error

Schedule schedules the declared reminder named id according to its YAML definition and the active QuietHours, answering done (when non-nil) with whether the platform accepted it.

When reminders are disabled by the player or CanScheduleNotifications is false, Schedule answers false without asking for permission. Otherwise, if notification permission has not yet been granted, Schedule requests it first and schedules only when granted. Returns ErrReminderNotFound (without calling done) if id is not declared in RemindersConfig.

func (r *Reminders) ScheduleWith(id string, opts ScheduleOptions, done func(scheduled bool)) error

ScheduleWith schedules the declared reminder named id with per-call overrides in opts. Returns ErrReminderNotFound or ErrInvalidSchedule (without calling done) when the arguments are invalid.

func (r *Reminders) Scheduled() []string

Scheduled returns the sorted IDs of all currently scheduled reminders. Read in a reactive computation, it follows Schedule, Cancel, CancelAll and foreground reconciliation.

func (r *Reminders) SetEnabled(enabled bool) error

SetEnabled persists the player's reminder setting. Disabling immediately cancels all scheduled reminders and prevents future Schedule calls from prompting or scheduling.

func (r *Reminders) SetQuietHours(qh *QuietHours) error

SetQuietHours updates and persists the player's quiet-hours window (nil disables quiet hours even when RemindersConfig defines defaults). Any currently scheduled reminder whose known fire time falls inside the new window is immediately deferred to the window's end without prompting for permission.

type RemindersConfig struct {
	// Version is the schema version; it must equal RemindersVersion (1).
	Version int `yaml:"version" schema:"required"`
	// QuietHours is the optional default daily local-time window during which reminders are deferred until the window ends.
	QuietHours *QuietHours `yaml:"quietHours,omitempty"`
	// Reminders lists the game's local re-engagement reminder definitions in declaration order.
	Reminders []ReminderDef `yaml:"reminders,omitempty"`
}

RemindersConfig is the root of a versioned YAML reminders file (reminders.yaml).

func LoadRemindersFS(fsys fs.FS, name string) (*RemindersConfig, error)

LoadRemindersFS reads name from fsys and parses it with ParseReminders.

func ParseReminders(data []byte) (*RemindersConfig, error)

ParseReminders decodes and validates a versioned YAML reminders document. Unknown fields, trailing YAML documents, duplicate keys, YAML anchors/aliases/merge keys, missing or unsupported versions, and invalid schedules or quiet hours are refused with *loaderr.Error line info.

func (c *RemindersConfig) Clone() *RemindersConfig

Clone returns a deep copy of c.

func (c *RemindersConfig) Lookup(id string) (ReminderDef, bool)

Lookup returns the reminder definition with ID id.

type RemindersOptions struct {
	// Config holds the game's declared reminders and optional default quiet hours (loaded with ParseReminders or LoadRemindersFS).
	Config *RemindersConfig
	// Localize resolves a reminder's Title and Body localization keys into display text.
	// When nil, keys are used as written.
	Localize func(key string) string
	// Storage persists the player's enabled toggle, custom quiet hours and active reminder IDs across runs.
	// When zero, cx.Storage() is used.
	Storage core.Storage
	// StorageKey is the prefix for keys written to Storage; DefaultRemindersKey is used when empty.
	StorageKey string
	// QuietHours overrides Config.QuietHours as the default quiet-hours window when the player has not saved a custom window.
	QuietHours *QuietHours
	// DefaultDisabled makes reminders start disabled until the player enables them with SetEnabled(true).
	DefaultDisabled bool
	// Prefix is prepended to reminder IDs passed to core.Scope.ShowNotification; DefaultReminderPrefix is used when empty.
	Prefix string
	// OnPress runs when the player presses a delivered reminder notification.
	OnPress func(ReminderPress)
}

RemindersOptions configures NewReminders.

type ReviewMoment int

ReviewMoment classifies an in-game outcome reported to ReviewPrompt.Moment.

const (
	// MomentPositive records a rewarding event such as clearing a level or setting a personal record.
	MomentPositive ReviewMoment = iota + 1
	// MomentNegative records a frustrating event such as losing a level, failing a purchase or hitting an error.
	// Recording a negative moment suppresses review prompts for the rest of the current session.
	MomentNegative
)
func (m ReviewMoment) String() string

String returns "positive", "negative" or "unknown".

type ReviewPrompt struct {
	// contains filtered or unexported fields
}

ReviewPrompt decides when to call core.Scope.RequestReview using persisted session, elapsed-day, positive-moment, cooldown and once-per-version rules.

State is stored in core.Storage as strict versioned JSON text and fails closed on any corrupt, unrecognised or future-version payload without overwriting it. On platforms where core.Env.CanRequestReview is false, MaybeAsk is a no-op returning false so a game can call it unconditionally.

func NewReviewPrompt(store core.Storage, opts ReviewPromptOptions) *ReviewPrompt

NewReviewPrompt creates a review prompt policy backed by store and records the start of a new session. If store is the zero core.Storage, or if the persisted JSON state is corrupt or unrecognised, the policy fails closed and MaybeAsk never prompts.

func (r *ReviewPrompt) Eligible() bool

Eligible reports whether all policy rules currently allow asking for a review (independent of whether the platform supports core.Scope.RequestReview). It returns false on corrupt state, after a negative moment in the current session, while suppressed, or before thresholds and cooldown are satisfied.

func (r *ReviewPrompt) MaybeAsk(cx *core.Scope) bool

MaybeAsk requests an in-app store rating through cx.RequestReview when the platform supports it (cx.Env().CanRequestReview()) and all policy rules allow it, returning whether it asked.

On platforms without a store prompt, MaybeAsk is a no-op returning false without modifying state. When asking, ReviewPrompt persists the prompt timestamp and version before calling cx.RequestReview so a storage failure fails closed and never causes repeated prompts.

func (r *ReviewPrompt) Moment(kind ReviewMoment)

Moment records a positive or negative gameplay moment. MomentPositive increments the current version's positive-moment counter in storage. MomentNegative suppresses prompts for the remainder of the current session. Unrecognised moment values are ignored.

func (r *ReviewPrompt) RecordSession()

RecordSession starts a new session on an existing ReviewPrompt (for example when a mobile app returns to the foreground after a long pause), clearing any session-scoped negative moment suppression and incrementing the persisted session count.

type ReviewPromptOptions struct {
	// AppVersion is the current release version (for example project.File.AppVersion).
	// ReviewPrompt asks at most once per AppVersion and resets per-version positive moments when AppVersion changes so a new release earns fresh engagement before asking again.
	AppVersion string

	// StorageKey is the core.Storage key holding the versioned JSON state.
	// DefaultReviewPromptKey is used when empty.
	StorageKey string

	// MinSessions is the minimum number of sessions before MaybeAsk may prompt.
	// Values <= 0 use DefaultReviewMinSessions (3). Stores advise against prompting in the first session.
	MinSessions int

	// MinDays is the minimum number of whole 24-hour days since first launch before MaybeAsk may prompt.
	// Values <= 0 use DefaultReviewMinDays (3).
	MinDays int

	// MinPositiveMoments is the minimum number of positive moments recorded in the current AppVersion before MaybeAsk may prompt.
	// Values <= 0 use DefaultReviewMinPositiveMoments (3).
	MinPositiveMoments int

	// Cooldown is the minimum time between store review requests across all app versions.
	// Values <= 0 use DefaultReviewCooldown (122 days).
	Cooldown time.Duration

	// Now returns the current wall-clock time; time.Now is used when nil.
	// Pass cx.WallTime in NSGo apps so nsgotest.WallTime and app.FastForward control the clock.
	Now func() time.Time

	// Suppress, when non-nil and returning true, prevents MaybeAsk from requesting a review
	// (for example while a purchase sheet, ad flow or modal dialog is open).
	Suppress func() bool
}

ReviewPromptOptions configures NewReviewPrompt.

type SaveVersion struct {
	// Exists is false when this side deleted the slot; the other fields are then zero.
	Exists bool
	// Revision is the cloud revision: the cloud copy's own, or for the local copy the revision it was last synced at (0 when never synced).
	Revision int64
	// Hash is "sha256:" followed by the hex SHA-256 of Data.
	Hash string
	// Modified is when the copy was last written, zero when unknown (a local write that bypassed CloudSyncer.Backend, or a plain cloud payload). A local time counts only for the exact copy it was recorded with: a later write that bypassed Backend makes it unknown.
	Modified time.Time
	// Device is the ID of the device that wrote the copy, empty when unknown.
	Device string
	// EnvelopeVersion is the save.Store schema version parsed from Data's save envelope, or 0 when Data is absent or not a save envelope.
	EnvelopeVersion int
	// Summary is CloudSyncOptions.Summarize's text for Data, such as "Level 12, 3h 40m played".
	Summary string
	// Data is the raw save payload.
	Data []byte
}

SaveVersion describes one side's copy of a slot in a Conflict or a SlotResult.

func DecodeCloudSave(raw []byte) (SaveVersion, error)

DecodeCloudSave reads a cloud payload. A JSON object whose "format" is CloudSaveFormat is decoded strictly (unknown fields, a newer version, a revision below 1 or at math.MaxInt64, a hash that does not match the data or a malformed value return an error wrapping ErrCorruptCloudSave); any other payload is a plain save written without CloudSyncer and is returned as revision 0 with no modified time or device.

type ScheduleOptions struct {
	// Delay, when positive, overrides the reminder's declared Delay or At with a relative delay from now. Mutually exclusive with At.
	Delay time.Duration
	// At, when non-zero, overrides the reminder's declared Delay or At with a specific wall-clock time. Mutually exclusive with Delay.
	At time.Time
	// Title, when non-empty, overrides the localized title for this scheduled reminder (for example when interpolating parameters with l10n).
	Title string
	// Body, when non-empty, overrides the localized body for this scheduled reminder.
	Body string
}

ScheduleOptions overrides parts of a declared ReminderDef for a single ScheduleWith call.

type ShareHost interface {
	// MaxPayloadBytes returns the maximum allowed byte length of PreparedCard.Query.
	// Returning <= 0 uses DefaultMaxInvitePayloadBytes (1024).
	MaxPayloadBytes() int

	// Share presents the platform share card or system share sheet for card and invokes done when complete.
	Share(card PreparedCard, done func(shown bool, err error))

	// SetMenuCard registers a callback supplying the card for the host's built-in share menu (such as a mini game's Forward item).
	// Passing nil disables/clears the menu card. Hosts without a system share menu treat this as a no-op.
	SetMenuCard(fn func() (PreparedCard, error))

	// LaunchInvite returns the invite that cold-started the game, if any.
	LaunchInvite() (LaunchInvite, bool)

	// OnInvite subscribes fn to invites that arrive while the game is running (warm re-open / onShow) and returns an unsubscribe function.
	OnInvite(fn func(LaunchInvite)) (stop func())
}

ShareHost is the small platform boundary underneath Invites. Built-in implementations are PlatformShareHost (mobile, desktop and web over NSGo's core APIs) and MiniGameShareHost (mini-game bridge ready for nsgo-dev/nsgo#2672); tests supply a fake ShareHost.

type SlotResult struct {
	// Slot is the save slot name.
	Slot string
	// Outcome is what was done.
	Outcome SyncOutcome
	// Conflict is set when both copies had changed, whatever the outcome.
	Conflict *Conflict
	// Fork is the slot the local copy was moved to under OutcomeKeptBoth, or under OutcomeNeedsUpdate when a mixed-version conflict forked the local copy without overwriting the local slot.
	Fork string
	// Discarded is the copy a resolution replaced under OutcomeKeptLocal or OutcomeKeptCloud, so a game can show or archive it.
	Discarded *SaveVersion
	// LocalVersion is this client's configured CloudSyncOptions.SaveVersion when Outcome is OutcomeNeedsUpdate, and 0 otherwise.
	LocalVersion int
	// CloudVersion is the cloud copy's save envelope version when Outcome is OutcomeNeedsUpdate, and 0 otherwise.
	CloudVersion int
}

SlotResult reports what a sync did to one slot.

type StepRecord = crashreport.StepRecord

StepRecord describes one recorded step in a CrashReporter's fixed-size ring buffer. It is an alias for crashreport.StepRecord, so headless servers build the same schema without importing liveops.

type SyncOutcome int

SyncOutcome says what CloudSyncer did to one slot.

const (
	// OutcomeUpToDate means both sides already held the same copy.
	OutcomeUpToDate SyncOutcome = iota
	// OutcomeUploaded means only the local copy had changed, and it was uploaded.
	OutcomeUploaded
	// OutcomeDownloaded means only the cloud copy had changed, and it was written locally.
	OutcomeDownloaded
	// OutcomeDeletedCloud means the slot was deleted locally and unchanged in the cloud, so the cloud copy was deleted.
	OutcomeDeletedCloud
	// OutcomeDeletedLocal means the slot was deleted in the cloud and unchanged locally, so the local copy was deleted.
	OutcomeDeletedLocal
	// OutcomeKeptLocal means a conflict was resolved in favour of the local copy; SlotResult.Discarded holds the cloud copy it replaced.
	OutcomeKeptLocal
	// OutcomeKeptCloud means a conflict was resolved in favour of the cloud copy; SlotResult.Discarded holds the local copy it replaced. When that copy was a valid save envelope and the cloud copy exists, the local save backend also keeps it as its backup; otherwise Discarded is the only copy left.
	OutcomeKeptCloud
	// OutcomeKeptBoth means a conflict was resolved by keeping the cloud copy in the slot and moving the local copy to SlotResult.Fork on both sides.
	OutcomeKeptBoth
	// OutcomeDeferred means a conflict was left unresolved, by ChoiceDefer under PolicyAsk or passed to CloudSyncer.Resolve; nothing was written.
	OutcomeDeferred
	// OutcomeNeedsUpdate means the cloud copy carries a save envelope version newer than CloudSyncOptions.SaveVersion, so it was not written locally; SlotResult.LocalVersion and SlotResult.CloudVersion report both versions so the game can ask the player to update. When a mixed-version conflict forked an older local copy to preserve it without overwriting either slot, SlotResult.Fork names the fork slot.
	OutcomeNeedsUpdate
)
func (o SyncOutcome) String() string

String returns a lowercase, hyphenated name such as "up-to-date" or "kept-both".

type SyncResult struct {
	// Slots holds one entry for each slot that synced without error.
	Slots []SlotResult
}

SyncResult reports what CloudSyncer.Sync did to each slot, sorted by slot name.

func (r SyncResult) Conflicts() []SlotResult

Conflicts returns the slot results that held a conflict.

func (r SyncResult) NeedsUpdate() []SlotResult

NeedsUpdate returns the slot results whose cloud copy carries a newer save envelope version than CloudSyncOptions.SaveVersion.