Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 39 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,15 @@ late final PersonalizationSdk sdk;
void main() {
WidgetsFlutterBinding.ensureInitialized();

sdk = Rees46.initialize(
const Rees46Config(shopId: 'YOUR_SHOP_ID'),
sdk = REES46.initialize(
const REES46Config(shopId: 'YOUR_SHOP_ID'),
);

runApp(const MyApp());
}
```

`Rees46` is the entry point. `Rees46.initialize` **returns the handle
`REES46` is the entry point. `REES46.initialize` **returns the handle
synchronously** and starts native initialization in the background; calls issued
right after are queued natively until the session is ready, so the handle is
usable straight away. A broken setup surfaces as a `PlatformException` on the
Expand All @@ -99,12 +99,12 @@ there is simply no token to send.
Keep one place that owns the handle, so no widget re-initializes:

```dart
class Rees46Service {
class REES46Service {
static const _shopId = 'YOUR_SHOP_ID';

static PersonalizationSdk get sdk => Rees46.isInitialized(_shopId)
? Rees46.getInstance(_shopId)
: Rees46.initialize(const Rees46Config(shopId: _shopId));
static PersonalizationSdk get sdk => REES46.isInitialized(_shopId)
? REES46.getInstance(_shopId)
: REES46.initialize(const REES46Config(shopId: _shopId));
}
```

Expand All @@ -124,12 +124,12 @@ Each gets its own native instance with isolated storage, session and `did`.

```dart
// Registered now, initialized on first use.
Rees46.registerShops(const [
Rees46Config(shopId: 'shop-a'),
Rees46Config(shopId: 'shop-b'),
REES46.registerShops(const [
REES46Config(shopId: 'shop-a'),
REES46Config(shopId: 'shop-b'),
]); // pass eagerInit: true to initialize up front

final shopA = Rees46.getInstance('shop-a');
final shopA = REES46.getInstance('shop-a');
```

Address instances explicitly once more than one is registered: `getInstance()`
Expand All @@ -154,7 +154,7 @@ Awaiting is optional — fire-and-forget from UI code is fine.
With several shops the namespace follows the instance:

```dart
await Rees46.getInstance('shop-b').tracking.productView('sku-1');
await REES46.getInstance('shop-b').tracking.productView('sku-1');
```

### Catalog
Expand Down Expand Up @@ -202,8 +202,10 @@ await sdk.tracking.syncFavorites(const ['sku-1', 'sku-2']);
await sdk.tracking.removeFromFavorites('sku-1');
```

`syncCart` and `syncFavorites` reject an empty list with an `ArgumentError` —
drop the last item through `removeFromCart` / `removeFromFavorites` instead.
An empty list is how an emptied cart or wishlist is reported: `items` goes on
the wire as `[]` alongside `full_cart` / `full_wish`, which is what the native
SDKs send. Removing a single product is still `removeFromCart` /
`removeFromFavorites`.

### Stories

Expand Down Expand Up @@ -289,39 +291,41 @@ duplicated under `payload`. The SDK's own keys are reserved and rejected —

### Attribution

Events can carry the tool the user came from. Per call, for one event:
Events can carry the campaign the user arrived from — a bulk mobile push, a
chain. Both values come from the link that opened the app, which carries them as
`recommended_by` and `recommended_code`:

```dart
await sdk.tracking.productView(
'sku-1',
source: const TrackingSource(
type: TrackingSourceType.dynamicBlock,
code: 'main_page_block',
),
);
```
myshop://product/sku-1?recommended_by=bulk&recommended_code=jkIWdXSRfwVyK
```

`source` is accepted by `productView`, `addToCart` and `addToFavorites` — the
events a recommendation leads to.

Or stored once, for the events that follow — the case where the source outlives
a single call, such as a user entering the catalog from a recommender block:
A campaign brings the user in and then colours everything they do next, so store
it once when you handle the link:

```dart
await sdk.tracking.setSource(
const TrackingSource(
type: TrackingSourceType.dynamicBlock,
code: 'main_page_block',
),
const TrackingSource(type: TrackingSourceType.bulk, code: 'jkIWdXSRfwVyK'),
);

// Carries source=main_page_block without being told to.
// Carries recommended_by=bulk without being told to.
await sdk.tracking.productView('sku-1');
```

The stored source lives natively per shop, survives restarts, and is kept for 48
hours or until it is replaced. A per-call `source` wins over the stored one, and
an order is attributed by the `recommendedSource` of the `purchase` call itself.
hours or until it is replaced.

To attribute a single event instead of everything that follows, pass `source` per
call — `productView`, `addToCart` and `addToFavorites` accept it:

```dart
await sdk.tracking.addToCart(
const TrackingItem(id: 'sku-1', quantity: 1),
source: const TrackingSource(type: TrackingSourceType.chain, code: 'welcome_2'),
);
```

A per-call `source` wins over the stored one, and an order is attributed by the
`recommendedSource` of the `purchase` call itself.

| `TrackingSourceType` | Wire value | Set by |
|---|---|---|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ interface PersonalizationHostApi {
fun getCollection(collectionId: String, shopId: String?, callback: (Result<String>) -> Unit)
/**
* Routes a push to the shop it belongs to (payload `shop_id`) and tracks it
* via the native `Rees46.handlePush`. [event] is the index of the Dart
* via the native `REES46.handlePush`. [event] is the index of the Dart
* `PushEvent` enum: 0 = received, 1 = delivered, 2 = clicked. The native side
* maps it to its own vocabulary (Android `PushEventType`, iOS `PushEvent`).
*/
Expand Down
10 changes: 5 additions & 5 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -136,10 +136,10 @@ final List<_TrackingDemo> _trackingDemos = [
];

class _InitPageState extends State<InitPage> {
// Initialized through the multi-instance [Rees46] facade — the same entry
// Initialized through the multi-instance [REES46] facade — the same entry
// point the iOS/Android demos use — so shop A is registered in the facade and
// the Multi-instance screen reaches the very same instance via
// Rees46.getInstance(shopId). Bound to shop A explicitly, so every call stays
// REES46.getInstance(shopId). Bound to shop A explicitly, so every call stays
// unambiguous even after that screen brings a second shop to life. Assigned in
// [_initialize] (rebuilt on re-initialize).
late PersonalizationSdk _sdk;
Expand Down Expand Up @@ -288,10 +288,10 @@ class _InitPageState extends State<InitPage> {
// Initialize shop A through the multi-instance facade — the unified entry
// point, same as iOS/Android. Returns the handle and registers the shop,
// so the Multi-instance screen resolves the very same instance via
// Rees46.getInstance(shopId). Re-initializing rebuilds the handle with the
// REES46.getInstance(shopId). Re-initializing rebuilds the handle with the
// current toggles.
_sdk = Rees46.initialize(
Rees46Config(
_sdk = REES46.initialize(
REES46Config(
shopId: _shopId,
apiDomain: _apiDomain,
stream: _stream,
Expand Down
28 changes: 14 additions & 14 deletions example/lib/multi_instance_pane.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import 'package:rees46_sdk/rees46_sdk.dart';
/// default; shop B is registered lazily and comes to life the moment this screen
/// resolves it. Everything each instance sends carries its own `shop_id`/`did`,
/// so the two session cards (did/sid) are the in-app proof of isolation. Also
/// exercises the fail-fast resolution contract and `Rees46.handlePush` routing.
/// exercises the fail-fast resolution contract and `REES46.handlePush` routing.
///
/// (The native demos also show per-shop Stories; the Flutter SDK exposes no
/// stories widget, so that part is omitted here.)
Expand Down Expand Up @@ -42,20 +42,20 @@ class _MultiInstancePaneState extends State<MultiInstancePane> {
super.initState();

// Shop A — eager default.
_shopA = Rees46.isInitialized(MultiInstancePane.shopIdA)
? Rees46.getInstance(MultiInstancePane.shopIdA)
: Rees46.initialize(
const Rees46Config(shopId: MultiInstancePane.shopIdA),
_shopA = REES46.isInitialized(MultiInstancePane.shopIdA)
? REES46.getInstance(MultiInstancePane.shopIdA)
: REES46.initialize(
const REES46Config(shopId: MultiInstancePane.shopIdA),
);

// Shop B — registered lazily, then materialized right here by resolving it.
if (!Rees46.isInitialized(MultiInstancePane.shopIdB) &&
!Rees46.pendingShopIds.contains(MultiInstancePane.shopIdB)) {
Rees46.registerShops(const [
Rees46Config(shopId: MultiInstancePane.shopIdB),
if (!REES46.isInitialized(MultiInstancePane.shopIdB) &&
!REES46.pendingShopIds.contains(MultiInstancePane.shopIdB)) {
REES46.registerShops(const [
REES46Config(shopId: MultiInstancePane.shopIdB),
]);
}
_shopB = Rees46.getInstance(MultiInstancePane.shopIdB); // B is born here
_shopB = REES46.getInstance(MultiInstancePane.shopIdB); // B is born here

_shopA.setPushNotificationCallbacks(
onReceived: (p) => _addLog('✓ shop A onReceived: ${_pushLabel(p)}'),
Expand Down Expand Up @@ -125,7 +125,7 @@ class _MultiInstancePaneState extends State<MultiInstancePane> {
'title': note,
'body': note,
};
final routed = await Rees46.handlePush(payload, PushEvent.received);
final routed = await REES46.handlePush(payload, PushEvent.received);
final result = routed != null ? 'routed:$routed' : 'dropped';
setState(() => _lastPushResult = result);
_addLog('injected shop_id=${shopId ?? '—'} → $result');
Expand Down Expand Up @@ -180,13 +180,13 @@ class _MultiInstancePaneState extends State<MultiInstancePane> {
children: [
ElevatedButton(
onPressed: () =>
_runContract('getInstance()', () => Rees46.getInstance()),
_runContract('getInstance()', () => REES46.getInstance()),
child: const Text('getInstance() → Ambiguous'),
),
ElevatedButton(
onPressed: () => _runContract(
'getInstance("nope")',
() => Rees46.getInstance('nope'),
() => REES46.getInstance('nope'),
),
child: const Text('getInstance("nope") → Unknown'),
),
Expand All @@ -200,7 +200,7 @@ class _MultiInstancePaneState extends State<MultiInstancePane> {

const SizedBox(height: 16),
const Text(
'Push routing (Rees46.handlePush)',
'Push routing (REES46.handlePush)',
style: TextStyle(fontWeight: FontWeight.bold),
),
Wrap(
Expand Down
4 changes: 2 additions & 2 deletions ios/Classes/pigeon/PersonalizationApi.g.swift
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ protocol PersonalizationHostApi {
/// Dart layer parses the result into [CollectionResponse].
func getCollection(collectionId: String, shopId: String?, completion: @escaping (Result<String, Error>) -> Void)
/// Routes a push to the shop it belongs to (payload `shop_id`) and tracks it
/// via the native `Rees46.handlePush`. [event] is the index of the Dart
/// via the native `REES46.handlePush`. [event] is the index of the Dart
/// `PushEvent` enum: 0 = received, 1 = delivered, 2 = clicked. The native side
/// maps it to its own vocabulary (Android `PushEventType`, iOS `PushEvent`).
func handlePush(payload: [String: String], event: Int64, completion: @escaping (Result<Void, Error>) -> Void)
Expand Down Expand Up @@ -935,7 +935,7 @@ class PersonalizationHostApiSetup {
getCollectionChannel.setMessageHandler(nil)
}
/// Routes a push to the shop it belongs to (payload `shop_id`) and tracks it
/// via the native `Rees46.handlePush`. [event] is the index of the Dart
/// via the native `REES46.handlePush`. [event] is the index of the Dart
/// `PushEvent` enum: 0 = received, 1 = delivered, 2 = clicked. The native side
/// maps it to its own vocabulary (Android `PushEventType`, iOS `PushEvent`).
let handlePushChannel = FlutterBasicMessageChannel(name: "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.handlePush\(channelSuffix)", binaryMessenger: binaryMessenger, codec: codec)
Expand Down
2 changes: 1 addition & 1 deletion lib/src/multi_instance/instance_resolver.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/// Pure decision logic behind [Rees46.getInstance]: given the requested `shopId`
/// Pure decision logic behind [REES46.getInstance]: given the requested `shopId`
/// (or none) and the sets of live and pending shops, decides which instance to
/// return, whether one must be lazily materialized, or which error to raise.
///
Expand Down
2 changes: 1 addition & 1 deletion lib/src/multi_instance/push_event.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/// Push lifecycle event routed by [Rees46.handlePush].
/// Push lifecycle event routed by [REES46.handlePush].
///
/// The Flutter vocabulary — `received` / `delivered` / `clicked` — matches the
/// SDK's existing push callbacks. Native maps it to its own set: Android
Expand Down
36 changes: 18 additions & 18 deletions lib/src/multi_instance/rees46.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import 'sdk_exceptions.dart';

/// Builds and initializes a [PersonalizationSdk] handle for [config]. Injectable
/// so tests can resolve shops without touching native or Pigeon.
typedef Rees46SdkFactory = PersonalizationSdk Function(Rees46Config config);
typedef REES46SdkFactory = PersonalizationSdk Function(REES46Config config);

/// Public entry point for the Flutter SDK — the unified, multi-instance API.
///
Expand All @@ -18,12 +18,12 @@ typedef Rees46SdkFactory = PersonalizationSdk Function(Rees46Config config);
///
/// ```dart
/// // Single shop:
/// final sdk = Rees46.initialize(Rees46Config(shopId: 'SHOP_ID'));
/// final sdk = REES46.initialize(REES46Config(shopId: 'SHOP_ID'));
/// sdk.trackEvent('category', ...);
///
/// // Several shops, initialized lazily on first use:
/// Rees46.registerShops([Rees46Config(shopId: 'shop-a'), Rees46Config(shopId: 'shop-b')]);
/// Rees46.getInstance('shop-a').trackEvent('category', ...);
/// REES46.registerShops([REES46Config(shopId: 'shop-a'), REES46Config(shopId: 'shop-b')]);
/// REES46.getInstance('shop-a').trackEvent('category', ...);
/// ```
///
/// ## Why the facade holds a shop-id mirror
Expand All @@ -37,29 +37,29 @@ typedef Rees46SdkFactory = PersonalizationSdk Function(Rees46Config config);
/// remains the source of truth for the instances themselves.
///
/// Per-call routing to a specific native instance (threading `shopId` through
/// every Pigeon call) lands once the native `Rees46` facade ships in the
/// every Pigeon call) lands once the native `REES46` facade ships in the
/// consumed artifacts — see the plan (`Multi-instance — Flutter Plan`, step F3).
/// Until then single-shop [initialize] is fully functional and the resolution
/// contract below is complete and tested.
class Rees46 {
Rees46._();
class REES46 {
REES46._();

static final Rees46 _instance = Rees46._();
static final REES46 _instance = REES46._();

/// Live (initialized) instances by shop id. The Dart-side mirror of the
/// native registry — used for resolution only.
final Map<String, PersonalizationSdk> _live = <String, PersonalizationSdk>{};

/// Shops registered lazily and not yet initialized. Materialized on the first
/// [getInstance] for the shop.
final Map<String, Rees46Config> _pending = <String, Rees46Config>{};
final Map<String, REES46Config> _pending = <String, REES46Config>{};

Rees46SdkFactory _factory = _defaultFactory;
REES46SdkFactory _factory = _defaultFactory;

static PersonalizationSdk _defaultFactory(Rees46Config config) {
static PersonalizationSdk _defaultFactory(REES46Config config) {
final sdk = PersonalizationSdk(shopId: config.shopId);
// F1: delegates to the existing single-shop native init. Per-call `shopId`
// routing to the native `Rees46` facade lands in plan step F3.
// routing to the native `REES46` facade lands in plan step F3.
sdk.initialize(config.toSdkInitConfig());
return sdk;
}
Expand All @@ -71,15 +71,15 @@ class Rees46 {
/// Initializes an SDK instance for [config] immediately and returns it. The
/// instance is registered, so it is also reachable via [getInstance]. Any
/// pending registration for the same shop is cleared.
static PersonalizationSdk initialize(Rees46Config config) =>
static PersonalizationSdk initialize(REES46Config config) =>
_instance._initialize(config);

/// Registers [configs] without initializing them. Initialization happens
/// lazily on the first [getInstance] for a shop — the region case, where only
/// the current region is needed. Pass [eagerInit] = true to initialize every
/// shop up front — the super-shop case, where instances must stay consistent.
static void registerShops(
List<Rees46Config> configs, {
List<REES46Config> configs, {
bool eagerInit = false,
}) => _instance._registerShops(configs, eagerInit: eagerInit);

Expand All @@ -99,7 +99,7 @@ class Rees46 {
_instance._isInitialized(shopId);

/// Routes a push to the shop it belongs to (the payload's `shop_id`) and tracks
/// [event] for it via the native `Rees46.handlePush`, then fires that shop's
/// [event] for it via the native `REES46.handlePush`, then fires that shop's
/// registered push callbacks. Call this from a host that owns its messaging
/// service.
///
Expand All @@ -126,14 +126,14 @@ class Rees46 {
// Instance implementation
// ---------------------------------------------------------------------------

PersonalizationSdk _initialize(Rees46Config config) {
PersonalizationSdk _initialize(REES46Config config) {
final sdk = _factory(config);
_live[config.shopId] = sdk;
_pending.remove(config.shopId);
return sdk;
}

void _registerShops(List<Rees46Config> configs, {required bool eagerInit}) {
void _registerShops(List<REES46Config> configs, {required bool eagerInit}) {
for (final config in configs) {
if (eagerInit) {
_initialize(config);
Expand Down Expand Up @@ -210,7 +210,7 @@ class Rees46 {
/// Test-only: overrides the factory that builds/initializes instances so shop
/// resolution can be exercised without touching native or Pigeon.
@visibleForTesting
static set debugFactory(Rees46SdkFactory factory) =>
static set debugFactory(REES46SdkFactory factory) =>
_instance._factory = factory;

/// Test-only: drops all live and pending registrations and restores the
Expand Down
Loading
Loading