acai-demo-sdk
v0.7.2
Published
Shared Try Demo feature package — session-end redirect claim, expiry polling, persona switching against auth-sso-server's /demo/* endpoints, and the DemoModeBar UI itself. Each consuming app supplies its own cookie adapter and post-switch navigation inste
Readme
açai demo SDK
Shared Try Demo package for açai apps: session-end redirect claim, expiry polling, persona switching against auth-sso-server's /demo/* endpoints, and the DemoModeBar UI.
Repository: getacaii/acai-demo-sdk. Default branch: main.
What it does
- Provides the React pieces and helpers every frontend needs to run a Try Demo session. Each consuming app supplies its own cookie adapter and post-switch navigation.
- Carries the backend clone and teardown contract types, type-only and safe to import from a NestJS backend.
- Sits between the app frontends and
auth-sso-server(the/demo/*endpoints); it has no server of its own.
Tech stack
- TypeScript, React (peer dependency
^18 || ^19),acai-ui-library(peer dependency) - Tests: Vitest
- Published to the public npm registry as
acai-demo-sdkby thePublishworkflow onv*tags
Getting started
Prerequisites: Node.js 22 and npm.
npm ci # Install dependencies
npm run build # Compile with tsc
npm run lint # Lint
npm run test # Unit testsNo environment variables are read by the package itself; consuming apps pass the SSO URL and cookie settings in. acai-demo-sdk/env provides assertProductionUrl() for use in next.config.
Entry points
| Import | Contents |
|---|---|
| acai-demo-sdk | Hooks, DemoModeBar and shell components |
| acai-demo-sdk/client | Client for the /demo/* endpoints |
| acai-demo-sdk/middleware-token | pickAccessToken() for Next.js middleware |
| acai-demo-sdk/env | Environment guards such as assertProductionUrl() |
| acai-demo-sdk/contracts | Clone and teardown contract types (type-only) |
| acai-demo-sdk/fixture | The one fictional template company (no React) |
| acai-demo-sdk/server | Kind client, template-ready rule, template lock key (Node only) |
| acai-demo-sdk/testing | Test helpers for consumers |
Project structure
src/ client, hooks, components, contracts, fixture and server helpers
test/ unit tests
.github/ CI and publish workflowsDeployment
This is a library, not a service. A v* tag triggers .github/workflows/publish.yml, which publishes to npm. Apps pick up a new version by bumping the dependency; their own deploys follow the reusable workflows in getacaii/acai-ai-platform (docs/CI-CD-STANDARD.md).
Contributing
- Work starts from a task issue in
getacaii/acai-ai-platform; the PR rules are indocs/TASK-LIFECYCLE.mdthere. - Open the PR against the default branch (
mainhere) with a Conventional Commits title.
Release notes
Removed in 0.7.0:
session.getEmployeePortalLink(fromuseDemoSessionand theUseDemoSessionResulttype). auth-sso-server no longer servesGET /demo/employee-portal-link, so the method could only returnnull. Nothing in the estate calls it. Delete any use; there is no replacement.
0.7.0
- Product analytics for signed-in users:
createProductAnalytics(root entry and the React-freeacai-demo-sdk/client). It reuses the Try Demo tracker's batching and cleaning and posts to auth-sso-serverPOST /api/v1/analytics/eventswith the user's access token (acai-ai-platform#1260, seedocs/platform/product-analytics.md). See "Product analytics" below. - The Try Demo tracker now sends through a shared batcher (
telemetry-batcher.ts). Its behaviour is unchanged: same URL, body, limits and stop rules. SDK_VERSION('acai-demo-sdk/server') is now0.7.0. An app that adopts this release will report its template as stale and rebuild it on the next "Provision now".
Product analytics
import { createProductAnalytics } from 'acai-demo-sdk/client';
const analytics = createProductAnalytics({
endpoint: process.env.NEXT_PUBLIC_SSO_URL!, // or the full .../api/v1/analytics/events URL
getAccessToken: () => getAccessTokenFromCookie(), // may also return a Promise
appId: 'hrms', // the registry app id
consent: userConsented, // nothing is sent until this is true
optOut: profile.analyticsOptOut, // the per-user opt-out, if known at start-up
routeTemplate: (path) => path, // optional; default: uuid and numeric segments -> :id
});
const unwire = analytics.start(); // clicks, visibility, pagehide, a 1 s route poll; call unwire() on unmount
analytics.trackAction('invoice.create');
analytics.trackFunnelStep('onboarding', 'invite-sent');
analytics.setOptOut(true); // stops sending and drops what is queuedWhat it records and what it never records:
- Routes: only the template. The query string and fragment are cut before your mapper sees the path, and the
result is cleaned again (
cleanRoutePath), so/people/[email protected]/edit?tab=salaryis sent as/people/:id/edit. - Clicks: the element's ARIA role (explicit or implied by the tag) and its
data-analytics-id, plus the click position in percent and a viewport bucket. Never text content, never input values, neveraria-label(labels often hold names). Adddata-analytics-idto the controls you want named in the heatmaps. Putdata-analytics-maskon an element or a whole section to skip clicks in it entirely. - Actions and funnel steps: short identifiers only (
invoice.create); names with spaces,@or ids are dropped. - Consent: off until
consent: true(orsetConsent(true)). Global Privacy Control or Do Not Track = nothing is sent at all.setOptOut(true)orsetConsent(false)stops sending and drops the queue. The server checks the tenant switch and the user's opt-out again and answers 204 without storing anything. - No user id, tenant id, email or role is ever in the payload: the server takes the tenant and user from the token.
- At most 50 events and about 14 KB per call (the server's limit is 16 KB), every 10 s,
keepaliveso the last batch survives a page close. A 401 is retried on the next batch (tokens refresh); other 4xx stop the tracker.
0.6.4
DemoShell'sextraActionscan be a function of the session. PassextraActions={(session) => ...}to build an app button that uses the session, for example pay's "View as Employee" (session.getEmployeePortalLink(...)). The function is called only while the bar shows. A plain node still works as before.SDK_VERSION('acai-demo-sdk/server') is now0.6.4. An app that adopts this release will report its template as stale and rebuild it on the next "Provision now".
0.6.3
DemoEndedScreentakes alogo(any React node, shown above the title), likeDemoShellalready does for the "your demo is ending" screen. Without it an app moving from its own demo-ended page to the shared one would lose its logo. Omit it for no logo.SDK_VERSION('acai-demo-sdk/server') is now0.6.3. An app that adopts this release will report its template as stale and rebuild it on the next "Provision now".
0.6.2
- Types for commonjs (node10) projects.
acai-demo-sdk/testingandacai-demo-sdk/clienthad notypesVersionsentry, so a project compiled withmodule: commonjsand nomoduleResolution(node10 ignoresexports) failed with TS2307 on those two imports. hrms-backend worked around it with a tsconfigpathsentry and itam-backend with a type shim: both can be removed once they are on 0.6.2. A test now fails if an exported subpath has notypesVersionsentry. SDK_VERSION('acai-demo-sdk/server') is now0.6.2. An app that adopts this release will report its template as stale and rebuild it on the next "Provision now".
0.6.1
Four helpers for backends and frontends. Nothing existing changes.
- Contract check (
acai-demo-sdk/testing):expectDemoContract(call)in an app's own spec sends the bodies auth-sso-server really sends (demoContractCases()) through the app's real routes and fails with one list of every case answered outsideDEMO_ROUTE_STATUS, naming a 400/422 as "rejected the body". A DTO that onlyimplementsthe contract type does not catch a field the app left out; this does (projects-backend answered 400property apps should not existonprovision-template). - Last look (
acai-demo-sdk/server):createLastLook(getKind, tenantId, expected = 'demo')returns a function to call as the last step inside the transaction. It asks auth-sso-server again and throwsDemoTenantGoneErrorunless the tenant still has the expected kind, so a demo torn down while the work ran rolls back instead of committing. An unreachable auth-sso-server staysDemoKindUnavailableError(retryable), never "gone". - Teardown helper (
acai-demo-sdk/server):runTeardown({ collectBlobKeys, deleteRows, deleteBlob, purgeQueues })runs the fixed order (collect file keys, delete rows, delete files, purge queues) and returns a count per step. A failure before the rows are deleted throws as is and leaves files and queues alone. After that, a failing file or purge does not stop the rest andDemoTeardownIncompleteErrorcarries the report. Once the rows are gone a failed file key cannot be found again on a retry: log the keys in the report. DemoShellandDemoEndedScreen(acai-demo-sdk): one component for the status poll, the bar, the role switch (with an inline error and Retry), the ending screen and the layout offset, instead of a copied banner per app, and a demo-ended page. The hook callbacks are kept stable inside, so a parent's inline arrow cannot re-fire the poll into a 429.topOffset={false}for a layout in normal flow.DemoEndedScreentakesreason(ENDED,EXPIRED,FAILED) as a prop: auth-sso-server storesendReasonbut does not return it yet.SDK_VERSION('acai-demo-sdk/server') is now0.6.1. An app that adopts this release will report its template as stale and rebuild it on the next "Provision now".
0.6.0
- Status codes (
acai-demo-sdk/contracts):DEMO_STATUS(OK200,ACCEPTED202),DEMO_ROUTE_STATUSandisDemoRouteStatus(route, status). auth-sso-server accepts 200 or 202 fromcloneandprovision-template, and only 200 fromteardownandtemplate-status. Never 201, which is what Nest answers on a POST that forgot@HttpCode. Use@HttpCode(DEMO_STATUS.OK)and assert the route's code in the app's own spec withisDemoRouteStatus. - Usage telemetry for the Try Demo heatmap, inside
useDemoSession. On by default; passtelemetry: falseto turn it off. It records which pages a visitor opens (the route with ids replaced by:id, never the query string or the fragment), where they click (position as a percent of the viewport, a viewport bucket and an element key fromdata-demo-feature, elsedata-testid, elsetag:role), how long the tab is in front (visible and active in the last 30 s) and role switches. It never reads text or input values, and never sends the persona's user id. It sends the role's display name. Batches go toPOST /demo/eventsevery 10 s (or 20 events, or 12 KB) with the demo JWT andkeepalive, and the last batch goes onpagehide.- Add
data-demo-feature="leave/approve"to a key control to name the feature its clicks belong to. - Global Privacy Control or Do Not Track: only app, role and time are sent (no routes, no clicks).
- Nothing is sent from the demo entry (
/app/demo-entry) and ended pages. - Best effort, never noise: it stops after any 4xx except 408 and 429 (404 = an older auth-sso-server without the route or a demo that is off, 401/403 = a bad token, 405, 413...), and after 3 failed batches in a row (5xx, 429, a network or CORS error). It never throws into the page. Event times use the server clock offset the hook already tracks, because the server drops an event more than a minute away from its own clock.
acai-demo-sdk/clientalso exports the React-free core (createDemoTelemetry,cleanRoutePath, ...).- Tests in an app that count
fetchcalls will now also see the/demo/eventsrequest (on a flush, or when the hook unmounts): filter it out, or passtelemetry: falsein that test. - Limits, on purpose: the element key and the route are cleaned (characters, and ids/tokens/emails become
:id), but adata-testidordata-demo-featurethat itself contains a name (row-jane-doe) or a route word that is a plain name (/employees/alice) is still sent as written. Keep names out of test ids and routes. In React StrictMode (development only) the first page view can be sent twice. - The notice shown to visitors (what is recorded and how to opt out) is NOT part of this release; its wording needs a legal check.
- Add
SDK_VERSION('acai-demo-sdk/server') is now0.6.0. An app that adopts this release will report its template as stale and rebuild it on the next "Provision now" (that is what the version is for).
0.3.0 (breaking for 0.x consumers)
- The demo JWT now lives in its own cookie,
demo_accessToken(DEMO_ACCESS_TOKEN_COOKIE), never the real-loginaccessToken. Write/clear it only through this package (writeDemoCookie,clearDemoState,endDemoSessionRedirect); read the token an API client should send withgetActiveAccessToken()(demo first, then real). Proxies/middleware usepickAccessToken()fromacai-demo-sdk/middleware-token. POST /demo/startreturns apollToken; everyGET /demo/status/:idsends it asx-demo-poll-token. It lives in sessionStorage only and reaches/demo-entryin the URL fragment (consumeDemoEntryFragment()).useDemoSessionkeeps callbacks in refs, applies a server-time offset, re-confirms expiry against/status(the server is the authority), backs off on 429/5xx (reconnecting), and exposesisSwitching/reconnecting/error.DemoModeBartakesswitching/reconnecting.acai-demo-sdk/env:assertProductionUrl()fornext.configso a production build never ships a localhost SSO URL.
License and ownership
© Humancloud Technologies Private Limited. All rights reserved.
