@lotics/app-sdk 0.2.0 → 0.5.0

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.
@@ -1,57 +1,59 @@
1
- import type { AppWorkflows, QueryAst, TableRow, WorkspaceTables } from "./types.js";
1
+ import type { AppWorkflows, AppQueries } from "./types.js";
2
2
  interface QueryState<R> {
3
3
  rows: R[];
4
4
  loading: boolean;
5
5
  error: string | null;
6
+ /**
7
+ * Re-run the underlying query against the current AST. Use after a known
8
+ * mutation point — a successful `useWorkflow(alias)()` call — to pull the
9
+ * latest state.
10
+ *
11
+ * The iframe SDK does not subscribe to realtime invalidation channels in
12
+ * v1; refetch is the explicit refresh path. Future SDK versions may add a
13
+ * `subscribe` RPC op for push-based invalidation.
14
+ */
15
+ refetch: () => void;
6
16
  }
7
- /**
8
- * Read all rows from a table. Re-fetches when the table id changes.
9
- * For derived/joined data, see `useQuery(ast)`.
10
- */
11
- export declare function useTable<K extends keyof WorkspaceTables & string>(table_id: K): QueryState<TableRow<K>>;
12
- export declare function useTable(table_id: string): QueryState<TableRow<string>>;
13
- /**
14
- * Mutation surface for a table. Returns imperative functions; doesn't manage
15
- * cache invalidation in v1 — components that read via useTable will pick up
16
- * changes on next remount or via realtime channels in v2.
17
- */
18
- export declare function useMutate<K extends keyof WorkspaceTables & string>(table_id: K): {
19
- update: (records: Array<{
20
- id: string;
21
- data: Partial<RowFor<K>>;
22
- }>) => Promise<unknown>;
23
- };
24
- export declare function useMutate(table_id: string): {
25
- update: (records: Array<{
26
- id: string;
27
- data: Record<string, unknown>;
28
- }>) => Promise<unknown>;
29
- };
30
- type RowFor<K extends keyof WorkspaceTables & string> = WorkspaceTables[K];
31
- /** Trigger a workflow by action_id. Returns a callable that runs it. */
32
- export declare function useAction(action_id: string): (inputs?: Record<string, unknown>) => Promise<unknown>;
33
17
  /**
34
18
  * Trigger a workflow by alias from the app's manifest.
35
19
  *
36
20
  * The alias must be declared in `package.json` "lotics.workflows" and synced
37
- * to `apps.workflows` on the last deploy. Returns a callable; pass whatever
38
- * inputs the workflow expects (the workflow's own trigger schema gates them
39
- * server-side).
21
+ * to `apps.workflows` on the last deploy.
40
22
  *
41
- * Per-app `lotics types` codegen augments `AppWorkflows` with the declared
42
- * alias keys passing an undeclared alias is a compile-time error.
23
+ * Per-app CLI codegen (`lotics app pull` / `app dev` / `app deploy`) writes
24
+ * `.lotics/app_workflows.d.ts` augmenting `AppWorkflows` with the declared
25
+ * alias → input-type map. Result:
26
+ * - Undeclared alias → compile-time error at the `useWorkflow("...")` site
27
+ * - Declared with full `{workflow_id, inputs}` form → callable typed as
28
+ * `(inputs: <DeclaredShape>) => Promise<unknown>`
29
+ * - Declared with shorthand (bare workflow_id) → callable typed as
30
+ * `(inputs?: Record<string, unknown>) => Promise<unknown>` (untyped)
43
31
  *
44
32
  * ```tsx
45
33
  * const issue = useWorkflow("issueInvoiceStorageDrop");
46
34
  * await issue({ record_id: row.__source_record_id });
47
35
  * ```
48
36
  */
49
- export declare function useWorkflow<K extends keyof AppWorkflows & string>(alias: K): (inputs?: Record<string, unknown>) => Promise<unknown>;
37
+ export declare function useWorkflow<K extends keyof AppWorkflows & string>(alias: K): UseWorkflowFn<K>;
50
38
  export declare function useWorkflow(alias: string): (inputs?: Record<string, unknown>) => Promise<unknown>;
39
+ type UseWorkflowFn<K extends keyof AppWorkflows & string> = AppWorkflows[K] extends Record<string, unknown> ? AppWorkflows[K] extends Record<string, never> ? (inputs?: Record<string, never>) => Promise<unknown> : (inputs: AppWorkflows[K]) => Promise<unknown> : (inputs?: Record<string, unknown>) => Promise<unknown>;
40
+ type UseQueryParams<K extends keyof AppQueries & string> = AppQueries[K] extends Record<string, never> ? [params?: Record<string, never>] : [params: AppQueries[K]];
51
41
  /**
52
- * Escape hatch pass a raw query AST. Same shape the server validates via
53
- * `parseQueryNode`. Use for joins, group-by, projections, and other shapes
54
- * `useTable`/`useRecord` don't express.
42
+ * Read rows from a query the app's author declared in `lotics.queries`.
43
+ *
44
+ * The app never sends a raw query AST — it invokes a named query by alias and
45
+ * fills the template's declared `{{params.x}}` value holes. The server holds
46
+ * the canonical AST; this is what bounds a public app's data exposure to
47
+ * exactly the queries the manifest declares.
48
+ *
49
+ * ```tsx
50
+ * const { rows, loading } = useQuery("openOrders", { status: "open" });
51
+ * ```
52
+ *
53
+ * Per-app CLI codegen writes `.lotics/app_queries.d.ts` augmenting `AppQueries`
54
+ * with the declared alias → param-type map, so an undeclared alias is a
55
+ * compile-time error and params are typed per the manifest.
55
56
  */
56
- export declare function useQuery(ast: QueryAst): QueryState<Record<string, unknown>>;
57
+ export declare function useQuery<K extends keyof AppQueries & string>(alias: K, ...rest: UseQueryParams<K>): QueryState<Record<string, unknown>>;
58
+ export declare function useQuery(alias: string, params?: Record<string, unknown>): QueryState<Record<string, unknown>>;
57
59
  export {};
package/dist/src/hooks.js CHANGED
@@ -1,71 +1,29 @@
1
1
  /**
2
2
  * Typed React hooks for Lotics app data access.
3
3
  *
4
- * Every hook is a thin wrapper over the postMessage RPC bridge — the parent
5
- * does the actual API calls with the user's session, results stream back
6
- * through `rpc()`. Hooks manage their own local cache via `useState`; we
7
- * intentionally don't ship a global store in v1.
4
+ * The SDK surface is two hooks: `useQuery` for reads, `useWorkflow` for every
5
+ * mutation. App code never writes records directly all writes flow through
6
+ * declared workflows, which gives the app owner a typed, audited chokepoint
7
+ * and means a publicly-shared app exposes no anonymous direct-write path.
8
8
  *
9
- * For users with the workspace-types augmentation in tsconfig, table IDs
10
- * passed to these hooks are typed against the actual schemas. Without it,
11
- * IDs are plain strings and rows are `Record<string, unknown>` code still
12
- * runs, just untyped.
9
+ * Every hook is a thin wrapper over the postMessage RPC bridge the parent
10
+ * does the actual API calls, results stream back through `rpc()`. Hooks manage
11
+ * their own local cache via `useState`; we intentionally don't ship a global
12
+ * store in v1.
13
13
  */
14
14
  import { useCallback, useEffect, useState } from "react";
15
15
  import { rpc } from "./rpc.js";
16
- export function useTable(table_id) {
17
- const [state, setState] = useState({
18
- rows: [],
19
- loading: true,
20
- error: null,
21
- });
22
- useEffect(() => {
23
- let cancelled = false;
24
- setState((s) => ({ rows: s.rows, loading: true, error: null }));
25
- // Server's typed-query path accepts `{ kind: "from_table", table_id }`
26
- // as the simplest AST; the resolver returns rows shaped per the table's
27
- // schema with source-addressing columns appended.
28
- rpc("query", {
29
- ast: { kind: "from_table", table_id },
30
- })
31
- .then((result) => {
32
- if (cancelled)
33
- return;
34
- setState({ rows: result.rows ?? [], loading: false, error: null });
35
- })
36
- .catch((err) => {
37
- if (cancelled)
38
- return;
39
- setState({ rows: [], loading: false, error: err.message });
40
- });
41
- return () => {
42
- cancelled = true;
43
- };
44
- }, [table_id]);
45
- return state;
46
- }
47
- export function useMutate(table_id) {
48
- return {
49
- // The parent's RPC bridge currently dispatches all `mutate` ops to update.
50
- // We omit the `op` field here rather than ship dead data — when create /
51
- // delete mutations land, we'll add `op` and a parent-side switch together.
52
- update: (records) => rpc("mutate", { table_id, records }),
53
- };
54
- }
55
- /** Trigger a workflow by action_id. Returns a callable that runs it. */
56
- export function useAction(action_id) {
57
- return useCallback((inputs) => rpc("action", { action_id, inputs: inputs ?? {} }), [action_id]);
58
- }
59
16
  export function useWorkflow(alias) {
60
17
  return useCallback((inputs) => rpc("workflow", { alias, inputs: inputs ?? {} }), [alias]);
61
18
  }
62
- /**
63
- * Escape hatchpass a raw query AST. Same shape the server validates via
64
- * `parseQueryNode`. Use for joins, group-by, projections, and other shapes
65
- * `useTable`/`useRecord` don't express.
66
- */
67
- export function useQuery(ast) {
68
- const astKey = JSON.stringify(ast);
19
+ export function useQuery(alias, params) {
20
+ // Stringified params keystructurally-equal-but-new param objects don't
21
+ // re-fire the effect every render.
22
+ const paramsKey = JSON.stringify(params ?? {});
23
+ // Bumping this token re-fires the effect without changing alias/params. The
24
+ // refetch callback mutates only this counter; state transitions still
25
+ // happen inside the effect so loading / error / rows flow consistently.
26
+ const [refetchToken, setRefetchToken] = useState(0);
69
27
  const [state, setState] = useState({
70
28
  rows: [],
71
29
  loading: true,
@@ -74,7 +32,7 @@ export function useQuery(ast) {
74
32
  useEffect(() => {
75
33
  let cancelled = false;
76
34
  setState((s) => ({ rows: s.rows, loading: true, error: null }));
77
- rpc("query", { ast })
35
+ rpc("query", { alias, params: params ?? {} })
78
36
  .then((result) => {
79
37
  if (cancelled)
80
38
  return;
@@ -88,9 +46,10 @@ export function useQuery(ast) {
88
46
  return () => {
89
47
  cancelled = true;
90
48
  };
91
- // Dep is the stringified AST so structurally-equal-but-referentially-new
92
- // objects don't re-fetch on every render.
93
49
  // eslint-disable-next-line react-hooks/exhaustive-deps
94
- }, [astKey]);
95
- return state;
50
+ }, [alias, paramsKey, refetchToken]);
51
+ const refetch = useCallback(() => {
52
+ setRefetchToken((n) => n + 1);
53
+ }, []);
54
+ return { ...state, refetch };
96
55
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Lotics App SDK — the runtime + typed hooks bundled into every custom-code
3
- * app at build time. Apps `import { mount, useTable, ... } from "@lotics/app-sdk"`
4
- * and ship the resulting bundle via `lotics app deploy`.
3
+ * app at build time. Apps `import { mount, useQuery, useWorkflow } from
4
+ * "@lotics/app-sdk"` and ship the resulting bundle via `lotics app deploy`.
5
5
  *
6
6
  * Curated UI primitive re-exports from `@lotics/ui` are deliberately NOT
7
7
  * included here. Users import them separately from a published `@lotics/ui`
@@ -10,7 +10,7 @@
10
10
  * depending on packages/ui's React Native Web setup.
11
11
  */
12
12
  export { mount } from "./mount.js";
13
- export { useTable, useMutate, useAction, useWorkflow, useQuery } from "./hooks.js";
13
+ export { useWorkflow, useQuery } from "./hooks.js";
14
14
  export { rpc } from "./rpc.js";
15
15
  export type { RpcOp } from "./rpc.js";
16
- export type { WorkspaceTables, AppWorkflows, RowOf, TableRow, SourceAddressing, QueryAst, } from "./types.js";
16
+ export type { AppWorkflows, AppQueries } from "./types.js";
package/dist/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Lotics App SDK — the runtime + typed hooks bundled into every custom-code
3
- * app at build time. Apps `import { mount, useTable, ... } from "@lotics/app-sdk"`
4
- * and ship the resulting bundle via `lotics app deploy`.
3
+ * app at build time. Apps `import { mount, useQuery, useWorkflow } from
4
+ * "@lotics/app-sdk"` and ship the resulting bundle via `lotics app deploy`.
5
5
  *
6
6
  * Curated UI primitive re-exports from `@lotics/ui` are deliberately NOT
7
7
  * included here. Users import them separately from a published `@lotics/ui`
@@ -10,5 +10,5 @@
10
10
  * depending on packages/ui's React Native Web setup.
11
11
  */
12
12
  export { mount } from "./mount.js";
13
- export { useTable, useMutate, useAction, useWorkflow, useQuery } from "./hooks.js";
13
+ export { useWorkflow, useQuery } from "./hooks.js";
14
14
  export { rpc } from "./rpc.js";
package/dist/src/rpc.d.ts CHANGED
@@ -10,9 +10,8 @@
10
10
  * iframe → parent: { id: number, op: string, payload: unknown }
11
11
  * parent → iframe: { id: number, type: "result", data } | { id, type: "error", message }
12
12
  *
13
- * Bumping protocol version requires a coordinated change in the parent
14
- * old bundles must keep working forever, since we can't force users to
15
- * redeploy. Add new ops alongside existing ones; never repurpose them.
13
+ * Bumping protocol version requires a coordinated change in the parent.
14
+ * Add new ops alongside existing ones; never repurpose them.
16
15
  */
17
- export type RpcOp = "query" | "mutate" | "action" | "workflow" | "filter";
16
+ export type RpcOp = "query" | "workflow";
18
17
  export declare function rpc<T = unknown>(op: RpcOp, payload: unknown): Promise<T>;
package/dist/src/rpc.js CHANGED
@@ -10,9 +10,8 @@
10
10
  * iframe → parent: { id: number, op: string, payload: unknown }
11
11
  * parent → iframe: { id: number, type: "result", data } | { id, type: "error", message }
12
12
  *
13
- * Bumping protocol version requires a coordinated change in the parent
14
- * old bundles must keep working forever, since we can't force users to
15
- * redeploy. Add new ops alongside existing ones; never repurpose them.
13
+ * Bumping protocol version requires a coordinated change in the parent.
14
+ * Add new ops alongside existing ones; never repurpose them.
16
15
  */
17
16
  const pending = new Map();
18
17
  let nextRpcId = 0;
@@ -1,71 +1,49 @@
1
1
  /**
2
- * Workspace-specific type augmentation point.
2
+ * App-specific workflow augmentation point.
3
3
  *
4
- * The base SDK ships `WorkspaceTables` empty — every table read returns rows
5
- * of `Record<string, unknown>`. The `lotics types` codegen writes a file
6
- * (typically `.lotics/types.ts`) that extends this interface with the user's
7
- * actual table schemas via TypeScript's module augmentation:
4
+ * The base SDK ships `AppWorkflows` empty — `useWorkflow(alias)` accepts any
5
+ * string at runtime. Per-app codegen (folded into `lotics app pull`) emits a
6
+ * file that augments this interface with the aliases declared in the app's
7
+ * `package.json` lotics.workflows, giving compile-time autocomplete +
8
+ * "undeclared alias" errors:
8
9
  *
9
10
  * ```ts
10
- * // .lotics/types.ts (generated)
11
+ * // .lotics/app_workflows.d.ts (generated)
11
12
  * import "@lotics/app-sdk";
12
13
  * declare module "@lotics/app-sdk" {
13
- * interface WorkspaceTables {
14
- * "tbl_orders": { container_no: string; status: "active" | "closed" };
14
+ * interface AppWorkflows {
15
+ * "issueInvoiceStorageDrop": { record_id: string };
16
+ * "issueInvoiceReuseLift": Record<string, never>;
15
17
  * }
16
18
  * }
17
19
  * ```
18
20
  *
19
- * After that, `useTable("tbl_orders")` is fully typed. Without the augmented
20
- * file in tsconfig's include list, table IDs are typed as `string` and rows
21
- * are `Record<string, unknown>` — code still runs, just untyped.
21
+ * The value type is the workflow's declared input shape — `Record<string, never>`
22
+ * for a workflow that takes no typed inputs, the typed object otherwise.
22
23
  */
23
- export interface WorkspaceTables {
24
+ export interface AppWorkflows {
24
25
  }
25
26
  /**
26
- * App-specific workflow augmentation point. Same pattern as WorkspaceTables.
27
+ * App-specific named-query augmentation point. Same pattern as AppWorkflows.
27
28
  *
28
- * The base SDK ships `AppWorkflows` empty — `useWorkflow(alias)` accepts any
29
- * string at runtime. Per-app codegen (folded into `lotics app pull`) emits a
30
- * file that augments this interface with the aliases declared in the app's
31
- * `package.json` lotics.workflows, giving compile-time autocomplete +
32
- * "undeclared alias" errors:
29
+ * The base SDK ships `AppQueries` empty — `useQuery(alias)` accepts any string
30
+ * at runtime. Per-app codegen (`lotics app pull`) emits a file that augments
31
+ * this interface with the queries declared in the app's `package.json`
32
+ * lotics.queries, mapping each alias to its declared param type:
33
33
  *
34
34
  * ```ts
35
- * // .lotics/types.ts (generated)
35
+ * // .lotics/app_queries.d.ts (generated)
36
36
  * import "@lotics/app-sdk";
37
37
  * declare module "@lotics/app-sdk" {
38
- * interface AppWorkflows {
39
- * "issueInvoiceStorageDrop": never;
40
- * "issueInvoiceReuseLift": never;
38
+ * interface AppQueries {
39
+ * "openOrders": { status: string };
40
+ * "allContainers": Record<string, never>;
41
41
  * }
42
42
  * }
43
43
  * ```
44
44
  *
45
- * The `never` value is a placeholder for v2 input/output typing when the
46
- * codegen learns to extract workflow trigger schemas, the value becomes the
47
- * input type. For now the hook's runtime signature is unaffected.
45
+ * The value type is the query's declared param shape`Record<string, never>`
46
+ * for a query that takes no params, the typed object otherwise.
48
47
  */
49
- export interface AppWorkflows {
48
+ export interface AppQueries {
50
49
  }
51
- /**
52
- * Helper: row type for a known table id, or fallback for unknown ones.
53
- * Currently unused by exported hooks (useRecord deferred to v2) but kept
54
- * for the eventual augmented-typing path.
55
- */
56
- export type RowOf<K extends string> = K extends keyof WorkspaceTables ? WorkspaceTables[K] : Record<string, unknown>;
57
- /** Source addressing emitted by the server for every record-derived row. */
58
- export interface SourceAddressing {
59
- __source_table_id?: string;
60
- __source_record_id?: string;
61
- __source_locked?: boolean;
62
- }
63
- /** A single record row plus source-addressing metadata. */
64
- export type TableRow<K extends string> = RowOf<K> & SourceAddressing;
65
- /**
66
- * Query AST passed to `useQuery` for power-user composition. Mirrors
67
- * `AppDataSourceQuery.root` server-side. Kept opaque (`unknown`) here
68
- * because the recursive zod schema doesn't translate to a clean TS type.
69
- * The server validates via `parseQueryNode`.
70
- */
71
- export type QueryAst = unknown;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lotics/app-sdk",
3
- "version": "0.2.0",
3
+ "version": "0.5.0",
4
4
  "description": "Runtime SDK for Lotics custom-code apps — typed hooks, postMessage bridge, mount entry point",
5
5
  "type": "module",
6
6
  "exports": {