primitive-functions 0.3.0-alpha.14 → 0.3.0-alpha.16

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.
Files changed (2) hide show
  1. package/index.d.ts +412 -72
  2. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -283,7 +283,7 @@ export interface CollectionCreateBody {
283
283
 
284
284
  /**
285
285
  * The typed HTTP profile, generated from the platform's OpenAPI document. Its
286
- * namespaces mirror the operation ids: agentSessions, analytics, blobBuckets, channels, collections, configVars, connections, databaseTypeConfigs, databases, db3, documents, email, functions, groups, integrations, invitations, locks, notifications, prompts, resourceMetadata, secrets, users.
286
+ * namespaces mirror the operation ids: agentSessions, analytics, blobBuckets, channels, collections, configVars, connections, databaseTypeConfigs, databases, db3, documents, email, functions, groups, integrations, invitations, locks, notifications, prompts, resourceMetadata, secrets, usage, users.
287
287
  * Methods take one options object carrying the operation's path parameters,
288
288
  * query parameters, request headers (under their wire names) and `body`.
289
289
  *
@@ -1841,10 +1841,7 @@ export interface FunctionApi {
1841
1841
  }>;
1842
1842
  };
1843
1843
  "configVars": {
1844
- /**
1845
- * `configVars.get` — GET /config-vars/{name}. Read an app config var under a server function's grants
1846
- * @beta
1847
- */
1844
+ /** `configVars.get` — GET /config-vars/{name}. Read an app config var under a server function's grants */
1848
1845
  "get"(args: {
1849
1846
  "name": string | number;
1850
1847
  }): Promise<{
@@ -1853,10 +1850,7 @@ export interface FunctionApi {
1853
1850
  }>;
1854
1851
  };
1855
1852
  "connections": {
1856
- /**
1857
- * `connections.send` — POST /connections/{connectionId}/send. Send a realtime message to one connection of this app
1858
- * @beta
1859
- */
1853
+ /** `connections.send` — POST /connections/{connectionId}/send. Send a realtime message to one connection of this app */
1860
1854
  "send"(args: {
1861
1855
  "connectionId": string | number;
1862
1856
  body: {
@@ -2048,6 +2042,7 @@ export interface FunctionApi {
2048
2042
  "update"(args: {
2049
2043
  "databaseType": string | number;
2050
2044
  "dryRun"?: string | number | boolean;
2045
+ "allowFieldRemoval"?: string | number | boolean;
2051
2046
  body: {
2052
2047
  autoPopulatedFields?: unknown;
2053
2048
  expectedModifiedAt?: unknown;
@@ -2100,6 +2095,17 @@ export interface FunctionApi {
2100
2095
  statusPath?: string;
2101
2096
  error?: string;
2102
2097
  } | null;
2098
+ /** Present when `allowFieldRemoval=true` let changes the append-only rule refuses through: each one */
2099
+ appendOnlyOverride?: {
2100
+ reasons?: {
2101
+ /** `models.<model>` or `models.<model>.fields.<field>` */
2102
+ path: string;
2103
+ /** `model-removed`, `field-removed`, `field-type-changed`, `enum-value-removed`, `field-made-required`, `required-field-added` or `vector-changed` */
2104
+ change: string;
2105
+ /** The change and what to do instead */
2106
+ reason: string;
2107
+ }[];
2108
+ };
2103
2109
  }>;
2104
2110
  };
2105
2111
  "databases": {
@@ -4828,7 +4834,7 @@ export interface FunctionApi {
4828
4834
  code?: string;
4829
4835
  status?: number;
4830
4836
  error?: string;
4831
- /** For an op refused `DB3_TRIGGER_REFUSED`: the refusing trigger's own code. */
4837
+ /** For an op refused `DB3_TRIGGER_REFUSED`: the refusing trigger's own code, or `TRIGGER_EVALUATION_FAILED` when its `when` could not be evaluated. */
4832
4838
  reason?: string;
4833
4839
  requestId?: string;
4834
4840
  }[];
@@ -5638,6 +5644,35 @@ export interface FunctionApi {
5638
5644
  /** The db3's type; null while it has none */
5639
5645
  type: string | null;
5640
5646
  }>;
5647
+ /**
5648
+ * `db3.update` — PUT /db3/{db3Id}. Rename a db3
5649
+ * @beta
5650
+ */
5651
+ "update"(args: {
5652
+ "db3Id": string | number;
5653
+ body: {
5654
+ /** The db3's new title, at most 255 characters, stored trimmed. A blank one is refused. */
5655
+ title: string;
5656
+ };
5657
+ }): Promise<{
5658
+ id: string;
5659
+ title: string | null;
5660
+ createdAt: string;
5661
+ modifiedAt: string;
5662
+ /** The user the db3 was created for, or `sys:<appId>` for a db3 the app created */
5663
+ createdBy: string;
5664
+ /** Who holds the db3: `user:<userId>` or `app` */
5665
+ custodian: string | null;
5666
+ sync: boolean;
5667
+ /** The db3's type; null while it has none */
5668
+ type: string | null;
5669
+ tags: string[];
5670
+ /** The caller's level; absent for the app-admin arm */
5671
+ permission?: string;
5672
+ /** How the caller holds it: `owner`, `grant` (a direct grant), `group`, `link`, `app` (the db3's app access), or `resource` (a member of the resource that holds the db3, such as an agent session) */
5673
+ accessSource?: string;
5674
+ grantedAt?: string;
5675
+ }>;
5641
5676
  /**
5642
5677
  * `db3.updatePermissions` — PUT /db3/{db3Id}/permissions. Grant or update a user's permission on a db3
5643
5678
  * @beta
@@ -7729,7 +7764,7 @@ export interface FunctionApi {
7729
7764
  code?: string;
7730
7765
  status?: number;
7731
7766
  error?: string;
7732
- /** For an op refused `DB3_TRIGGER_REFUSED`: the refusing trigger's own code. */
7767
+ /** For an op refused `DB3_TRIGGER_REFUSED`: the refusing trigger's own code, or `TRIGGER_EVALUATION_FAILED` when its `when` could not be evaluated. */
7733
7768
  reason?: string;
7734
7769
  requestId?: string;
7735
7770
  }[];
@@ -8354,10 +8389,7 @@ export interface FunctionApi {
8354
8389
  }>;
8355
8390
  };
8356
8391
  "email": {
8357
- /**
8358
- * `email.send` — POST /emails/send. Send an application email under a server function's grant
8359
- * @beta
8360
- */
8392
+ /** `email.send` — POST /emails/send. Send an application email under a server function's grant */
8361
8393
  "send"(args: {
8362
8394
  body: {
8363
8395
  /** The recipient's email address. */
@@ -9335,10 +9367,7 @@ export interface FunctionApi {
9335
9367
  inviteToken: string | null;
9336
9368
  status: "pending" | "expired" | "accepted";
9337
9369
  }>;
9338
- /**
9339
- * `invitations.getBy` — POST /invitations/get-by. Find the pending invitation that carries a unique property value
9340
- * @beta
9341
- */
9370
+ /** `invitations.getBy` — POST /invitations/get-by. Find the pending invitation that carries a unique property value */
9342
9371
  "getBy"(args: {
9343
9372
  body: {
9344
9373
  /** A unique property's name. */
@@ -9519,7 +9548,10 @@ export interface FunctionApi {
9519
9548
  hasMore: boolean;
9520
9549
  nextCursor?: string;
9521
9550
  }>;
9522
- /** `notifications.listDevices` — GET /me/push-tokens. List the caller's registered push devices */
9551
+ /**
9552
+ * `notifications.listDevices` — GET /me/push-tokens. List the caller's registered push devices
9553
+ * @experimental
9554
+ */
9523
9555
  "listDevices"(args?: {
9524
9556
  "userId"?: string | number;
9525
9557
  }): Promise<{
@@ -9563,7 +9595,10 @@ export interface FunctionApi {
9563
9595
  sourceRef?: string;
9564
9596
  createdAt: string;
9565
9597
  }>;
9566
- /** `notifications.registerDevice` — POST /me/push-tokens. Register (upsert) the caller's device push token */
9598
+ /**
9599
+ * `notifications.registerDevice` — POST /me/push-tokens. Register (upsert) the caller's device push token
9600
+ * @experimental
9601
+ */
9567
9602
  "registerDevice"(args: {
9568
9603
  "userId"?: string | number;
9569
9604
  body: {
@@ -9628,7 +9663,10 @@ export interface FunctionApi {
9628
9663
  }): Promise<{
9629
9664
  unreadCount: number;
9630
9665
  }>;
9631
- /** `notifications.unregisterDevice` — DELETE /me/push-tokens/{token}. Unregister one of the caller's device push tokens */
9666
+ /**
9667
+ * `notifications.unregisterDevice` — DELETE /me/push-tokens/{token}. Unregister one of the caller's device push tokens
9668
+ * @experimental
9669
+ */
9632
9670
  "unregisterDevice"(args: {
9633
9671
  "token": string | number;
9634
9672
  "userId"?: string | number;
@@ -9781,10 +9819,7 @@ export interface FunctionApi {
9781
9819
  }>;
9782
9820
  };
9783
9821
  "secrets": {
9784
- /**
9785
- * `secrets.get` — GET /secrets/{name}. Read an app secret under a server function's grants
9786
- * @beta
9787
- */
9822
+ /** `secrets.get` — GET /secrets/{name}. Read an app secret under a server function's grants */
9788
9823
  "get"(args: {
9789
9824
  "name": string | number;
9790
9825
  }): Promise<{
@@ -9792,6 +9827,37 @@ export interface FunctionApi {
9792
9827
  value?: string;
9793
9828
  }>;
9794
9829
  };
9830
+ "usage": {
9831
+ /**
9832
+ * `usage.forUser` — GET /usage/users/{userId}. Get one member's usage over a window and the bytes they own
9833
+ * @beta
9834
+ */
9835
+ "forUser"(args: {
9836
+ "userId": string | number;
9837
+ "since"?: string | number | boolean;
9838
+ "until"?: string | number | boolean;
9839
+ }): Promise<{
9840
+ appId: string;
9841
+ userId: string;
9842
+ /** The window's start, ISO 8601 UTC */
9843
+ since: string;
9844
+ /** The window's end, ISO 8601 UTC, exclusive */
9845
+ until: string;
9846
+ meters: {
9847
+ meter: string;
9848
+ unit: string;
9849
+ quantity: number;
9850
+ /** The bytes the window's points carried */
9851
+ bytes: number;
9852
+ /** How many sampled points the figure rests on */
9853
+ points: number;
9854
+ }[];
9855
+ storage: {
9856
+ meter: string;
9857
+ bytes: number;
9858
+ }[];
9859
+ }>;
9860
+ };
9795
9861
  "users": {
9796
9862
  /**
9797
9863
  * `users.aggregate` — POST /users/aggregate. Aggregate the app's users from a server function
@@ -10548,6 +10614,26 @@ export type Db3ModelFilterOf<TQueries, M extends string> = M extends keyof TQuer
10548
10614
  : Record<string, unknown>
10549
10615
  : Record<string, unknown>;
10550
10616
 
10617
+ /**
10618
+ * The names an upsert of model `M` takes when `TQueries` types them (its
10619
+ * unique fields and named unique constraints, `Db3.<Model>Unique`), `string`
10620
+ * otherwise.
10621
+ */
10622
+ export type Db3ModelUniqueOf<TQueries, M extends string> = M extends keyof TQueries
10623
+ ? TQueries[M] extends { unique: infer U }
10624
+ ? U
10625
+ : string
10626
+ : string;
10627
+
10628
+ /**
10629
+ * What an upsert's `upsertOn` or `constraint` takes, given the name as
10630
+ * written (`TName`) and the model's names (`TUnique`): a string literal
10631
+ * must be one of the model's names, so a typo or a field that is not unique
10632
+ * fails typecheck; a computed `string` compiles, and the server refuses it
10633
+ * 400 `DOCUMENT_ENTRY_INVALID` when it names neither.
10634
+ */
10635
+ export type Db3UpsertName<TName extends string, TUnique> = string extends TName ? TName : TUnique;
10636
+
10551
10637
  /** Model `M`'s sort type when `TQueries` types it, `Record<string, 1 | -1>` otherwise. */
10552
10638
  export type Db3ModelSortOf<TQueries, M extends string> = M extends keyof TQueries
10553
10639
  ? TQueries[M] extends { sort: infer S }
@@ -10765,29 +10851,58 @@ export interface Db3StringSetChange {
10765
10851
 
10766
10852
  /**
10767
10853
  * The `data` a db3 write takes: any of the row's fields, each optional, and a
10768
- * `Db3StringSetChange` on a string-set field beside the set itself.
10854
+ * `Db3StringSetChange` on a string-set field beside the set itself. A field
10855
+ * the model leaves optional also takes `null`, which stores a null in place of
10856
+ * the value (on a string set, an empty set); a required field does not.
10857
+ *
10858
+ * ```ts
10859
+ * await tasks.patch(id, { data: { note: null } });
10860
+ * ```
10769
10861
  */
10770
10862
  export type Db3WriteData<TRow> = {
10771
- [K in keyof TRow]?: TRow[K] | (NonNullable<TRow[K]> extends string[] ? Db3StringSetChange : never);
10863
+ [K in keyof TRow]?:
10864
+ | TRow[K]
10865
+ | (NonNullable<TRow[K]> extends string[] ? Db3StringSetChange : never)
10866
+ | (undefined extends TRow[K] ? null : never);
10772
10867
  };
10773
10868
 
10774
10869
  /**
10775
10870
  * One write of a db3 `batch`, typed to a model's row. `condition` is a guard
10776
10871
  * in the query filter grammar: the op applies only when the record is live and
10777
- * matches it.
10872
+ * matches it. An `upsert`'s `constraint` names a unique field or a named
10873
+ * unique constraint of the model (`TConstraint`).
10778
10874
  */
10779
- export type Db3BatchOp<TRow = Record<string, unknown>> =
10875
+ export type Db3BatchOp<TRow = Record<string, unknown>, TConstraint = string> =
10780
10876
  | { action: "create"; id?: string; data: Db3WriteData<TRow>; condition?: Record<string, unknown>; requestId?: string }
10781
10877
  | { action: "patch"; id: string; data: Db3WriteData<TRow>; condition?: Record<string, unknown>; requestId?: string }
10782
10878
  | { action: "delete"; id: string; condition?: Record<string, unknown>; requestId?: string }
10783
- | { action: "upsert"; constraint: string; id?: string; data: Db3WriteData<TRow>; condition?: Record<string, unknown>; requestId?: string }
10879
+ | { action: "upsert"; constraint: TConstraint; id?: string; data: Db3WriteData<TRow>; condition?: Record<string, unknown>; requestId?: string }
10784
10880
  | { action: "increment"; id: string; fields: Record<string, number>; condition?: Record<string, unknown>; requestId?: string };
10785
10881
 
10786
- /** One write of a handle-level `batch`: its `model` picks the row its `data` is typed to. */
10787
- export type Db3HandleBatchOp<TModels> = {
10788
- [M in Db3ModelNames<TModels>]: Db3BatchOp<Db3ModelRow<TModels, M>> & { model: M };
10882
+ /**
10883
+ * One write of a handle-level `batch`: its `model` picks the row its `data`
10884
+ * is typed to, and the names an `upsert`'s `constraint` takes when
10885
+ * `TQueries` types them.
10886
+ */
10887
+ export type Db3HandleBatchOp<TModels, TQueries = {}, TConstraint extends string = string> = {
10888
+ [M in Db3ModelNames<TModels>]: Db3BatchOp<Db3ModelRow<TModels, M>, Db3UpsertName<TConstraint, Db3ModelUniqueOf<TQueries, M>>> & { model: M };
10789
10889
  }[Db3ModelNames<TModels>];
10790
10890
 
10891
+ /**
10892
+ * The ops of a model's `batch`, checked one by one: `TConstraints` holds
10893
+ * the name each op's `upsert` writes, inferred per op, so a computed
10894
+ * `string` in one op leaves another op's literal checked against the
10895
+ * model's names (`TUnique`).
10896
+ */
10897
+ export type Db3BatchOps<TRow, TUnique, TConstraints extends readonly unknown[]> = {
10898
+ [K in keyof TConstraints]: Db3BatchOp<TRow, Db3UpsertName<Extract<TConstraints[K], string>, TUnique>> | Db3BatchReadOp;
10899
+ };
10900
+
10901
+ /** The ops of a handle-level `batch`, checked one by one as `Db3BatchOps` are, each by its own `model`. */
10902
+ export type Db3HandleBatchOps<TModels, TQueries, TConstraints extends readonly unknown[]> = {
10903
+ [K in keyof TConstraints]: Db3HandleBatchOp<TModels, TQueries, Extract<TConstraints[K], string>> | Db3HandleBatchReadOp<TModels>;
10904
+ };
10905
+
10791
10906
  /**
10792
10907
  * One read of a db3 batch at a model: a `query` with what `query` takes, a
10793
10908
  * `count` with its filter, or an `aggregate` with what `aggregate` takes,
@@ -10861,7 +10976,7 @@ export interface Db3BatchResult {
10861
10976
  * `DB3_RECORD_NOT_FOUND`, a model the type does not declare 400
10862
10977
  * `DB3_MODEL_NOT_DECLARED`.
10863
10978
  */
10864
- export interface Db3ModelHandle<TRow, TQuery = DocumentQueryOptions, TCount = { filter?: Record<string, unknown> | string }, TAggregate = Record<string, unknown>> {
10979
+ export interface Db3ModelHandle<TRow, TQuery = DocumentQueryOptions, TCount = { filter?: Record<string, unknown> | string }, TAggregate = Record<string, unknown>, TUnique = string> {
10865
10980
  /**
10866
10981
  * The record with this id, or `null` when there is none.
10867
10982
  * @beta
@@ -10882,16 +10997,18 @@ export interface Db3ModelHandle<TRow, TQuery = DocumentQueryOptions, TCount = {
10882
10997
  /**
10883
10998
  * Create or replace a record; the id is minted when omitted. `ifNotExists`
10884
10999
  * applies only when no record has the id, `upsertOn` lands on the record
10885
- * holding the same unique key. `appliedFields` names what the type's hook
11000
+ * holding the same unique key: it names a unique field or a named unique
11001
+ * constraint of the model (`TUnique`), and any other name is refused 400
11002
+ * `DOCUMENT_ENTRY_INVALID`. `appliedFields` names what the type's hook
10886
11003
  * rules wrote.
10887
11004
  * @beta
10888
11005
  */
10889
- save(body: {
11006
+ save<TUpsertOn extends string = string>(body: {
10890
11007
  id?: string;
10891
11008
  data: Db3WriteData<TRow>;
10892
11009
  condition?: Record<string, unknown>;
10893
11010
  ifNotExists?: boolean;
10894
- upsertOn?: string;
11011
+ upsertOn?: Db3UpsertName<TUpsertOn, TUnique>;
10895
11012
  requestId?: string;
10896
11013
  }): Promise<{ record: TRow; appliedFields?: Record<string, unknown> }>;
10897
11014
  /**
@@ -10922,7 +11039,10 @@ export interface Db3ModelHandle<TRow, TQuery = DocumentQueryOptions, TCount = {
10922
11039
  * or each on its own with `atomic: false`.
10923
11040
  * @beta
10924
11041
  */
10925
- batch(ops: Array<Db3BatchOp<TRow> | Db3BatchReadOp>, options?: { atomic?: boolean; requestId?: string }): Promise<Db3BatchResult>;
11042
+ batch<TConstraints extends readonly unknown[] = unknown[]>(
11043
+ ops: [...Db3BatchOps<TRow, TUnique, TConstraints>],
11044
+ options?: { atomic?: boolean; requestId?: string }
11045
+ ): Promise<Db3BatchResult>;
10926
11046
  /**
10927
11047
  * Several reads of this model in one request, answered from one state of the db3.
10928
11048
  * @beta
@@ -10940,13 +11060,13 @@ export interface Db3Handle<TModels, TQueries = {}> {
10940
11060
  /** The type key this handle was opened with. */
10941
11061
  type: string;
10942
11062
  /** @beta */
10943
- model<M extends Db3ModelNames<TModels>>(modelName: M): Db3ModelHandle<Db3ModelRow<TModels, M>, Db3ModelQueryOptions<TQueries, M>, Db3ModelCountOptions<TQueries, M>, Db3ModelAggregateBody<TQueries, M>>;
11063
+ model<M extends Db3ModelNames<TModels>>(modelName: M): Db3ModelHandle<Db3ModelRow<TModels, M>, Db3ModelQueryOptions<TQueries, M>, Db3ModelCountOptions<TQueries, M>, Db3ModelAggregateBody<TQueries, M>, Db3ModelUniqueOf<TQueries, M>>;
10944
11064
  /**
10945
11065
  * Writes and reads across models in one request (at most 100); each op names its `model`.
10946
11066
  * @beta
10947
11067
  */
10948
- batch(
10949
- ops: Array<Db3HandleBatchOp<TModels> | Db3HandleBatchReadOp<TModels>>,
11068
+ batch<TConstraints extends readonly unknown[] = unknown[]>(
11069
+ ops: [...Db3HandleBatchOps<TModels, TQueries, TConstraints>],
10950
11070
  options?: { atomic?: boolean; requestId?: string }
10951
11071
  ): Promise<Db3BatchResult>;
10952
11072
  /**
@@ -11257,6 +11377,43 @@ export interface AgentSessionDeleteResult {
11257
11377
  sessionId: string;
11258
11378
  }
11259
11379
 
11380
+ /** The window `ctx.usage.forUser` reads: ISO 8601 strings or `Date`s, UTC, half-open. */
11381
+ export interface UsageWindowOptions {
11382
+ /** Start, inclusive. Default 30 days before `until`; no earlier than 90 days ago. */
11383
+ since?: string | Date;
11384
+ /** End, exclusive. Default now. */
11385
+ until?: string | Date;
11386
+ }
11387
+
11388
+ /** One meter of a member's usage: what they drove in the window, as a quantity. */
11389
+ export interface UserUsageMeter {
11390
+ meter: string;
11391
+ unit: string;
11392
+ quantity: number;
11393
+ /** The bytes the window's points carried. */
11394
+ bytes: number;
11395
+ /** How many sampled points the figure rests on. */
11396
+ points: number;
11397
+ }
11398
+
11399
+ /** The bytes a member owns now under one storage meter. */
11400
+ export interface UserUsageStorage {
11401
+ meter: string;
11402
+ bytes: number;
11403
+ }
11404
+
11405
+ /** What `ctx.usage.forUser` answers: quantities and bytes, never a cost. */
11406
+ export interface UserUsage {
11407
+ appId: string;
11408
+ userId: string;
11409
+ /** The window's start, ISO 8601 UTC. */
11410
+ since: string;
11411
+ /** The window's end, ISO 8601 UTC, exclusive. */
11412
+ until: string;
11413
+ meters: UserUsageMeter[];
11414
+ storage: UserUsageStorage[];
11415
+ }
11416
+
11260
11417
  /** One agent's client tools, by name: each one's `input` and `output` (#3798). */
11261
11418
  export type AgentClientTools<K extends AgentKeys> = PromptSchemas[K] extends {
11262
11419
  agent: { clientTools: infer T };
@@ -11896,6 +12053,7 @@ export interface FunctionContext {
11896
12053
  * the code that asked for it.
11897
12054
  */
11898
12055
  integrations: {
12056
+ /** @public */
11899
12057
  call(
11900
12058
  integrationKey: string,
11901
12059
  request?: IntegrationCallRequest
@@ -11914,6 +12072,7 @@ export interface FunctionContext {
11914
12072
  * Nesting is bounded at four levels.
11915
12073
  */
11916
12074
  functions: {
12075
+ /** @public */
11917
12076
  start(
11918
12077
  functionKey: string,
11919
12078
  input?: unknown,
@@ -11944,6 +12103,7 @@ export interface FunctionContext {
11944
12103
  * Once a tree has pushed, a key it does not declare is a compile error.
11945
12104
  */
11946
12105
  prompts: {
12106
+ /** @public */
11947
12107
  run<K extends PromptKeys>(
11948
12108
  promptKey: K,
11949
12109
  args?: PromptRunArgs
@@ -12008,6 +12168,26 @@ export interface FunctionContext {
12008
12168
  options?: AgentSessionSubjectOptions
12009
12169
  ): Promise<AgentSessionDeleteResult>;
12010
12170
  };
12171
+ /**
12172
+ * One member's usage in this app, read-only.
12173
+ *
12174
+ * `forUser` answers what `userId` drove over a UTC, half-open window, as
12175
+ * a quantity per meter (costliest meter first), and the bytes they own now
12176
+ * per storage meter. No field carries a cost. The window defaults to the
12177
+ * 30 days before now; `since` may be no earlier than 90 days ago
12178
+ * (`USAGE_WINDOW_TOO_OLD`), and a `Date` is sent as its ISO string.
12179
+ *
12180
+ * Naming follows the header's subject rule for a read: a run may read its
12181
+ * own caller; a run with no caller, or one an app owner or admin invoked,
12182
+ * may read any member; a member's run may read another member only when
12183
+ * this function declares `users:readAny`; a run an agent drives reads
12184
+ * only its initiator (`SUBJECT_USER_FORBIDDEN`). Someone who is not a
12185
+ * member of this app is `SUBJECT_USER_NOT_FOUND`.
12186
+ */
12187
+ usage: {
12188
+ /** @beta */
12189
+ forUser(userId: string, options?: UsageWindowOptions): Promise<UserUsage>;
12190
+ };
12011
12191
  /**
12012
12192
  * The value of one app secret, under a `secret:<NAME>` grant (#3183).
12013
12193
  *
@@ -12018,12 +12198,12 @@ export interface FunctionContext {
12018
12198
  * Rejects with `FUNCTION_SECRET_NOT_FOUND` when the grant names a value
12019
12199
  * this environment has not been given — secrets are provisioned per
12020
12200
  * environment, out of band from the push.
12021
- * @beta
12201
+ * @public
12022
12202
  */
12023
12203
  secret(name: string): Promise<string>;
12024
12204
  /**
12025
12205
  * The value of one app config var, under a `var:<NAME>` grant (#3183).
12026
- * @beta
12206
+ * @public
12027
12207
  */
12028
12208
  configVar(name: string): Promise<string>;
12029
12209
  /**
@@ -12045,6 +12225,7 @@ export interface FunctionContext {
12045
12225
  * `limit` is capped by the route at 100.
12046
12226
  *
12047
12227
  * Prefer `ctx.users.query`, which filters, sorts and pages up to 1,000.
12228
+ * @public
12048
12229
  */
12049
12230
  list(options?: UserPageOptions): Promise<UserPage>;
12050
12231
  /**
@@ -12056,6 +12237,7 @@ export interface FunctionContext {
12056
12237
  * replay pages it had already taken.
12057
12238
  *
12058
12239
  * Prefer `ctx.users.query`, which filters, sorts and pages up to 1,000.
12240
+ * @public
12059
12241
  */
12060
12242
  iterate(options?: UserPageOptions): AsyncIterable<UserPage>;
12061
12243
  /**
@@ -12097,6 +12279,7 @@ export interface FunctionContext {
12097
12279
  * @beta
12098
12280
  */
12099
12281
  forEachBatch(options: UserWalkOptions): Promise<UserWalkStart>;
12282
+ /** @public */
12100
12283
  send(userId: string, payload: unknown): Promise<SendResult>;
12101
12284
  /**
12102
12285
  * One member with their properties — read from the source of truth, so a
@@ -12141,13 +12324,13 @@ export interface FunctionContext {
12141
12324
  * (an array in declared order, or an object by field name), as
12142
12325
  * `ctx.users.getBy` takes them. Null when no unaccepted, unexpired
12143
12326
  * invitation carries it; a value a user holds is `ctx.users.getBy`'s.
12144
- * @beta
12327
+ * @public
12145
12328
  */
12146
12329
  getBy(name: UniqueUserPropertyKey, value: unknown): Promise<PendingInvitation | null>;
12147
12330
  };
12148
12331
  /** The same frame to ONE connection, under a `connections:send` grant. */
12149
12332
  connections: {
12150
- /** @beta */
12333
+ /** @public */
12151
12334
  send(connectionId: string, payload: unknown): Promise<SendResult>;
12152
12335
  };
12153
12336
  /**
@@ -12191,9 +12374,13 @@ export interface FunctionContext {
12191
12374
  /**
12192
12375
  * Wait for `key`. Answers `acquired: true` with the handle, or
12193
12376
  * `acquired: false, timedOut: true` with the last contention seen.
12377
+ * @public
12194
12378
  */
12195
12379
  acquire(key: string, options: LockAcquireOptions): Promise<LockAcquireResult>;
12196
- /** Release a handle `acquire` handed back. */
12380
+ /**
12381
+ * Release a handle `acquire` handed back.
12382
+ * @public
12383
+ */
12197
12384
  release(handle: LockHandle): Promise<LockReleaseResult>;
12198
12385
  /**
12199
12386
  * Acquire, run `fn`, and release in `finally` — on a return and on a
@@ -12203,6 +12390,7 @@ export interface FunctionContext {
12203
12390
  * acquired within `timeoutMs`. A nested `withLock` on the same key in
12204
12391
  * one run re-enters, and its release frees the outer hold: use distinct
12205
12392
  * keys, or one wrapper.
12393
+ * @public
12206
12394
  */
12207
12395
  withLock<T>(
12208
12396
  key: string,
@@ -12490,7 +12678,10 @@ export interface AuthDb3ModelHandle<TRow, TQuery = DocumentQueryOptions> {
12490
12678
  export interface AuthDb3Handle<TModels, TQueries = {}> {
12491
12679
  /** @beta */
12492
12680
  model<M extends Db3ModelNames<TModels>>(modelName: M): AuthDb3ModelHandle<Db3ModelRow<TModels, M>, Db3ModelQueryOptions<TQueries, M>>;
12493
- /** The caller's level on the db3, or `null`: none, not a db3 of this app, or its sync is off. One read. */
12681
+ /**
12682
+ * The caller's level on the db3, or `null`: none, not a db3 of this app, or its sync is off. One read.
12683
+ * @beta
12684
+ */
12494
12685
  permissions(): Promise<DocumentPermission | null>;
12495
12686
  }
12496
12687
 
@@ -12501,7 +12692,10 @@ export interface AuthDocumentHandle {
12501
12692
  * @deprecated Use `auth.db3`.
12502
12693
  */
12503
12694
  get(): Promise<Record<string, any> | null>;
12504
- /** The caller's permission on the document, or `null` when they have none. */
12695
+ /**
12696
+ * The caller's permission on the document, or `null` when they have none.
12697
+ * @deprecated Use `auth.db3`.
12698
+ */
12505
12699
  permissions(): Promise<DocumentPermission | null>;
12506
12700
  /**
12507
12701
  * The document's tags, or `null` when this app has no such document.
@@ -12522,15 +12716,30 @@ export interface FunctionAuthContext {
12522
12716
  readonly user: FunctionAuthUser | null;
12523
12717
  /** What started this invocation. */
12524
12718
  readonly trigger: FunctionTrigger;
12525
- /** Whether the caller's app role is exactly `role`: `hasRole("admin")` is false for an owner. */
12719
+ /**
12720
+ * Whether the caller's app role is exactly `role`: `hasRole("admin")` is false for an owner.
12721
+ * @public
12722
+ */
12526
12723
  hasRole(role: string): boolean;
12527
- /** Every group the caller belongs to, loaded whole. */
12724
+ /**
12725
+ * Every group the caller belongs to, loaded whole.
12726
+ * @public
12727
+ */
12528
12728
  memberships(): Promise<AuthMembership[]>;
12529
- /** Whether the caller belongs to the group. */
12729
+ /**
12730
+ * Whether the caller belongs to the group.
12731
+ * @public
12732
+ */
12530
12733
  isMemberOf(groupId: string): Promise<boolean>;
12531
- /** The ids of the groups the caller belongs to. */
12734
+ /**
12735
+ * The ids of the groups the caller belongs to.
12736
+ * @public
12737
+ */
12532
12738
  memberGroups(): Promise<string[]>;
12533
- /** Whether the caller holds `role` or above on the group. */
12739
+ /**
12740
+ * Whether the caller holds `role` or above on the group.
12741
+ * @public
12742
+ */
12534
12743
  hasGroupRole(groupId: string, role: GroupRole): Promise<boolean>;
12535
12744
  /**
12536
12745
  * The caller's user properties (declared names only, defaults applied), or
@@ -12558,7 +12767,10 @@ export interface FunctionAuthContext {
12558
12767
  getBy(name: UniqueUserPropertyKey, value: unknown): Promise<AppUser | null>;
12559
12768
  };
12560
12769
  readonly collections: {
12561
- /** The caller's role on the collection, or `null` when they have none. */
12770
+ /**
12771
+ * The caller's role on the collection, or `null` when they have none.
12772
+ * @public
12773
+ */
12562
12774
  resolveRole(collectionId: string): Promise<CollectionRole | null>;
12563
12775
  };
12564
12776
  /**
@@ -12581,7 +12793,7 @@ export interface FunctionAuthContext {
12581
12793
  db3<K extends Db3TypeKeys>(db3Id: string, type: K): AuthDb3Handle<Db3Models<K>, Db3QueriesOf<K>>;
12582
12794
  /**
12583
12795
  * An app config var's value.
12584
- * @beta
12796
+ * @public
12585
12797
  */
12586
12798
  configVar(name: string): Promise<string>;
12587
12799
  }
@@ -12646,6 +12858,7 @@ export declare function deny(
12646
12858
  * import { defineFunction, fail, requireSignedIn } from "primitive-functions";
12647
12859
  *
12648
12860
  * export default defineFunction({
12861
+ * input: ["quantity"],
12649
12862
  * authorize: requireSignedIn(),
12650
12863
  * handler: async (input: { quantity: number }) => {
12651
12864
  * if (input.quantity > 100) fail("ORDER_TOO_LARGE", "orders are capped at 100 units");
@@ -12786,6 +12999,7 @@ export interface FunctionAuthorizedContext<TAuth> {
12786
12999
  * await step.sleep("cool-off", "1 hour");
12787
13000
  * await ctx.reauthorize(); // throws FORBIDDEN if the member left the group
12788
13001
  * ```
13002
+ * @public
12789
13003
  */
12790
13004
  reauthorize(): Promise<TAuth>;
12791
13005
  }
@@ -12824,15 +13038,106 @@ interface AuthorizeNotInferred {
12824
13038
  }
12825
13039
 
12826
13040
  /**
12827
- * The object form's definition: an `authorize` method beside the handler.
12828
- * `TAuth` is what `authorize`'s `allow` resolves, and the handler reads
12829
- * it as `ctx.auth`. `TAuthorized` is what `authorize` is held to, and
12830
- * only `defineFunction` sets it apart from `TAuth`.
13041
+ * The keys an object form's `input` list may name: every top-level property
13042
+ * the input declares, across a union's members. An index signature adds
13043
+ * none, and an input typed `any` accepts any string.
13044
+ */
13045
+ export type FunctionInputKey<TInput> = 0 extends 1 & TInput
13046
+ ? string
13047
+ : TInput extends unknown
13048
+ ? keyof {
13049
+ [P in keyof TInput as string extends P
13050
+ ? never
13051
+ : number extends P
13052
+ ? never
13053
+ : symbol extends P
13054
+ ? never
13055
+ : P]: unknown;
13056
+ } & string
13057
+ : never;
13058
+
13059
+ /**
13060
+ * What an object form's handler reads as `input`: the input picked to the
13061
+ * keys its `input` list names, member by member for a union, and `{}` when
13062
+ * the list names nothing.
12831
13063
  */
12832
- export interface FunctionDefinition<TInput, TOutput, TAuth, TAuthorized = TAuth> {
13064
+ export type FunctionApprovedInput<TInput, I extends PropertyKey> = [I] extends [never]
13065
+ ? {}
13066
+ : TInput extends unknown
13067
+ ? Pick<TInput, Extract<I, keyof TInput>>
13068
+ : never;
13069
+
13070
+ // Names a type where the compiler must not infer from it, so the `input`
13071
+ // list is the only place the approved keys come from and the checks below
13072
+ // only ever read what was inferred elsewhere. Not the intrinsic `NoInfer`,
13073
+ // which would raise the TypeScript these declarations need to 5.4.
13074
+ type ListedOnly<T> = [T][T extends any ? 0 : never];
13075
+
13076
+ // The type an object form's `input` list is checked against, once the list
13077
+ // `L` is inferred: `L` itself when every key it names is one of `TKey`,
13078
+ // and the keys otherwise, so the refusal names the key. The list is a
13079
+ // literal array (a tuple once inferred): a widened array, whose type does
13080
+ // not say which keys it holds, is refused, so its type never approves a key
13081
+ // the value may not name. The check sits here and not in a constraint on
13082
+ // `L`: an `authorize` whose `auth` is not annotated supplies the unkeyed
13083
+ // `TInput` only after the list is read, and a constraint over it would see
13084
+ // no keys.
13085
+ type ListedList<L extends readonly string[], TKey extends string> = [L[number]] extends [TKey]
13086
+ ? number extends L["length"]
13087
+ ? readonly ["an input list is a literal array of the keys the handler reads"]
13088
+ : L
13089
+ : readonly TKey[];
13090
+
13091
+ // The unkeyed form's keys, over `keyof`: a mapped type here fixes `TInput`
13092
+ // before an `authorize` whose `auth` is not annotated is read.
13093
+ type ListedInputKey<TInput> = TInput extends unknown ? keyof TInput & string : never;
13094
+
13095
+ // A list named in explicit type arguments is still written on the
13096
+ // definition: the type arguments alone approve nothing.
13097
+ type ListWritten<L> = [L] extends [never] ? {} : L extends readonly [] ? {} : { input: unknown };
13098
+
13099
+ // The keys a handler's own input type reads that the approved input `H`
13100
+ // does not have, member by member for a union on either side.
13101
+ type UnlistedReads<P, H> = P extends unknown
13102
+ ? Exclude<keyof P, H extends unknown ? keyof H : never>
13103
+ : never;
13104
+
13105
+ // The handler's input type `P` is inferred from its own annotation (or is
13106
+ // `H` when it has none), so an annotation never widens what it reads: one
13107
+ // naming a key the list does not, even an optional one, is refused by name,
13108
+ // and one the approved input is not assignable to is refused as before. An
13109
+ // explicit `any` is the author's own way out and is left alone.
13110
+ type ApprovedHandler<P, H> = 0 extends 1 & P
13111
+ ? {}
13112
+ : [UnlistedReads<P, H>] extends [never]
13113
+ ? [H] extends [P]
13114
+ ? {}
13115
+ : { handler: (input: H, ...rest: any[]) => unknown }
13116
+ : {
13117
+ handler: `the handler reads ${Extract<UnlistedReads<P, H>, string | number>}, which its input list does not name`;
13118
+ };
13119
+
13120
+ /**
13121
+ * The object form's definition: an `authorize` method beside the handler,
13122
+ * and the `input` list of the keys the handler may read. `TAuth` is what
13123
+ * `authorize`'s `allow` resolves, and the handler reads it as
13124
+ * `ctx.auth`. `TAuthorized` is what `authorize` is held to, and only
13125
+ * `defineFunction` sets it apart from `TAuth`; so does `THandlerInput`,
13126
+ * the handler's input, and `TList`, the type the list is held to.
13127
+ */
13128
+ export interface FunctionDefinition<
13129
+ TInput,
13130
+ TOutput,
13131
+ TAuth,
13132
+ TAuthorized = TAuth,
13133
+ THandlerInput = TInput,
13134
+ TList extends readonly string[] = readonly string[]
13135
+ > {
13136
+ /** The top-level input keys the handler may read. `authorize` reads them all. */
13137
+ input?: TList;
12833
13138
  authorize: AuthorizeFn<TInput, TAuthorized>;
12834
13139
  handler: (
12835
- input: TInput,
13140
+ input: THandlerInput,
12836
13141
  ctx: FunctionContext & FunctionAuthorizedContext<TAuth>,
12837
13142
  step: FunctionStep
12838
13143
  ) => TOutput | Promise<TOutput>;
@@ -12878,32 +13183,67 @@ export type AuthorizedFunctionHandler<TInput, TOutput, TAuth> = FunctionHandler<
12878
13183
  * taking `(input, ctx, step)` runs exactly as a wrapped one does — so this is
12879
13184
  * a typing and intent marker, not a different calling convention.
12880
13185
  *
12881
- * The OBJECT form, `defineFunction(key?, { authorize, handler })`, adds an
12882
- * `authorize` method that decides who may run the handler; what its
12883
- * `allow` resolves is the handler's `ctx.auth`. A definition with any
12884
- * other key, or a member that is not a function, throws a `TypeError` when
12885
- * the module loads.
13186
+ * The OBJECT form, `defineFunction(key?, { input, authorize, handler })`,
13187
+ * adds an `authorize` method that decides who may run the handler; what its
13188
+ * `allow` resolves is the handler's `ctx.auth`. `input` lists the
13189
+ * top-level input keys the handler may read, and its `input` is typed as
13190
+ * the declared input picked to them. With no list the handler's `input` is
13191
+ * `{}`, and an annotation on the handler's parameter never adds a key the
13192
+ * list does not name. With explicit type arguments the list is the fourth,
13193
+ * as a tuple (`<In, Out, Auth, ["classId"]>`), and is still written on the
13194
+ * definition. `authorize` always reads the whole input:
13195
+ *
13196
+ * ```ts
13197
+ * export default defineFunction("get-class", {
13198
+ * input: ["classId"],
13199
+ * authorize: async (input, auth) => (auth.user ? allow() : deny("FORBIDDEN")),
13200
+ * handler: async (input, ctx) => ({ classId: input.classId }),
13201
+ * });
13202
+ * ```
13203
+ *
13204
+ * A definition with any other key, or a member that is not a function,
13205
+ * throws a `TypeError` when the module loads.
12886
13206
  */
12887
13207
  export declare function defineFunction<
12888
13208
  K extends FunctionKeys,
12889
- TAuth = WriteAuthorizeBeforeHandler | null
13209
+ TAuth = WriteAuthorizeBeforeHandler | null,
13210
+ const L extends readonly string[] = never,
13211
+ THandlerInput = FunctionApprovedInput<FunctionInput<K>, L[number]>
12890
13212
  >(
12891
13213
  key: K,
12892
13214
  definition: FunctionDefinition<
12893
13215
  FunctionInput<K>,
12894
13216
  FunctionOutput<K>,
12895
13217
  TAuth,
12896
- DefinedAuthorize<TAuth>
12897
- >
13218
+ DefinedAuthorize<TAuth>,
13219
+ THandlerInput,
13220
+ ListedList<L, FunctionInputKey<FunctionInput<K>>>
13221
+ > &
13222
+ ListedOnly<
13223
+ ListWritten<L> &
13224
+ ApprovedHandler<THandlerInput, FunctionApprovedInput<FunctionInput<K>, L[number]>>
13225
+ >
12898
13226
  ): AuthorizedFunctionHandler<FunctionInput<K>, FunctionOutput<K>, TAuth> & {
12899
13227
  functionKey: K;
12900
13228
  };
12901
13229
  export declare function defineFunction<
12902
13230
  TInput = unknown,
12903
13231
  TOutput = unknown,
12904
- TAuth = WriteAuthorizeBeforeHandler | null
13232
+ TAuth = WriteAuthorizeBeforeHandler | null,
13233
+ const L extends readonly string[] = never,
13234
+ THandlerInput = FunctionApprovedInput<TInput, L[number]>
12905
13235
  >(
12906
- definition: FunctionDefinition<TInput, TOutput, TAuth, DefinedAuthorize<TAuth>>
13236
+ definition: FunctionDefinition<
13237
+ TInput,
13238
+ TOutput,
13239
+ TAuth,
13240
+ DefinedAuthorize<TAuth>,
13241
+ THandlerInput,
13242
+ ListedList<L, ListedInputKey<TInput>>
13243
+ > &
13244
+ ListedOnly<
13245
+ ListWritten<L> & ApprovedHandler<THandlerInput, FunctionApprovedInput<TInput, L[number]>>
13246
+ >
12907
13247
  ): AuthorizedFunctionHandler<TInput, TOutput, TAuth>;
12908
13248
  /**
12909
13249
  * A bare handler, keyed.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "primitive-functions",
3
- "version": "0.3.0-alpha.14",
3
+ "version": "0.3.0-alpha.16",
4
4
  "description": "The module a Primitive server function imports. Supplied by the platform at invoke time; reserved here so the name is ours before the runtime lands.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "Primitive LLC",