@zaptek/application-livel 0.16.0-next-20261116093904 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,10 +1,24 @@
1
1
  # @zaptek/application-livel
2
2
 
3
- ## 0.16.0-next-20261116093904
3
+ ## 0.16.2
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [25dc8ec]
8
+ - @zaptek/resource@0.4.1
9
+
10
+ ## 0.16.1
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [53eb541]
15
+ - @zaptek/resource@0.4.0
16
+
17
+ ## 0.16.0
4
18
 
5
19
  ### Minor Changes
6
20
 
7
- - 8d5bca7: A published application signs its visitors and accounts in on its own domain: the published host (email code, guest session promoted on sign-in), alongside the platform's preview host. The template's instructions describe the platform's tables an application reads (`src/platform-tables.gen.ts`, written by the platform) and its commerce calls.
21
+ - 0a9c41d: Delete files with `useDeleteFiles` alone, given their ids (one or more): it deletes the file records under the member's rights, their bytes following once the deletion commits, as the platform no longer serves `files.delete_file` and `files.delete_files`. Breaking: `useDeleteFile` is gone; call `useDeleteFiles` with `[id]`.
8
22
 
9
23
  ## 0.15.1
10
24
 
@@ -1,16 +1,10 @@
1
1
  import { type SupabaseClient } from "@supabase/supabase-js";
2
- import { type ApplicationAccount } from "../host/published-host.js";
2
+ import type { LivelHost } from "../host/livel-host.js";
3
3
  import { type RpcCaller } from "../rpc/rpc-caller.js";
4
4
  export type LivelApplicationClient = {
5
5
  supabase: SupabaseClient;
6
6
  rpc: RpcCaller;
7
7
  workspace_id: string;
8
- /**
9
- * The account of the person using the application once published outside
10
- * Livel (a visitor, a guest or a signed-in account); none inside Livel,
11
- * where the member is.
12
- */
13
- account: ApplicationAccount | null;
14
8
  /** Resolves to `true` once the member session is available, `false` if never. */
15
9
  ready: Promise<boolean>;
16
10
  /** Shows an error in Livel; uncaught errors and rejections are reported already. */
@@ -27,17 +21,12 @@ export type LivelApplicationConfig = {
27
21
  supabase_publishable_key: string;
28
22
  /** Workspace the application shows when the member has several. */
29
23
  workspace_id: string;
30
- /** The application itself: whom its visitors and accounts belong to. */
31
- application_id: string;
32
24
  };
33
25
  /** Reads the configuration Livel gives the application through Vite. */
34
26
  export declare function readLivelApplicationConfig(): LivelApplicationConfig;
35
27
  /**
36
- * Supabase and RPC clients acting as whoever uses the application: every
37
- * request asks the host for the current access token. Inside Livel's iframe
38
- * the host is the embedding page, acting as the member, who never gives the
39
- * application a refresh token; outside, the application acts as its
40
- * visitors until someone becomes a guest or signs in (`account`). The same
41
- * policies apply to all. Browser only.
28
+ * Supabase and RPC clients acting as the member: every request asks the host
29
+ * for the current access token, so the application never holds a refresh
30
+ * token. Inside Livel's iframe the host is the embedding page. Browser only.
42
31
  */
43
- export declare function createLivelApplicationClient(config?: LivelApplicationConfig): LivelApplicationClient;
32
+ export declare function createLivelApplicationClient(config?: LivelApplicationConfig, host?: LivelHost): LivelApplicationClient;
@@ -1,6 +1,5 @@
1
1
  import { createClient } from "@supabase/supabase-js";
2
2
  import { createEmbeddedHost } from "../host/embedded-host.js";
3
- import { createPublishedHost, } from "../host/published-host.js";
4
3
  import { createRpcCaller } from "../rpc/rpc-caller.js";
5
4
  function requireEnvironmentVariable(name, value) {
6
5
  if (!value?.trim()) {
@@ -24,7 +23,6 @@ export function readLivelApplicationConfig() {
24
23
  supabase_url: requireEnvironmentVariable("VITE_SUPABASE_URL", env.VITE_SUPABASE_URL),
25
24
  supabase_publishable_key: requireEnvironmentVariable("VITE_SUPABASE_PUBLISHABLE_KEY", env.VITE_SUPABASE_PUBLISHABLE_KEY),
26
25
  workspace_id: requireEnvironmentVariable("VITE_LIVEL_WORKSPACE_ID", env.VITE_LIVEL_WORKSPACE_ID),
27
- application_id: requireEnvironmentVariable("VITE_LIVEL_APPLICATION_ID", env.VITE_LIVEL_APPLICATION_ID),
28
26
  };
29
27
  }
30
28
  /**
@@ -36,37 +34,20 @@ function tunnelHeaders(url) {
36
34
  ? { "ngrok-skip-browser-warning": "1" }
37
35
  : {};
38
36
  }
39
- /** Inside Livel's iframe (its preview, a published application opened there). */
40
- const isEmbedded = () => typeof window !== "undefined" && window.parent !== window;
41
37
  /**
42
- * Supabase and RPC clients acting as whoever uses the application: every
43
- * request asks the host for the current access token. Inside Livel's iframe
44
- * the host is the embedding page, acting as the member, who never gives the
45
- * application a refresh token; outside, the application acts as its
46
- * visitors until someone becomes a guest or signs in (`account`). The same
47
- * policies apply to all. Browser only.
38
+ * Supabase and RPC clients acting as the member: every request asks the host
39
+ * for the current access token, so the application never holds a refresh
40
+ * token. Inside Livel's iframe the host is the embedding page. Browser only.
48
41
  */
49
- export function createLivelApplicationClient(config = readLivelApplicationConfig()) {
42
+ export function createLivelApplicationClient(config = readLivelApplicationConfig(), host = createEmbeddedHost(requireHttpUrl("VITE_LIVEL_HOST_ORIGIN", config.host_origin).origin)) {
50
43
  const platformUrl = requireHttpUrl("VITE_LIVEL_PLATFORM_URL", config.platform_url);
51
- const rpcUrl = new URL("/api/rpc", platformUrl).href;
52
- const published = isEmbedded()
53
- ? null
54
- : createPublishedHost({
55
- application_id: config.application_id,
56
- rpc: createRpcCaller({
57
- url: rpcUrl,
58
- headers: () => tunnelHeaders(platformUrl),
59
- }),
60
- });
61
- const host = published ??
62
- createEmbeddedHost(requireHttpUrl("VITE_LIVEL_HOST_ORIGIN", config.host_origin).origin);
63
44
  const supabaseUrl = requireHttpUrl("VITE_SUPABASE_URL", config.supabase_url);
64
45
  const supabase = createClient(supabaseUrl.href, config.supabase_publishable_key, {
65
46
  global: { headers: tunnelHeaders(supabaseUrl) },
66
47
  accessToken: host.getAccessToken,
67
48
  });
68
49
  const rpc = createRpcCaller({
69
- url: rpcUrl,
50
+ url: new URL("/api/rpc", platformUrl).href,
70
51
  headers: async () => {
71
52
  const accessToken = await host.getAccessToken();
72
53
  if (!accessToken) {
@@ -83,7 +64,6 @@ export function createLivelApplicationClient(config = readLivelApplicationConfig
83
64
  supabase,
84
65
  rpc,
85
66
  workspace_id: config.workspace_id,
86
- account: published?.account ?? null,
87
67
  ready: host.ready,
88
68
  reportError: host.reportError,
89
69
  dispose: host.dispose,
@@ -1,5 +1,4 @@
1
- export { LivelApplicationProvider, useApplicationAccount, } from "./livel-application.provider.js";
2
- export type { UseApplicationAccountResult } from "./livel-application.provider.js";
1
+ export { LivelApplicationProvider } from "./livel-application.provider.js";
3
2
  export { LivelDataConnectionStatus } from "./livel-data-connection-status.component.js";
4
3
  export { FileDownloadButton, FileUploadButton } from "./files/index.js";
5
4
  export type { FileDownloadButtonProps, FileUploadButtonProps, } from "./files/index.js";
@@ -1,3 +1,3 @@
1
- export { LivelApplicationProvider, useApplicationAccount, } from "./livel-application.provider.js";
1
+ export { LivelApplicationProvider } from "./livel-application.provider.js";
2
2
  export { LivelDataConnectionStatus } from "./livel-data-connection-status.component.js";
3
3
  export { FileDownloadButton, FileUploadButton } from "./files/index.js";
@@ -1,5 +1,4 @@
1
1
  import { type ReactNode } from "react";
2
- import type { ApplicationAccount, ApplicationAccountState } from "../host/published-host.js";
3
2
  import { type LivelApplicationClient } from "../client/livel-application-client.js";
4
3
  export type LivelApplicationStatus = "connecting" | "ready" | "unavailable";
5
4
  export type LivelApplicationState = {
@@ -19,14 +18,3 @@ export declare function LivelApplicationProvider({ children, }: {
19
18
  */
20
19
  export declare function useReportError(): (error: unknown) => void;
21
20
  export declare function useLivelApplication(): LivelApplicationState;
22
- export type UseApplicationAccountResult = {
23
- /** Outside Livel, whom the application acts as; inside, the member. */
24
- state: ApplicationAccountState | null;
25
- account: ApplicationAccount | null;
26
- };
27
- /**
28
- * The account of the person using the published application: its state,
29
- * re-rendered when it changes, and its sign-in, guest and sign-out actions.
30
- * Inside Livel, where the member is, there is none.
31
- */
32
- export declare function useApplicationAccount(): UseApplicationAccountResult;
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
3
3
  import { ResourceProvider } from "@zaptek/resource";
4
- import { createContext, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore, } from "react";
4
+ import { createContext, useCallback, useContext, useEffect, useMemo, useState, } from "react";
5
5
  import { createLivelApplicationClient, } from "../client/livel-application-client.js";
6
6
  const LivelApplicationContext = createContext(null);
7
7
  /** No message of its own: the application shows a write's outcome itself. */
@@ -73,15 +73,3 @@ export function useLivelApplication() {
73
73
  }
74
74
  return state;
75
75
  }
76
- const insideLivel = { status: "visitor" };
77
- /**
78
- * The account of the person using the published application: its state,
79
- * re-rendered when it changes, and its sign-in, guest and sign-out actions.
80
- * Inside Livel, where the member is, there is none.
81
- */
82
- export function useApplicationAccount() {
83
- const { client } = useLivelApplication();
84
- const account = client?.account ?? null;
85
- const state = useSyncExternalStore(listener => account?.subscribe(listener) ?? (() => { }), () => account?.state() ?? insideLivel, () => insideLivel);
86
- return { state: account ? state : null, account };
87
- }
@@ -46,6 +46,5 @@ export declare function useDownloadFile(): import("@tanstack/react-query").UseMu
46
46
  /** Uses Livel's signed upload ticket, then registers the Storage object. */
47
47
  export declare function useUploadFiles(): import("@tanstack/react-query").UseMutationResult<UploadedFile[], Error, UploadFilesInput, unknown>;
48
48
  export declare function useUpdateFile<TFile extends FileRecord = FileRecord>(): import("@tanstack/react-query").UseMutationResult<TFile, Error, UpdateFileInput, unknown>;
49
- export declare function useDeleteFile<TFile extends FileRecord = FileRecord>(): import("@tanstack/react-query").UseMutationResult<TFile, Error, string, unknown>;
50
49
  export declare function useDeleteFiles<TFile extends FileRecord = FileRecord>(): import("@tanstack/react-query").UseMutationResult<TFile[], Error, string[], unknown>;
51
50
  export declare function useChangeFileVisibility<TFile extends FileRecord = FileRecord>(): import("@tanstack/react-query").UseMutationResult<TFile, Error, ChangeFileVisibilityInput, unknown>;
@@ -71,12 +71,6 @@ export function getCompletedUploads(error) {
71
71
  ? uploadedFiles.map(requireUploadedFile)
72
72
  : [];
73
73
  }
74
- function requireFileRecords(value) {
75
- if (!Array.isArray(value)) {
76
- throw new Error("Livel returned an invalid file list");
77
- }
78
- return value.map(requireFileRecord);
79
- }
80
74
  function selectDownloadUrl(response) {
81
75
  if (!isRecord(response) || typeof response.url !== "string") {
82
76
  throw new Error("Livel returned an invalid file download URL");
@@ -242,33 +236,21 @@ export function useUpdateFile() {
242
236
  },
243
237
  });
244
238
  }
245
- export function useDeleteFile() {
246
- const { client, status } = useLivelApplication();
247
- const queryClient = useQueryClient();
248
- return useMutation({
249
- mutationFn: async (fileId) => {
250
- const connectedClient = requireConnectedClient(client, status);
251
- return requireFileRecord(await connectedClient.rpc.call(["files", "delete_file"], {
252
- file_id: fileId,
253
- }));
254
- },
255
- onSuccess: async () => {
256
- await invalidateFileQueries(queryClient, client?.workspace_id ?? null);
257
- },
258
- onError: async () => {
259
- await invalidateFileQueries(queryClient, client?.workspace_id ?? null);
260
- },
261
- });
262
- }
263
239
  export function useDeleteFiles() {
264
240
  const { client, status } = useLivelApplication();
265
241
  const queryClient = useQueryClient();
266
242
  return useMutation({
267
243
  mutationFn: async (fileIds) => {
268
244
  const connectedClient = requireConnectedClient(client, status);
269
- return requireFileRecords(await connectedClient.rpc.call(["files", "delete_files"], {
270
- file_ids: fileIds,
271
- }));
245
+ // Their bytes follow the records once the deletion commits.
246
+ const { data } = await connectedClient.supabase
247
+ .from("files")
248
+ .delete()
249
+ .in("id", fileIds)
250
+ .eq("workspace_id", connectedClient.workspace_id)
251
+ .select("*")
252
+ .throwOnError();
253
+ return data;
272
254
  },
273
255
  onSuccess: async () => {
274
256
  await invalidateFileQueries(queryClient, client?.workspace_id ?? null);
@@ -2,5 +2,5 @@ export { useReportError, useLivelApplication, } from "../components/livel-applic
2
2
  export type { LivelApplicationState, LivelApplicationStatus, } from "../components/livel-application.provider.js";
3
3
  export { useRpcQuery } from "./rpc.hooks.js";
4
4
  export type { RpcQueryOptions } from "./rpc.hooks.js";
5
- export { getCompletedUploads, useChangeFileVisibility, useDeleteFile, useDeleteFiles, useDownloadFile, useFile, useFileDownloadUrl, useFiles, useUpdateFile, useUploadFiles, } from "./files.hooks.js";
5
+ export { getCompletedUploads, useChangeFileVisibility, useDeleteFiles, useDownloadFile, useFile, useFileDownloadUrl, useFiles, useUpdateFile, useUploadFiles, } from "./files.hooks.js";
6
6
  export type { ChangeFileVisibilityInput, FileFilters, FileRecord, PaginationOptions, UpdateFileInput, UploadedFile, UploadFilesInput, } from "./files.hooks.js";
@@ -1,3 +1,3 @@
1
1
  export { useReportError, useLivelApplication, } from "../components/livel-application.provider.js";
2
2
  export { useRpcQuery } from "./rpc.hooks.js";
3
- export { getCompletedUploads, useChangeFileVisibility, useDeleteFile, useDeleteFiles, useDownloadFile, useFile, useFileDownloadUrl, useFiles, useUpdateFile, useUploadFiles, } from "./files.hooks.js";
3
+ export { getCompletedUploads, useChangeFileVisibility, useDeleteFiles, useDownloadFile, useFile, useFileDownloadUrl, useFiles, useUpdateFile, useUploadFiles, } from "./files.hooks.js";
package/dist/index.d.ts CHANGED
@@ -2,8 +2,6 @@ export { createLivelApplicationClient, readLivelApplicationConfig, } from "./cli
2
2
  export type { LivelApplicationClient, LivelApplicationConfig, } from "./client/livel-application-client.js";
3
3
  export { createEmbeddedHost } from "./host/embedded-host.js";
4
4
  export type { LivelHost } from "./host/livel-host.js";
5
- export { createPublishedHost } from "./host/published-host.js";
6
- export type { ApplicationAccount, ApplicationAccountState, PublishedHost, } from "./host/published-host.js";
7
5
  export type { LivelApplicationError, LivelHostMethods, } from "./host/livel-host.contract.js";
8
6
  export { createRpcCaller } from "./rpc/rpc-caller.js";
9
7
  export type { RpcCaller, RpcCallerOptions } from "./rpc/rpc-caller.js";
package/dist/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  export { createLivelApplicationClient, readLivelApplicationConfig, } from "./client/livel-application-client.js";
2
2
  export { createEmbeddedHost } from "./host/embedded-host.js";
3
- export { createPublishedHost } from "./host/published-host.js";
4
3
  export { createRpcCaller } from "./rpc/rpc-caller.js";
5
4
  export { livelDevErrorsPath } from "./dev/dev-errors.contract.js";
@@ -1,4 +1,4 @@
1
- # Authentication
1
+ # Authentication in the iframe
2
2
 
3
3
  Livel remains responsible for the Supabase connection, the refresh token and the
4
4
  session. On load, the application's client opens a
@@ -33,29 +33,8 @@ SDK hooks for the resources they cover and keep any new
33
33
  query in an application-specific hook.
34
34
 
35
35
  The origin of the session is isolated behind `LivelHost`: in the iframe,
36
- it is the Livel page (`createEmbeddedHost`); published outside Livel, the
37
- application itself (`createPublishedHost`), as described below. The hooks
38
- do not change.
39
-
40
- ## Published outside Livel: visitors and accounts
41
-
42
- On its own address, the application is used by the workspace's outside: it
43
- acts as its anonymous visitors until someone becomes a guest or signs in.
44
- Their tokens carry the Postgres role `external`: they read and write only
45
- what the workspace's roles for them allow, on the columns tables open to the
46
- outside; the member's tables stay closed. `useApplicationAccount()` returns
47
- the state (`visitor`, `guest`, `signed_in`, or `null` inside Livel) and the
48
- account's actions:
49
-
50
- | Action | Effect |
51
- | --- | --- |
52
- | `requestSignInCode(email)` | Emails a 6-digit code (same answer whether an account exists or not). |
53
- | `signIn(email, code)` | Signs in: `"signed_in"`, or `"pending"` when the workspace approves accounts first. A guest becomes the account, keeping its rows. |
54
- | `ensureGuest()` | Makes the visitor a guest before its first write (a cart), where the application opens accounts to anyone. |
55
- | `signOut()` | Ends the session; the application acts as its visitors again. |
56
-
57
- The session's refresh token, renewed at each use, is kept in the browser's
58
- storage. `VITE_LIVEL_APPLICATION_ID` names the application.
36
+ it is the Livel page (`createEmbeddedHost`). A standalone application will provide
37
+ its own connection behind the same contract, without changing the hooks.
59
38
 
60
39
  The low-level export `createLivelApplicationClient()` is browser-only
61
40
  and must be released with `client.dispose()` when its owner goes away.
package/docs/files.md CHANGED
@@ -17,7 +17,7 @@ temporary: do not store it as a durable reference.
17
17
  | `useDownloadFile()` | Request a fresh download URL on click. |
18
18
  | `useUploadFiles()` | Upload files and record their metadata. |
19
19
  | `useUpdateFile()` | Change a file's metadata. |
20
- | `useDeleteFile()` / `useDeleteFiles()` | Delete one or more files. |
20
+ | `useDeleteFiles()` | Delete one or more files: their bytes follow. |
21
21
  | `useChangeFileVisibility()` | Change the public or private visibility. |
22
22
 
23
23
  Reads are TanStack Query queries; changes are TanStack Query
@@ -120,7 +120,6 @@ The SDK does not copy the full schema of the `files` table: it guarantees the
120
120
  | Mutation | Argument of `mutate` or `mutateAsync` |
121
121
  | --- | --- |
122
122
  | `useUpdateFile()` | `{ id, name?, metadata? }`; at least one field to change. |
123
- | `useDeleteFile()` | The file identifier. |
124
123
  | `useDeleteFiles()` | An array of identifiers. |
125
124
  | `useChangeFileVisibility()` | `{ id, is_public }`. |
126
125
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaptek/application-livel",
3
- "version": "0.16.0-next-20261116093904",
3
+ "version": "0.16.2",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "license": "UNLICENSED",
@@ -42,7 +42,7 @@
42
42
  "@orpc/client": "^1.16.2",
43
43
  "@supabase/supabase-js": "^2.114.0",
44
44
  "penpal": "^8.0.1",
45
- "@zaptek/resource": "0.3.0"
45
+ "@zaptek/resource": "0.4.1"
46
46
  },
47
47
  "peerDependencies": {
48
48
  "@tanstack/react-query": "^5.90.21",
@@ -1,10 +1,8 @@
1
- # Livel fournit ces valeurs publiques au serveur de développement et à la publication.
1
+ # Livel fournit ces valeurs publiques au serveur de développement.
2
2
  # Pour tester l'auth dans une iframe locale, renseigner les mêmes valeurs dans .env.local.
3
- VITE_LIVEL_PLATFORM_URL=https://livel.example.com
4
- VITE_LIVEL_HOST_ORIGIN=https://livel.example.com
3
+ VITE_LIVEL_PLATFORM_ORIGIN=https://livel.example.com
5
4
  VITE_LIVEL_WORKSPACE_ID=00000000-0000-0000-0000-000000000000
6
- VITE_LIVEL_APPLICATION_ID=00000000-0000-0000-0000-000000000000
7
5
  VITE_SUPABASE_URL=https://example.supabase.co
8
6
  VITE_SUPABASE_PUBLISHABLE_KEY=...
9
7
 
10
- # Le token est transmis par l'iframe (membre) ou par la plateforme (visiteurs et comptes), jamais par une variable d'environnement.
8
+ # Le token utilisateur est transmis par l'iframe, jamais par une variable d'environnement.
@@ -76,16 +76,6 @@ description })` in the hooks' callbacks. The `Toaster` is mounted
76
76
  `src/livel-objects.gen.ts`, generated by Livel: do not modify it or declare
77
77
  data types by hand. After the objects change, Livel
78
78
  regenerates the file; run the build and fix each type error.
79
- - The platform's own tables the application's visitors and accounts may
80
- read (an Astela site's products, variants, collections, sales channel,
81
- carts) are declared in `src/platform-tables.gen.ts`, generated likewise
82
- with only the columns they may read. A buyer's prices come from the
83
- `my_variant_prices` RPC (`p_product_variant_ids`), never from a price
84
- computed in the application. Checkout and coupons are platform procedures,
85
- called with the SDK's `client.rpc.call(["payments",
86
- "init_checkout_session"], input)`, `["discount_coupons",
87
- "apply_discount_coupon"]`, `["discount_coupons", "remove_discount_coupon"]`
88
- and `["carts", "unlock_cart"]`.
89
79
  - Read and write an object's records with a resource declared once,
90
80
  in `src/lib/resources/<object>.resource.ts`, with `defineResource` from
91
81
  `@zaptek/resource` on the generated table: relations (a `<field>_id` column),
@@ -110,12 +100,5 @@ description })` in the hooks' callbacks. The `Toaster` is mounted
110
100
  - A date without a time (`"2025-06-12"`) is a calendar date: do not
111
101
  pass it to `new Date(...)`, which reads it at midnight UTC and can display the previous day.
112
102
  Compare it as an ISO string and format it from its components.
113
- - Published outside Livel, the application serves the workspace's outside:
114
- it acts as its anonymous visitors until someone becomes a guest or signs
115
- in. Use `useApplicationAccount()` (`@zaptek/application-livel/components`)
116
- for the sign-in by emailed code, the guest a first write needs
117
- (`ensureGuest()` before adding to a cart) and the sign-out; read
118
- `docs/authentication.md`. What each one may read or write is the
119
- workspace's roles for them: never filter access in the application's code.
120
103
  - Do not modify `src/routeTree.gen.ts` by hand: TanStack generates it.
121
104
  - Keep the SPA mode and the `livel.json` contract unless explicitly requested.
@@ -17,8 +17,8 @@
17
17
  },
18
18
  "packageManager": "pnpm@10.34.0",
19
19
  "dependencies": {
20
- "@zaptek/application-livel": "0.16.0-next-20261116093904",
21
- "@zaptek/resource": "0.3.0",
20
+ "@zaptek/application-livel": "0.16.2",
21
+ "@zaptek/resource": "0.4.1",
22
22
  "@tanstack/react-query": "catalog:",
23
23
  "zod": "catalog:",
24
24
  "@base-ui/react": "catalog:",
@@ -1,49 +0,0 @@
1
- import type { LivelHost } from "./livel-host.js";
2
- import type { RpcCaller } from "../rpc/rpc-caller.js";
3
- /**
4
- * Whom the application acts as: its anonymous visitors, a guest (an
5
- * account without email, made at a visitor's first write), or a signed-in
6
- * account.
7
- */
8
- export type ApplicationAccountState = {
9
- status: "visitor";
10
- } | {
11
- status: "guest";
12
- principal_id: string;
13
- } | {
14
- status: "signed_in";
15
- principal_id: string;
16
- };
17
- /**
18
- * The account of the person using a published application: signing in by
19
- * an emailed code, the guest a first write needs, signing out.
20
- */
21
- export type ApplicationAccount = {
22
- state(): ApplicationAccountState;
23
- /** Calls `listener` whenever the state changes; returns the unsubscribe. */
24
- subscribe(listener: () => void): () => void;
25
- /** Emails a sign-in code (the same answer whether or not an account exists). */
26
- requestSignInCode(email: string): Promise<void>;
27
- /**
28
- * Signs in with the code received; `pending` when the application
29
- * approves its accounts and this one waits.
30
- */
31
- signIn(email: string, code: string): Promise<"signed_in" | "pending">;
32
- /** Makes the visitor a guest, before a first write (a cart). */
33
- ensureGuest(): Promise<void>;
34
- signOut(): Promise<void>;
35
- };
36
- export type PublishedHost = LivelHost & {
37
- account: ApplicationAccount;
38
- };
39
- /**
40
- * A published application, outside Livel: it acts as its visitors until
41
- * someone becomes a guest or signs in, through the platform's public
42
- * procedures. The session (its refresh token, renewed at each use) is kept in
43
- * the browser's storage.
44
- */
45
- export declare function createPublishedHost(options: {
46
- application_id: string;
47
- /** The platform's procedures, called without a session. */
48
- rpc: RpcCaller;
49
- }): PublishedHost;
@@ -1,142 +0,0 @@
1
- /** Renewed this long before it expires. */
2
- const expiryMarginMs = 30_000;
3
- const isLive = (token) => token !== null &&
4
- new Date(token.expires_at).getTime() - expiryMarginMs > Date.now();
5
- /** The browser's storage, absent (private mode, server) as none. */
6
- function storage() {
7
- try {
8
- return typeof window === "undefined" ? null : window.localStorage;
9
- }
10
- catch {
11
- return null;
12
- }
13
- }
14
- /**
15
- * A published application, outside Livel: it acts as its visitors until
16
- * someone becomes a guest or signs in, through the platform's public
17
- * procedures. The session (its refresh token, renewed at each use) is kept in
18
- * the browser's storage.
19
- */
20
- export function createPublishedHost(options) {
21
- const { application_id: applicationId, rpc } = options;
22
- const storageKey = `zaptek.session.${applicationId}`;
23
- const listeners = new Set();
24
- let visitorToken = null;
25
- let renewing = null;
26
- const readSession = () => {
27
- const stored = storage()?.getItem(storageKey);
28
- if (!stored)
29
- return null;
30
- try {
31
- return JSON.parse(stored);
32
- }
33
- catch {
34
- return null;
35
- }
36
- };
37
- const stateOf = (current) => current
38
- ? {
39
- status: current.is_guest ? "guest" : "signed_in",
40
- principal_id: current.principal_id,
41
- }
42
- : { status: "visitor" };
43
- let session = readSession();
44
- // One object per state: React compares snapshots by identity.
45
- let state = stateOf(session);
46
- const setSession = (next) => {
47
- const changed = next?.principal_id !== session?.principal_id ||
48
- next?.is_guest !== session?.is_guest;
49
- session = next;
50
- if (next)
51
- storage()?.setItem(storageKey, JSON.stringify(next));
52
- else
53
- storage()?.removeItem(storageKey);
54
- if (!changed)
55
- return;
56
- state = stateOf(next);
57
- for (const listener of listeners)
58
- listener();
59
- };
60
- const call = (name, input) => rpc.call(["applications", name], input);
61
- async function sessionToken(current) {
62
- if (isLive(current))
63
- return current.access_token;
64
- try {
65
- const renewed = await call("refresh_session", {
66
- refresh_token: current.refresh_token,
67
- });
68
- setSession({ ...renewed, is_guest: current.is_guest });
69
- return renewed.access_token;
70
- }
71
- catch {
72
- // Expired, withdrawn or replayed elsewhere: back to a visitor.
73
- setSession(null);
74
- return null;
75
- }
76
- }
77
- async function accessToken() {
78
- if (session) {
79
- const current = session;
80
- renewing ??= sessionToken(current).finally(() => {
81
- renewing = null;
82
- });
83
- const token = await renewing;
84
- if (token)
85
- return token;
86
- }
87
- if (!visitorToken || !isLive(visitorToken)) {
88
- visitorToken = await call("get_visitor_token", {
89
- application_id: applicationId,
90
- });
91
- }
92
- return visitorToken.access_token;
93
- }
94
- const account = {
95
- state: () => state,
96
- subscribe(listener) {
97
- listeners.add(listener);
98
- return () => listeners.delete(listener);
99
- },
100
- requestSignInCode: email => call("request_sign_in_code", {
101
- application_id: applicationId,
102
- email,
103
- }),
104
- async signIn(email, code) {
105
- const result = await call("sign_in", {
106
- application_id: applicationId,
107
- email,
108
- code,
109
- guest_refresh_token: session?.is_guest
110
- ? session.refresh_token
111
- : undefined,
112
- });
113
- if (result.status === "signed_in") {
114
- setSession({ ...result.session, is_guest: false });
115
- }
116
- return result.status;
117
- },
118
- async ensureGuest() {
119
- if (session)
120
- return;
121
- const guest = await call("start_guest_session", {
122
- application_id: applicationId,
123
- });
124
- setSession({ ...guest, is_guest: true });
125
- },
126
- async signOut() {
127
- const current = session;
128
- setSession(null);
129
- if (current) {
130
- await call("sign_out", { refresh_token: current.refresh_token });
131
- }
132
- },
133
- };
134
- return {
135
- ready: Promise.resolve(true),
136
- getAccessToken: accessToken,
137
- // Outside Livel, nobody receives the application's errors.
138
- reportError: () => { },
139
- dispose: () => listeners.clear(),
140
- account,
141
- };
142
- }