@standards/client 1.0.0-alpha.419 → 1.0.0-alpha.421

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,6 +1,6 @@
1
1
 
2
- import { r as MultipartRequestOptions, s as TransportConfig, t as HttpTransport } from "./http-transport-BxJhcXjy.mjs";
3
- import { AggregateRecordsOptions, BundleBuilder, DocumentFile, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult, UsageReport, UsageScope } from "@standards/schema";
2
+ import { S as OperationTransport, _ as HttpTransport, t as AppClient, w as TransportConfig } from "./app-TCIe_XWO.js";
3
+ import { AggregateRecordsOptions, BundleBuilder, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult } from "@standards/schema";
4
4
  /**
5
5
  * What a sync carries besides the bundle itself.
6
6
  *
@@ -12,123 +12,10 @@ import { AggregateRecordsOptions, BundleBuilder, DocumentFile, ExtractRecord, Ex
12
12
  interface SyncBundleOptions {
13
13
  resolutions?: SchemaSourceResolution[];
14
14
  }
15
- /**
16
- * The two verbs a sync needs, typed non-generically: the real `Transport`
17
- * satisfies it, and so does a hand-rolled stub, which a `Pick` of the generic
18
- * signatures would reject.
19
- */
20
- interface SyncTransport {
21
- get(path: string): Promise<unknown>;
22
- put(path: string, body?: unknown): Promise<unknown>;
23
- }
15
+ /** Both calls are contract operations, on any transport. */
16
+ type SyncTransport = Pick<HttpTransport, "call">;
24
17
  /** GET the installed summary; PUT the built bundle when its hash, label, description or uses differ, or it was never synced. */
25
18
  declare function syncBundle(transport: SyncTransport, bundle: BundleBuilder<string, readonly ObjectBuilderLike[]>, options?: SyncBundleOptions): Promise<SyncBundleResult>;
26
- /**
27
- * What the files and documents methods upload: a `File` (or any `Blob` carrying
28
- * a `name`) with a non-empty filename and MIME type. The server checks the MIME
29
- * type, the extension and the file signature against each other, so all three
30
- * travel with the bytes. A `Buffer` or a path is not an input: wrap the bytes in
31
- * `new File([bytes], "name.png", { type: "image/png" })`.
32
- */
33
- type FileInput = Blob & {
34
- readonly name: string;
35
- };
36
- /**
37
- * The timeout of one upload's request, in ms (#4741). A large file on a slow
38
- * link outlives the client's `timeoutMs` (30 s by default) and surfaces as a
39
- * connection failure, possibly after the server stored it — so raise it for
40
- * large uploads rather than retrying a timed-out attach.
41
- */
42
- interface UploadTimeoutOption {
43
- timeoutMs?: number;
44
- }
45
- interface AttachToRecordInput extends UploadTimeoutOption {
46
- objectName: string;
47
- recordId: string;
48
- /** The record's `document` attribute; the server defaults to `attachments`. */
49
- attributeName?: string;
50
- /** Append to this existing document's pack instead of creating a document. */
51
- documentId?: string;
52
- /** The new document's title; the server defaults to the filename without its extension. */
53
- title?: string;
54
- /**
55
- * The bytes to upload, private, in the same request — the input
56
- * `files.upload` takes. The attach route takes one file per call: append
57
- * more by passing the returned `document.id` as `documentId`. An
58
- * already-uploaded file is not an input, so a public upload can never end up
59
- * in a document.
60
- */
61
- file: FileInput;
62
- }
63
- interface AttachToRecordResult {
64
- document: {
65
- id: string;
66
- title: string;
67
- };
68
- file: DocumentFile;
69
- /** `created`: a new document on the record; `appended`: added to `documentId`'s pack. */
70
- action: "created" | "appended";
71
- }
72
- interface DocumentsApi {
73
- /**
74
- * Upload a file and attach it to a record's document attribute in ONE
75
- * multipart `POST /records/:object/:id/documents/attach`. The server
76
- * validates the file against the attribute and deletes the upload if the
77
- * attach fails, so an error never leaves an orphaned file.
78
- */
79
- attachToRecord(input: AttachToRecordInput): Promise<AttachToRecordResult>;
80
- /** The document's files in pack order (`GET /documents/:id/files`). */
81
- listFiles(documentId: string): Promise<DocumentFile[]>;
82
- }
83
- /** The two verbs this module needs, typed non-generically so a stub satisfies it. */
84
- interface DocumentsTransport {
85
- get(path: string): Promise<unknown>;
86
- postMultipart(path: string, form: FormData, options?: MultipartRequestOptions): Promise<unknown>;
87
- }
88
- declare function createDocumentsApi(transport: DocumentsTransport): DocumentsApi;
89
- interface UploadFileBase extends UploadTimeoutOption {
90
- file: FileInput;
91
- /** Stored as the file's folder (`folderPath` on `POST /files/upload`). */
92
- folderPath?: string;
93
- }
94
- /** Anyone holding the returned `publicUrl` can open the file. A public file never joins a document. */
95
- interface UploadPublicFileInput extends UploadFileBase {
96
- public: true;
97
- }
98
- /** The default: readable through a signed URL from `getDownloadUrl`. */
99
- interface UploadPrivateFileInput extends UploadFileBase {
100
- public?: false;
101
- }
102
- type UploadFileInput = UploadPublicFileInput | UploadPrivateFileInput;
103
- interface UploadedFileBase {
104
- id: string;
105
- /** The stored (sanitized) filename. */
106
- name: string;
107
- mimeType: string;
108
- size: number;
109
- }
110
- interface PublicUploadedFile extends UploadedFileBase {
111
- isPublic: true;
112
- /** `{publicFilesUrl}/{id}`: permanent, and never carries a credential. */
113
- publicUrl: string;
114
- }
115
- interface PrivateUploadedFile extends UploadedFileBase {
116
- isPublic: false;
117
- publicUrl?: never;
118
- }
119
- /** Discriminated on `isPublic`: only the public branch has a `publicUrl`. */
120
- type UploadedFile = PublicUploadedFile | PrivateUploadedFile;
121
- interface FilesApi {
122
- /** One multipart `POST /files/upload`. */
123
- upload(input: UploadPublicFileInput): Promise<PublicUploadedFile>;
124
- upload(input: UploadPrivateFileInput): Promise<PrivateUploadedFile>;
125
- upload(input: UploadFileInput): Promise<UploadedFile>;
126
- /** A fresh signed read URL (`GET /files/:id/url`); it expires, so ask again each time. */
127
- getDownloadUrl(fileId: string): Promise<string>;
128
- }
129
- /** The one verb this module needs: the `files` operations. */
130
- type FilesTransport = Pick<HttpTransport, "call">;
131
- declare function createFilesApi(transport: FilesTransport): FilesApi;
132
19
  /** `daily-stats` → `dailyStats`. Object names are kebab-case (enforced by the builder). */
133
20
  type CamelCase<S extends string> = S extends `${infer Head}-${infer Tail}` ? `${Head}${Capitalize<CamelCase<Tail>>}` : S;
134
21
  type Attr<TBuilder> = keyof ExtractRecord<TBuilder> & string;
@@ -145,6 +32,33 @@ type RecordInput<TBuilder> = ExtractRecordInputStrict<TBuilder> & {
145
32
  type RecordUpdate<TBuilder> = ExtractRecordUpdateStrict<TBuilder> & {
146
33
  [key: string]: unknown;
147
34
  };
35
+ /** What `create()` takes beside the values. */
36
+ interface RecordCreateOptions {
37
+ /**
38
+ * Create the record even when required attributes are missing. The values
39
+ * given are still validated.
40
+ * @default false
41
+ */
42
+ allowDraft?: boolean;
43
+ /**
44
+ * The record's `metadata`: application state kept beside its values, never
45
+ * shown as an attribute. System keys are dropped.
46
+ */
47
+ metadata?: Record<string, unknown>;
48
+ }
49
+ /**
50
+ * What `update()` takes beside the patch. No `allowDraft`: the server already
51
+ * validates every update as a draft, so a required attribute the patch leaves
52
+ * out is never refused.
53
+ */
54
+ interface RecordUpdateOptions {
55
+ /**
56
+ * Keys shallow-merged into the record's `metadata`: each one replaced whole,
57
+ * `null` removes it, the keys not named stay. Written with the patch in one
58
+ * transaction.
59
+ */
60
+ metadata?: Record<string, unknown>;
61
+ }
148
62
  /** What `export()` takes beside its columns. */
149
63
  interface RecordsExportOptions {
150
64
  /** Export only these records (at most `EXPORT_MAX_IDS`, 20 000). */
@@ -257,8 +171,27 @@ interface RecordsQuery<TBuilder> {
257
171
  all(): Promise<ExtractRecord<TBuilder>[]>;
258
172
  single(): Promise<ExtractRecord<TBuilder> | null>;
259
173
  get(id: string): Promise<ExtractRecord<TBuilder>>;
260
- create(input: RecordInput<TBuilder>): Promise<ExtractRecord<TBuilder>>;
261
- update(id: string, patch: RecordUpdate<TBuilder>): Promise<ExtractRecord<TBuilder>>;
174
+ /**
175
+ * `POST /records/<object>`. `allowDraft` creates the record with required
176
+ * attributes missing (so its input types every attribute as optional);
177
+ * `metadata` is the record's application state.
178
+ */
179
+ create(input: RecordInput<TBuilder>, options?: RecordCreateOptions): Promise<ExtractRecord<TBuilder>>;
180
+ create(input: RecordUpdate<TBuilder>, options: RecordCreateOptions & {
181
+ allowDraft: true;
182
+ }): Promise<ExtractRecord<TBuilder>>;
183
+ /**
184
+ * `PUT /records/<object>/<id>`: merges the patch into the record. The server
185
+ * validates every update as a draft, so there is no `allowDraft`.
186
+ *
187
+ * With `metadata`, the patch and the metadata are written together by one
188
+ * `record.set` step of `POST /operations`, in one transaction; the record is
189
+ * read first (`GET /records/<object>/<id>`) for the object id the step
190
+ * names. A refused step rejects with the `StandardsRequestError` its code
191
+ * maps to (`StandardsAuthError` for a 403), with that code and status but
192
+ * no field `details`, which the same refusal on `PUT` carries.
193
+ */
194
+ update(id: string, patch: RecordUpdate<TBuilder>, options?: RecordUpdateOptions): Promise<ExtractRecord<TBuilder>>;
262
195
  delete(id: string): Promise<void>;
263
196
  /**
264
197
  * `POST /records/<object>/bulk-create`, 100 inputs per request, sent one after
@@ -299,38 +232,16 @@ interface UntypedBuilder {
299
232
  /** What `standards.from("object-name")` hands back. */
300
233
  type UntypedRecordsQuery = RecordsQuery<UntypedBuilder>;
301
234
  /**
302
- * The verbs this module needs, typed non-generically: the real `Transport`
303
- * satisfies it, and so does a hand-rolled stub, which a `Pick` of the generic
304
- * signatures would reject. `postRaw` only serves `export()`, which refuses
305
- * when a stub leaves it out. Each path is its contract operation's
306
- * (`buildOperationPath`, every parameter one encoded segment); the verbs stay
307
- * the transport's.
235
+ * Every records call is a contract operation (`call`), on any transport, the
236
+ * in-process one included. `export()` alone reads the CSV as it streams, so it
237
+ * needs an HTTP transport's `postRaw`.
308
238
  */
309
- interface RecordsTransport {
310
- get(path: string): Promise<unknown>;
311
- post(path: string, body?: unknown): Promise<unknown>;
239
+ type RecordsTransport = Pick<HttpTransport, "call"> & {
312
240
  postRaw?(path: string, body: unknown): Promise<Response>;
313
- put(path: string, body?: unknown): Promise<unknown>;
314
- delete(path: string): Promise<unknown>;
315
- }
241
+ };
316
242
  /** A builder gives typed records; a bare object name is the untyped escape hatch. */
317
243
  declare function createRecordsQuery<TBuilder extends ObjectBuilderLike>(transport: RecordsTransport, target: TBuilder): RecordsQuery<TBuilder>;
318
244
  declare function createRecordsQuery(transport: RecordsTransport, target: string): UntypedRecordsQuery;
319
- interface UsageReportInput {
320
- /** First day of the window, `YYYY-MM-DD` (UTC, inclusive). */
321
- from: string;
322
- /** Last day of the window, `YYYY-MM-DD` (UTC, inclusive); at most 366 days after `from`. */
323
- to: string;
324
- /** `me` (the default): the caller's own usage. `workspace`: every member's, gated on `billing:read`. */
325
- scope?: UsageScope;
326
- }
327
- interface UsageApi {
328
- /** AI usage and cost over an inclusive UTC day window (`GET /ai/usage`). */
329
- report(input: UsageReportInput): Promise<UsageReport>;
330
- }
331
- /** The one verb this module needs: the `ai.usage` operation. */
332
- type UsageTransport = Pick<HttpTransport, "call">;
333
- declare function createUsageApi(transport: UsageTransport): UsageApi;
334
245
  type NameOf<B> = B extends {
335
246
  _types: {
336
247
  name: infer N extends string;
@@ -342,28 +253,59 @@ type ObjectsOf<TObjects extends readonly ObjectBuilderLike[]> = { readonly [B in
342
253
  type AnyBundle = BundleBuilder<string, readonly ObjectBuilderLike[]>;
343
254
  /** The object builders of every bundle in a tuple: what the typed client infers from. */
344
255
  type ObjectsOfBundles<TBundles extends readonly AnyBundle[]> = TBundles[number]["objectBuilders"];
345
- interface Standards {
346
- bundles: {
347
- /** Sync a bundle to the workspace; a no-op (`applied: false`) when it already holds this version. */
348
- sync(bundle: AnyBundle, options?: SyncBundleOptions): Promise<SyncBundleResult>;
256
+ type ContractSync = AppClient["bundles"]["sync"];
257
+ /** `bundles.sync`, either way: from your bundle's builder, or the contract's call. */
258
+ interface BundlesSync {
259
+ /**
260
+ * Build `bundle`, compare it with the version the workspace holds, and put
261
+ * it only when it changed: `{ applied: false }` when it already holds it.
262
+ */
263
+ (bundle: AnyBundle, options?: SyncBundleOptions): Promise<SyncBundleResult>;
264
+ /** The contract's call, with an artifact you built yourself. */
265
+ (...args: Parameters<ContractSync>): ReturnType<ContractSync>;
266
+ }
267
+ /**
268
+ * The client: every operation of the contract at the root, by group and
269
+ * verb (`decisions.list`, `users.get`, `files.upload`…), with your bundles'
270
+ * objects beside them as typed queries (see {@link StandardsOf}).
271
+ */
272
+ type Standards = Omit<AppClient, "bundles"> & {
273
+ readonly bundles: Omit<AppClient["bundles"], "sync"> & {
274
+ readonly sync: BundlesSync;
349
275
  };
350
276
  /** Untyped access to an object the code does not declare (created at runtime). */
351
277
  from(objectName: string): UntypedRecordsQuery;
352
- /** Upload files (private or public) and read them back through signed URLs. */
353
- files: FilesApi;
354
- /** Attach uploads to a record's document attribute and list a document's files. */
355
- documents: DocumentsApi;
356
- /** AI usage and cost of the caller or the whole workspace. */
357
- usage: UsageApi;
358
- }
278
+ /**
279
+ * Every operation of the contract, under its own name only: the way to a
280
+ * group one of your objects shares a name with, since the object wins at
281
+ * the root.
282
+ */
283
+ readonly contract: AppClient;
284
+ };
285
+ /**
286
+ * The client with your objects: each one a typed query at the root. An object
287
+ * named like a contract group takes its place there (the group stays under
288
+ * `contract`), so a group Standards adds later never changes what your code
289
+ * reads.
290
+ */
291
+ type StandardsOf<TObjects extends readonly ObjectBuilderLike[]> = Omit<Standards, keyof ObjectsOf<TObjects>> & ObjectsOf<TObjects>;
359
292
  /**
360
- * The options `createStandards` takes. Every field of `TransportConfig` is
361
- * optional here: on the server a missing `baseUrl` / `apiKey` is read from
362
- * `STANDARDS_API_URL` / `STANDARDS_API_KEY`, and an explicit value always wins.
293
+ * Every call `createStandards` makes is a contract operation (`call`, and
294
+ * `stream` for an `"events"` one); a records `export()` also
295
+ * needs an HTTP transport's `postRaw`.
363
296
  */
364
- type StandardsConfig = Partial<TransportConfig>;
297
+ type StandardsTransport = OperationTransport & Partial<Pick<HttpTransport, "postRaw">>;
298
+ /**
299
+ * The options `createStandards` takes: an API key's HTTP connection
300
+ * (`baseUrl`, `apiKey`, read from the environment when absent), or a
301
+ * `transport` of your own (the in-process one in a server that embeds
302
+ * Standards, `createInProcessTransport`), never both.
303
+ */
304
+ type StandardsConfig = Partial<TransportConfig> & {
305
+ transport?: StandardsTransport;
306
+ };
365
307
  declare function createStandards<const TBundles extends readonly AnyBundle[]>(config: StandardsConfig & {
366
308
  bundles: TBundles;
367
- }): Standards & ObjectsOf<ObjectsOfBundles<TBundles>>;
309
+ }): StandardsOf<ObjectsOfBundles<TBundles>>;
368
310
  declare function createStandards(config?: StandardsConfig): Standards;
369
- export { PrivateUploadedFile as A, DocumentsTransport as B, UpdateManyEntry as C, CamelCase as D, createRecordsQuery as E, UploadedFile as F, SyncTransport as G, FileInput as H, createFilesApi as I, syncBundle as K, AttachToRecordInput as L, UploadFileInput as M, UploadPrivateFileInput as N, FilesApi as O, UploadPublicFileInput as P, AttachToRecordResult as R, UntypedRecordsQuery as S, UpdateManyResult as T, UploadTimeoutOption as U, createDocumentsApi as V, SyncBundleOptions as W, RecordUpdate as _, StandardsConfig as a, RecordsQuery as b, UsageReportInput as c, CreateManyError as d, CreateManyResult as f, RecordInput as g, FetchResult as h, Standards as i, PublicUploadedFile as j, FilesTransport as k, UsageTransport as l, DeleteManyResult as m, ObjectsOf as n, createStandards as o, DeleteManyError as p, ObjectsOfBundles as r, UsageApi as s, AnyBundle as t, createUsageApi as u, RecordsAggregateOptions as v, UpdateManyError as w, UntypedBuilder as x, RecordsExportOptions as y, DocumentsApi as z };
311
+ export { SyncTransport as A, UntypedRecordsQuery as C, createRecordsQuery as D, UpdateManyResult as E, CamelCase as O, UntypedBuilder as S, UpdateManyError as T, RecordUpdate as _, Standards as a, RecordsExportOptions as b, StandardsTransport as c, CreateManyResult as d, DeleteManyError as f, RecordInput as g, RecordCreateOptions as h, ObjectsOfBundles as i, syncBundle as j, SyncBundleOptions as k, createStandards as l, FetchResult as m, BundlesSync as n, StandardsConfig as o, DeleteManyResult as p, ObjectsOf as r, StandardsOf as s, AnyBundle as t, CreateManyError as u, RecordUpdateOptions as v, UpdateManyEntry as w, RecordsQuery as x, RecordsAggregateOptions as y };
@@ -0,0 +1,4 @@
1
+ /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
+ import{d as e,f as t,h as n,i as r,m as i,o as a,t as o}from"./app-CjHQKAwu.mjs";import{AggregateValidationError as s,DuplicateError as c,RecordQuery as l,SCHEMA_ERROR_HTTP_STATUS as u,SchemaErrorCode as d,decodeRecordValues as f,encodeRecordValues as p,isPlainRecord as m}from"@standards/schema";import{buildOperationPath as h,bundlesOperations as g,decodeOperationOutput as _,recordAccessOperations as v,recordOperationsOperations as y,recordsOperations as b}from"@standards/schema/api";async function readInstalled(e,t){try{return await e.call(g.get,{name:t})}catch(e){if(e instanceof n&&e.status===404)return null;throw e}}async function syncBundle(r,i,a={}){let o=await i.build(),s=await readInstalled(r,o.name);if(s?.hash===o.hash&&s.label===o.label&&s.description===o.description&&s.uses.join(`
3
+ `)===o.uses.join(`
4
+ `))return{applied:!1,hash:o.hash};let c=a.resolutions&&a.resolutions.length>0?{...o,resolutions:a.resolutions}:o;try{return await r.call(g.sync,{name:o.name,bundle:c})}catch(r){throw r instanceof n&&r.status===409?new e(r.status,r.message,r.code):r instanceof n&&r.status===400?new t(r.status,r.message,r.code):r}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const x=/* @__PURE__ */ new Set([`from`,`bundles`,`contract`]);function assertObjectKeys(e){let t=/* @__PURE__ */ new Map;for(let n of e){if(n.includes(`--`)||n.endsWith(`-`))throw new i(`Object "${n}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let e=objectKeyOf(n);if(x.has(e))throw new i(`Object "${n}" maps to the client key "${e}", which is reserved. Rename the object.`);let r=t.get(e);if(r!==void 0&&r!==n)throw new i(`Objects "${r}" and "${n}" both map to the client key "${e}". Rename one of them.`);t.set(e,n)}}function assertObjectNames(e){let t=/* @__PURE__ */ new Set;for(let n of e){if(t.has(n))throw new c(`object`,n);t.add(n)}assertObjectKeys(e)}function readRecord(e,t){let{values:n,...r}=t;return m(n)?{...r,...f(e,n)}:t}var S=class RecordsQueryImpl extends l{constructor(e,t,n,r={object:t,combinator:`and`,rules:[],sorts:[]}){super(r),this.transport=e,this.objectName=t,this.definition=n}with(e){return new RecordsQueryImpl(this.transport,this.objectName,this.definition,{...this.state,...e})}body(){let e={};return this.state.search!==void 0&&(e.q=this.state.search),this.state.rules.length>0&&(e.filters={combinator:this.state.combinator,rules:this.state.rules}),this.state.sorts.length>0&&(e.sorts=this.state.sorts),this.state.limit!==void 0&&(e.limit=this.state.limit),this.state.offset!==void 0&&(e.offset=this.state.offset),e}revive(e){return readRecord(this.definition,e)}async export(e,t={}){if(!this.transport.postRaw)throw new i(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:n,sorts:r}=this.body(),{ids:a,locale:o,filename:s}=t;return await this.transport.postRaw(h(b.export,{objectName:this.objectName}),{q:this.state.search??``,...n?{filters:n}:{},...r?{sorts:r}:{},columns:e,...a?{ids:a}:{},...o?{locale:o}:{},timezone:t.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...s?{filename:s}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new s(d.AGGREGATE_SEARCH_UNSUPPORTED,`An aggregate cannot be narrowed by a search; use filters instead`);let t={...e,query:this.toDefinition(),timezone:e.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone};return await this.transport.call(b.aggregate,{objectName:this.objectName,...t})}async fetchPage(){let e={objectName:this.objectName,...this.body()},t=this.state.search===void 0?await this.transport.call(b.list,e):await this.transport.call(b.search,e);return{records:t.data.map(e=>this.revive(e)),page:t.page}}async fetch(){let{records:e,page:t}=await this.fetchPage();return{records:e,total:t.total}}async all(){if(this.state.limit!==void 0&&this.state.limit<0)return(await this.fetch()).records;let e=this.state.limit??1/0,t=[],n=this.state.offset??0;for(;;){let r=Math.min(1e3,e-t.length);if(r<=0)return t;let{records:i,page:a}=await this.with({limit:r,offset:n}).fetchPage();if(t.push(...i),!a.hasMore)return t;let o=a.nextOffset??n+i.length;if(o<=n)return t;n=o}}async single(){let{records:e}=await this.limit(1).fetch();return e[0]??null}async get(e){let t=await this.transport.call(b.get,{objectName:this.objectName,id:e});return this.revive(t)}async create(e,{allowDraft:t,metadata:n}={}){let r={...t!==void 0&&{allowDraft:t},...n!==void 0&&{metadata:n}},i=await this.transport.call(b.create,{objectName:this.objectName,data:p(this.definition,e),...Object.keys(r).length>0&&{options:r}});return this.revive(i)}async update(e,t,{metadata:n}={}){let r=p(this.definition,t);if(n===void 0){let t=await this.transport.call(b.update,{objectName:this.objectName,id:e,values:r});return this.revive(t)}let{objectId:i}=await this.transport.call(b.get,{objectName:this.objectName,id:e}),{steps:o}=await this.transport.call(y.execute,{opId:crypto.randomUUID(),steps:[{kind:`record.set`,objectId:i,recordId:e,values:r,metadata:n}]}),[s]=o;if(s===void 0||s.status===`error`){let e=s?.code,t=e===void 0?500:u[e];throw a(t,JSON.stringify({message:s?.message,code:e}))}let c=_(b.get,s.record);return this.revive(c)}async delete(e){await this.transport.call(b.delete,{objectName:this.objectName,id:e})}async inChunks(e,t){for(let n=0;n<e.length;n+=100)await t(e.slice(n,n+100),n)}async createMany(e){let t={created:[],errors:[]};return await this.inChunks(e,async(e,n)=>{let r=await this.transport.call(b.bulkCreate,{objectName:this.objectName,records:e.map(e=>p(this.definition,e))});t.created.push(...r.created.map(e=>this.revive(e))),t.errors.push(...r.errors.map(e=>({...e,index:e.index+n})))}),t}async updateMany(e){let t={updated:[],errors:[]};return await this.inChunks(e,async e=>{let n=await this.transport.call(b.bulkUpdate,{objectName:this.objectName,updates:e.map(({id:e,data:t})=>({id:e,data:p(this.definition,t)}))});t.updated.push(...n.updated.map(e=>this.revive(e))),t.errors.push(...n.errors)}),t}async deleteMany(e){let t={deleted:[],errors:[]};return await this.inChunks(e,async e=>{let n=await this.transport.call(b.bulkDelete,{objectName:this.objectName,ids:e});t.deleted.push(...n.deleted),t.errors.push(...n.errors)}),t}async listAccess(e){return await this.transport.call(v.list,{objectName:this.objectName,recordId:e})}async grantAccess(e,t,n){return await this.transport.call(v.grant,{objectName:this.objectName,recordId:e,actorId:t,role:n})}async revokeAccess(e,t){return await this.transport.call(v.revoke,{objectName:this.objectName,recordId:e,actorId:t})}async clearAccess(e){return await this.transport.call(v.clear,{objectName:this.objectName,recordId:e})}};const C=/* @__PURE__ */ new WeakMap;function definitionOf(e){let t=C.get(e);if(t)return t;let n=e.build();return C.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new S(e,t,null);let n=definitionOf(t);return new S(e,n.name,n)}function readEnvironment(){return typeof process>`u`||!process.env?{}:{baseUrl:process.env.STANDARDS_API_URL||void 0,apiKey:process.env.STANDARDS_API_KEY||void 0}}function resolveConfig(e){if(globalThis.window!==void 0){if(e.apiKey)throw new i(`createStandards received an apiKey in a browser context. API keys belong to server code only (Route Handlers, Server Components, scripts).`);if(e.baseUrl===void 0)throw new i(`createStandards needs an explicit baseUrl in a browser context: STANDARDS_API_URL and STANDARDS_API_KEY are never read from the environment there.`);return{...e,baseUrl:e.baseUrl,apiKey:``}}let t=readEnvironment(),n=e.baseUrl??t.baseUrl;if(n===void 0)throw new i(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let r=e.apiKey??t.apiKey;if(r===void 0)throw new i(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...e,baseUrl:n,apiKey:r}}function createStandards(e={}){let{bundles:t=[],transport:n,...a}=e;if(n!==void 0&&Object.values(a).some(e=>e!==void 0))throw new i(`createStandards takes a transport or an HTTP connection (baseUrl, apiKey, tenantId, timeoutMs), not both.`);return buildStandards(n??r(resolveConfig(a)),t.flatMap(e=>e.objectBuilders))}function buildStandards(e,t){let n=o(e),sync=((t,r)=>isBundleBuilder(t)?syncBundle(e,t,r):n.bundles.sync(t,r)),r={...n,bundles:{...n.bundles,sync},from:t=>createRecordsQuery(e,t),contract:n},i=t.map(e=>definitionOf(e).name);return assertObjectNames(i),t.forEach((t,n)=>{r[objectKeyOf(i[n])]=createRecordsQuery(e,t)}),r}function isBundleBuilder(e){return typeof e==`object`&&!!e&&`objectBuilders`in e&&typeof e.build==`function`}export{readRecord as a,definitionOf as i,createStandards as n,syncBundle as o,createRecordsQuery as r,buildStandards as t};
package/dist/index.d.mts CHANGED
@@ -1,18 +1,12 @@
1
1
 
2
- import { A as PrivateUploadedFile, B as DocumentsTransport, C as UpdateManyEntry, D as CamelCase, E as createRecordsQuery, F as UploadedFile, G as SyncTransport, H as FileInput, I as createFilesApi, K as syncBundle, L as AttachToRecordInput, M as UploadFileInput, N as UploadPrivateFileInput, O as FilesApi, P as UploadPublicFileInput, R as AttachToRecordResult, S as UntypedRecordsQuery, T as UpdateManyResult, U as UploadTimeoutOption, V as createDocumentsApi, W as SyncBundleOptions, _ as RecordUpdate, a as StandardsConfig, b as RecordsQuery, c as UsageReportInput, d as CreateManyError, f as CreateManyResult, g as RecordInput, h as FetchResult, i as Standards, j as PublicUploadedFile, k as FilesTransport, l as UsageTransport, m as DeleteManyResult, n as ObjectsOf, o as createStandards, p as DeleteManyError, r as ObjectsOfBundles, s as UsageApi, t as AnyBundle, u as createUsageApi, v as RecordsAggregateOptions, w as UpdateManyError, x as UntypedBuilder, y as RecordsExportOptions, z as DocumentsApi } from "./create-standards-HiWpTAlP.mjs";
3
- import { _ as StandardsRequestError, g as StandardsConfigurationError, h as StandardsAuthError, m as BundleValidationError, o as Transport, p as BundleConflictError, r as MultipartRequestOptions, s as TransportConfig, u as createTransport } from "./http-transport-BxJhcXjy.mjs";
4
- import { ActorType, Attribute, BUNDLE_NAME_PATTERN, BuiltBundle, BundleBuilder, BundlePiece, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, InstalledBundleSummary, NotFoundError, ObjectBuilderLike, ObjectDefinition, ObjectDefinition as ObjectDefinition$1, RecordAccessRole, RecordAudience, RecordMetadata, SchemaError, SchemaErrorCode, SchemaSourceCurrencyRetype, SchemaSourcePhoneRetype, SchemaSourceRename, SchemaSourceResolution, SchemaSourceRetype, SortDirection, SortRule, SyncBundleResult, UsageBucket, UsageModality, UsageReport, UsageScope, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, currency, currentActor, date, detailView, document, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, text, today, user } from "@standards/schema";
2
+ import { A as SyncTransport, C as UntypedRecordsQuery, D as createRecordsQuery, E as UpdateManyResult, O as CamelCase, S as UntypedBuilder, T as UpdateManyError, _ as RecordUpdate, a as Standards, b as RecordsExportOptions, c as StandardsTransport, d as CreateManyResult, f as DeleteManyError, g as RecordInput, h as RecordCreateOptions, i as ObjectsOfBundles, j as syncBundle, k as SyncBundleOptions, l as createStandards, m as FetchResult, n as BundlesSync, o as StandardsConfig, p as DeleteManyResult, r as ObjectsOf, s as StandardsOf, t as AnyBundle, u as CreateManyError, v as RecordUpdateOptions, w as UpdateManyEntry, x as RecordsQuery, y as RecordsAggregateOptions } from "./create-standards-B4fQnzl5.mjs";
3
+ import { A as BundleConflictError, C as Transport, D as createTransport, M as StandardsAuthError, N as StandardsConfigurationError, P as StandardsRequestError, j as BundleValidationError, w as TransportConfig, y as MultipartRequestOptions } from "./app-TCIe_XWO.mjs";
4
+ import { ActorType, Attribute, BUNDLE_NAME_PATTERN, BuiltBundle, BundleBuilder, BundlePiece, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, InstalledBundleSummary, NotFoundError, ObjectBuilderLike, ObjectDefinition, RecordAccessRole, RecordAudience, RecordMetadata, SchemaError, SchemaErrorCode, SchemaSourceCurrencyRetype, SchemaSourcePhoneRetype, SchemaSourceRename, SchemaSourceResolution, SchemaSourceRetype, SortDirection, SortRule, SyncBundleResult, UsageBucket, UsageModality, UsageReport, UsageScope, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, currency, currentActor, date, detailView, document, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, text, today, user } from "@standards/schema";
5
5
  import { encodePathSegment } from "@standards/schema/api";
6
- /**
7
- * JSON delivers dates as ISO strings; the client knows the definition, so it
8
- * revives system timestamps and every `date` attribute so `ExtractRecord` tells
9
- * the truth on the wire. Nothing else is transformed.
10
- */
11
- export declare function reviveRecord<T extends Record<string, unknown>>(definition: ObjectDefinition$1 | null, raw: T): T;
12
6
  /**
13
7
  * Every caller-supplied path segment is percent-encoded: `objectName` and `id`
14
8
  * come from the application, and an id such as `../../bundles/x` must
15
9
  * never leave `/records/<object>/`.
16
10
  */
17
11
  export declare function recordsPath(objectName: string, ...segments: string[]): string;
18
- export { type ActorType, type AnyBundle, type AttachToRecordInput, type AttachToRecordResult, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DeleteManyError, type DeleteManyResult, type DocumentsApi, type DocumentsTransport, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FileInput, type FilesApi, type FilesTransport, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type PrivateUploadedFile, type PublicUploadedFile, type RecordAccessRole, type RecordAudience, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, StandardsRequestError, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UploadFileInput, type UploadPrivateFileInput, type UploadPublicFileInput, type UploadTimeoutOption, type UploadedFile, type UsageApi, type UsageBucket, type UsageModality, type UsageReport, type UsageReportInput, type UsageScope, type UsageTransport, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createDocumentsApi, createFilesApi, createRecordsQuery, createStandards, createTransport, createUsageApi, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, syncBundle, text, today, user };
12
+ export { type ActorType, type AnyBundle, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type BundlesSync, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DeleteManyError, type DeleteManyResult, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type RecordAccessRole, type RecordAudience, type RecordCreateOptions, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordUpdateOptions, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, type StandardsOf, StandardsRequestError, type StandardsTransport, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UsageBucket, type UsageModality, type UsageReport, type UsageScope, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, syncBundle, text, today, user };
package/dist/index.d.ts CHANGED
@@ -1,18 +1,12 @@
1
1
 
2
- import { A as PrivateUploadedFile, B as DocumentsTransport, C as UpdateManyEntry, D as CamelCase, E as createRecordsQuery, F as UploadedFile, G as SyncTransport, H as FileInput, I as createFilesApi, K as syncBundle, L as AttachToRecordInput, M as UploadFileInput, N as UploadPrivateFileInput, O as FilesApi, P as UploadPublicFileInput, R as AttachToRecordResult, S as UntypedRecordsQuery, T as UpdateManyResult, U as UploadTimeoutOption, V as createDocumentsApi, W as SyncBundleOptions, _ as RecordUpdate, a as StandardsConfig, b as RecordsQuery, c as UsageReportInput, d as CreateManyError, f as CreateManyResult, g as RecordInput, h as FetchResult, i as Standards, j as PublicUploadedFile, k as FilesTransport, l as UsageTransport, m as DeleteManyResult, n as ObjectsOf, o as createStandards, p as DeleteManyError, r as ObjectsOfBundles, s as UsageApi, t as AnyBundle, u as createUsageApi, v as RecordsAggregateOptions, w as UpdateManyError, x as UntypedBuilder, y as RecordsExportOptions, z as DocumentsApi } from "./create-standards-BWOo2EZw.js";
3
- import { _ as StandardsRequestError, g as StandardsConfigurationError, h as StandardsAuthError, m as BundleValidationError, o as Transport, p as BundleConflictError, r as MultipartRequestOptions, s as TransportConfig, u as createTransport } from "./http-transport-BxJhcXjy.js";
4
- import { ActorType, Attribute, BUNDLE_NAME_PATTERN, BuiltBundle, BundleBuilder, BundlePiece, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, InstalledBundleSummary, NotFoundError, ObjectBuilderLike, ObjectDefinition, ObjectDefinition as ObjectDefinition$1, RecordAccessRole, RecordAudience, RecordMetadata, SchemaError, SchemaErrorCode, SchemaSourceCurrencyRetype, SchemaSourcePhoneRetype, SchemaSourceRename, SchemaSourceResolution, SchemaSourceRetype, SortDirection, SortRule, SyncBundleResult, UsageBucket, UsageModality, UsageReport, UsageScope, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, currency, currentActor, date, detailView, document, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, text, today, user } from "@standards/schema";
2
+ import { A as SyncTransport, C as UntypedRecordsQuery, D as createRecordsQuery, E as UpdateManyResult, O as CamelCase, S as UntypedBuilder, T as UpdateManyError, _ as RecordUpdate, a as Standards, b as RecordsExportOptions, c as StandardsTransport, d as CreateManyResult, f as DeleteManyError, g as RecordInput, h as RecordCreateOptions, i as ObjectsOfBundles, j as syncBundle, k as SyncBundleOptions, l as createStandards, m as FetchResult, n as BundlesSync, o as StandardsConfig, p as DeleteManyResult, r as ObjectsOf, s as StandardsOf, t as AnyBundle, u as CreateManyError, v as RecordUpdateOptions, w as UpdateManyEntry, x as RecordsQuery, y as RecordsAggregateOptions } from "./create-standards-YjhWkQYe.js";
3
+ import { A as BundleConflictError, C as Transport, D as createTransport, M as StandardsAuthError, N as StandardsConfigurationError, P as StandardsRequestError, j as BundleValidationError, w as TransportConfig, y as MultipartRequestOptions } from "./app-TCIe_XWO.js";
4
+ import { ActorType, Attribute, BUNDLE_NAME_PATTERN, BuiltBundle, BundleBuilder, BundlePiece, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, InstalledBundleSummary, NotFoundError, ObjectBuilderLike, ObjectDefinition, RecordAccessRole, RecordAudience, RecordMetadata, SchemaError, SchemaErrorCode, SchemaSourceCurrencyRetype, SchemaSourcePhoneRetype, SchemaSourceRename, SchemaSourceResolution, SchemaSourceRetype, SortDirection, SortRule, SyncBundleResult, UsageBucket, UsageModality, UsageReport, UsageScope, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, currency, currentActor, date, detailView, document, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, text, today, user } from "@standards/schema";
5
5
  import { encodePathSegment } from "@standards/schema/api";
6
- /**
7
- * JSON delivers dates as ISO strings; the client knows the definition, so it
8
- * revives system timestamps and every `date` attribute so `ExtractRecord` tells
9
- * the truth on the wire. Nothing else is transformed.
10
- */
11
- export declare function reviveRecord<T extends Record<string, unknown>>(definition: ObjectDefinition$1 | null, raw: T): T;
12
6
  /**
13
7
  * Every caller-supplied path segment is percent-encoded: `objectName` and `id`
14
8
  * come from the application, and an id such as `../../bundles/x` must
15
9
  * never leave `/records/<object>/`.
16
10
  */
17
11
  export declare function recordsPath(objectName: string, ...segments: string[]): string;
18
- export { type ActorType, type AnyBundle, type AttachToRecordInput, type AttachToRecordResult, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DeleteManyError, type DeleteManyResult, type DocumentsApi, type DocumentsTransport, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FileInput, type FilesApi, type FilesTransport, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type PrivateUploadedFile, type PublicUploadedFile, type RecordAccessRole, type RecordAudience, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, StandardsRequestError, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UploadFileInput, type UploadPrivateFileInput, type UploadPublicFileInput, type UploadTimeoutOption, type UploadedFile, type UsageApi, type UsageBucket, type UsageModality, type UsageReport, type UsageReportInput, type UsageScope, type UsageTransport, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createDocumentsApi, createFilesApi, createRecordsQuery, createStandards, createTransport, createUsageApi, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, syncBundle, text, today, user };
12
+ export { type ActorType, type AnyBundle, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type BundlesSync, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DeleteManyError, type DeleteManyResult, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type RecordAccessRole, type RecordAudience, type RecordCreateOptions, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordUpdateOptions, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, type StandardsOf, StandardsRequestError, type StandardsTransport, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UsageBucket, type UsageModality, type UsageReport, type UsageScope, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, syncBundle, text, today, user };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./create-standards-Bl-VDgXY.js"),t=require("./http-transport-Dr0ZiTG1.js");let n=require("@standards/schema/api"),r=require("@standards/schema");Object.defineProperty(exports,"BUNDLE_NAME_PATTERN",{enumerable:!0,get:function(){return r.BUNDLE_NAME_PATTERN}}),exports.BundleConflictError=t.p,exports.BundleValidationError=t.m,Object.defineProperty(exports,"DuplicateError",{enumerable:!0,get:function(){return r.DuplicateError}}),Object.defineProperty(exports,"ForbiddenError",{enumerable:!0,get:function(){return r.ForbiddenError}}),Object.defineProperty(exports,"NotFoundError",{enumerable:!0,get:function(){return r.NotFoundError}}),Object.defineProperty(exports,"SchemaError",{enumerable:!0,get:function(){return r.SchemaError}}),Object.defineProperty(exports,"SchemaErrorCode",{enumerable:!0,get:function(){return r.SchemaErrorCode}}),exports.StandardsAuthError=t.h,exports.StandardsConfigurationError=t.g,exports.StandardsRequestError=t._,Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return r.ValidationError}}),Object.defineProperty(exports,"assertBundleName",{enumerable:!0,get:function(){return r.assertBundleName}}),Object.defineProperty(exports,"bundle",{enumerable:!0,get:function(){return r.bundle}}),Object.defineProperty(exports,"canonicalStringify",{enumerable:!0,get:function(){return r.canonicalStringify}}),Object.defineProperty(exports,"checkbox",{enumerable:!0,get:function(){return r.checkbox}}),Object.defineProperty(exports,"content",{enumerable:!0,get:function(){return r.content}}),exports.createDocumentsApi=e.l,exports.createFilesApi=e.c,exports.createRecordsQuery=e.i,exports.createStandards=e.n,exports.createTransport=t.n,exports.createUsageApi=e.r,Object.defineProperty(exports,"currency",{enumerable:!0,get:function(){return r.currency}}),Object.defineProperty(exports,"currentActor",{enumerable:!0,get:function(){return r.currentActor}}),Object.defineProperty(exports,"date",{enumerable:!0,get:function(){return r.date}}),Object.defineProperty(exports,"detailView",{enumerable:!0,get:function(){return r.detailView}}),Object.defineProperty(exports,"document",{enumerable:!0,get:function(){return r.document}}),Object.defineProperty(exports,"encodePathSegment",{enumerable:!0,get:function(){return n.encodePathSegment}}),Object.defineProperty(exports,"formula",{enumerable:!0,get:function(){return r.formula}}),Object.defineProperty(exports,"group",{enumerable:!0,get:function(){return r.group}}),Object.defineProperty(exports,"listView",{enumerable:!0,get:function(){return r.listView}}),Object.defineProperty(exports,"location",{enumerable:!0,get:function(){return r.location}}),Object.defineProperty(exports,"multiselect",{enumerable:!0,get:function(){return r.multiselect}}),Object.defineProperty(exports,"now",{enumerable:!0,get:function(){return r.now}}),Object.defineProperty(exports,"number",{enumerable:!0,get:function(){return r.number}}),Object.defineProperty(exports,"object",{enumerable:!0,get:function(){return r.object}}),Object.defineProperty(exports,"phone",{enumerable:!0,get:function(){return r.phone}}),Object.defineProperty(exports,"query",{enumerable:!0,get:function(){return r.query}}),exports.recordsPath=t.a,Object.defineProperty(exports,"relation",{enumerable:!0,get:function(){return r.relation}}),exports.reviveRecord=e.o,Object.defineProperty(exports,"richtext",{enumerable:!0,get:function(){return r.richtext}}),Object.defineProperty(exports,"rollup",{enumerable:!0,get:function(){return r.rollup}}),Object.defineProperty(exports,"select",{enumerable:!0,get:function(){return r.select}}),Object.defineProperty(exports,"status",{enumerable:!0,get:function(){return r.status}}),exports.syncBundle=e.u,Object.defineProperty(exports,"text",{enumerable:!0,get:function(){return r.text}}),Object.defineProperty(exports,"today",{enumerable:!0,get:function(){return r.today}}),Object.defineProperty(exports,"user",{enumerable:!0,get:function(){return r.user}});
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./create-standards-CqOOm8eg.js"),t=require("./app-d25WfBqA.js");let n=require("@standards/schema/api"),r=require("@standards/schema");Object.defineProperty(exports,"BUNDLE_NAME_PATTERN",{enumerable:!0,get:function(){return r.BUNDLE_NAME_PATTERN}}),exports.BundleConflictError=t.d,exports.BundleValidationError=t.f,Object.defineProperty(exports,"DuplicateError",{enumerable:!0,get:function(){return r.DuplicateError}}),Object.defineProperty(exports,"ForbiddenError",{enumerable:!0,get:function(){return r.ForbiddenError}}),Object.defineProperty(exports,"NotFoundError",{enumerable:!0,get:function(){return r.NotFoundError}}),Object.defineProperty(exports,"SchemaError",{enumerable:!0,get:function(){return r.SchemaError}}),Object.defineProperty(exports,"SchemaErrorCode",{enumerable:!0,get:function(){return r.SchemaErrorCode}}),exports.StandardsAuthError=t.p,exports.StandardsConfigurationError=t.m,exports.StandardsRequestError=t.h,Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return r.ValidationError}}),Object.defineProperty(exports,"assertBundleName",{enumerable:!0,get:function(){return r.assertBundleName}}),Object.defineProperty(exports,"bundle",{enumerable:!0,get:function(){return r.bundle}}),Object.defineProperty(exports,"canonicalStringify",{enumerable:!0,get:function(){return r.canonicalStringify}}),Object.defineProperty(exports,"checkbox",{enumerable:!0,get:function(){return r.checkbox}}),Object.defineProperty(exports,"content",{enumerable:!0,get:function(){return r.content}}),exports.createRecordsQuery=e.r,exports.createStandards=e.n,exports.createTransport=t.i,Object.defineProperty(exports,"currency",{enumerable:!0,get:function(){return r.currency}}),Object.defineProperty(exports,"currentActor",{enumerable:!0,get:function(){return r.currentActor}}),Object.defineProperty(exports,"date",{enumerable:!0,get:function(){return r.date}}),Object.defineProperty(exports,"detailView",{enumerable:!0,get:function(){return r.detailView}}),Object.defineProperty(exports,"document",{enumerable:!0,get:function(){return r.document}}),Object.defineProperty(exports,"encodePathSegment",{enumerable:!0,get:function(){return n.encodePathSegment}}),Object.defineProperty(exports,"formula",{enumerable:!0,get:function(){return r.formula}}),Object.defineProperty(exports,"group",{enumerable:!0,get:function(){return r.group}}),Object.defineProperty(exports,"listView",{enumerable:!0,get:function(){return r.listView}}),Object.defineProperty(exports,"location",{enumerable:!0,get:function(){return r.location}}),Object.defineProperty(exports,"multiselect",{enumerable:!0,get:function(){return r.multiselect}}),Object.defineProperty(exports,"now",{enumerable:!0,get:function(){return r.now}}),Object.defineProperty(exports,"number",{enumerable:!0,get:function(){return r.number}}),Object.defineProperty(exports,"object",{enumerable:!0,get:function(){return r.object}}),Object.defineProperty(exports,"phone",{enumerable:!0,get:function(){return r.phone}}),Object.defineProperty(exports,"query",{enumerable:!0,get:function(){return r.query}}),exports.recordsPath=t.s,Object.defineProperty(exports,"relation",{enumerable:!0,get:function(){return r.relation}}),Object.defineProperty(exports,"richtext",{enumerable:!0,get:function(){return r.richtext}}),Object.defineProperty(exports,"rollup",{enumerable:!0,get:function(){return r.rollup}}),Object.defineProperty(exports,"select",{enumerable:!0,get:function(){return r.select}}),Object.defineProperty(exports,"status",{enumerable:!0,get:function(){return r.status}}),exports.syncBundle=e.o,Object.defineProperty(exports,"text",{enumerable:!0,get:function(){return r.text}}),Object.defineProperty(exports,"today",{enumerable:!0,get:function(){return r.today}}),Object.defineProperty(exports,"user",{enumerable:!0,get:function(){return r.user}});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
- import{c as e,i as t,l as n,n as r,o as i,r as a,u as o}from"./create-standards-Dn5ZKfjN.mjs";import{_ as s,a as c,g as l,h as u,m as d,n as f,p}from"./http-transport-GAQftrWY.mjs";import{BUNDLE_NAME_PATTERN as m,DuplicateError as h,ForbiddenError as g,NotFoundError as _,SchemaError as v,SchemaErrorCode as y,ValidationError as b,assertBundleName as x,bundle as S,canonicalStringify as C,checkbox as w,content as T,currency as E,currentActor as D,date as O,detailView as k,document as A,formula as j,group as M,listView as N,location as P,multiselect as F,now as I,number as L,object as R,phone as z,query as B,relation as V,richtext as H,rollup as U,select as W,status as G,text as K,today as q,user as J}from"@standards/schema";import{encodePathSegment as Y}from"@standards/schema/api";export{m as BUNDLE_NAME_PATTERN,p as BundleConflictError,d as BundleValidationError,h as DuplicateError,g as ForbiddenError,_ as NotFoundError,v as SchemaError,y as SchemaErrorCode,u as StandardsAuthError,l as StandardsConfigurationError,s as StandardsRequestError,b as ValidationError,x as assertBundleName,S as bundle,C as canonicalStringify,w as checkbox,T as content,n as createDocumentsApi,e as createFilesApi,t as createRecordsQuery,r as createStandards,f as createTransport,a as createUsageApi,E as currency,D as currentActor,O as date,k as detailView,A as document,Y as encodePathSegment,j as formula,M as group,N as listView,P as location,F as multiselect,I as now,L as number,R as object,z as phone,B as query,c as recordsPath,V as relation,i as reviveRecord,H as richtext,U as rollup,W as select,G as status,o as syncBundle,K as text,q as today,J as user};
2
+ import{n as e,o as t,r as n}from"./create-standards-orKjtGR6.mjs";import{d as r,f as i,h as a,i as o,m as s,p as c,s as l}from"./app-CjHQKAwu.mjs";import{BUNDLE_NAME_PATTERN as u,DuplicateError as d,ForbiddenError as f,NotFoundError as p,SchemaError as m,SchemaErrorCode as h,ValidationError as g,assertBundleName as _,bundle as v,canonicalStringify as y,checkbox as b,content as x,currency as S,currentActor as C,date as w,detailView as T,document as E,formula as D,group as O,listView as k,location as A,multiselect as j,now as M,number as N,object as P,phone as F,query as I,relation as L,richtext as R,rollup as z,select as B,status as V,text as H,today as U,user as W}from"@standards/schema";import{encodePathSegment as G}from"@standards/schema/api";export{u as BUNDLE_NAME_PATTERN,r as BundleConflictError,i as BundleValidationError,d as DuplicateError,f as ForbiddenError,p as NotFoundError,m as SchemaError,h as SchemaErrorCode,c as StandardsAuthError,s as StandardsConfigurationError,a as StandardsRequestError,g as ValidationError,_ as assertBundleName,v as bundle,y as canonicalStringify,b as checkbox,x as content,n as createRecordsQuery,e as createStandards,o as createTransport,S as currency,C as currentActor,w as date,T as detailView,E as document,G as encodePathSegment,D as formula,O as group,k as listView,A as location,j as multiselect,M as now,N as number,P as object,F as phone,I as query,l as recordsPath,L as relation,R as richtext,z as rollup,B as select,V as status,t as syncBundle,H as text,U as today,W as user};
@@ -1,6 +1,6 @@
1
1
 
2
- import { i as Standards, n as ObjectsOf, r as ObjectsOfBundles, t as AnyBundle } from "./create-standards-HiWpTAlP.mjs";
3
- import "./http-transport-BxJhcXjy.mjs";
2
+ import { i as ObjectsOfBundles, s as StandardsOf, t as AnyBundle } from "./create-standards-B4fQnzl5.mjs";
3
+ import "./app-TCIe_XWO.mjs";
4
4
  import { ExtractRecord, ExtractRecordInputStrict, ObjectBuilderLike } from "@standards/schema";
5
5
  /**
6
6
  * A filter rule the in-memory workspace does not serve. The server answers
@@ -42,7 +42,7 @@ export type TestSeed<TBuilder> = Omit<ExtractRecordInputStrict<TBuilder>, Pinned
42
42
  };
43
43
  export interface TestStandards<TObjects extends readonly ObjectBuilderLike[]> {
44
44
  /** The real client over the in-memory workspace: pass it wherever the app takes `createStandards`'s. */
45
- db: Standards & ObjectsOf<TObjects>;
45
+ db: StandardsOf<TObjects>;
46
46
  /**
47
47
  * Store records directly, without a request; ids and timestamps are filled
48
48
  * in unless given. Keyed by the object's name, as `from()` is.
@@ -60,7 +60,9 @@ export interface TestStandards<TObjects extends readonly ObjectBuilderLike[]> {
60
60
  * app ships — over a transport that answers like the records API: pages of 20
61
61
  * by default and 1000 at most, newest first, the server's filter operators and
62
62
  * sort order. An operator it does not serve throws
63
- * `UnsupportedFilterOperatorError`; any other route answers `501`.
63
+ * `UnsupportedFilterOperatorError`. `update` with `metadata` is served (its
64
+ * single `record.set` step of `POST /operations`), the metadata not kept; any
65
+ * other route answers `501`.
64
66
  *
65
67
  * @example
66
68
  * const { db, seed } = createTestStandards({ bundles: [helpdesk] });
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
- import { i as Standards, n as ObjectsOf, r as ObjectsOfBundles, t as AnyBundle } from "./create-standards-BWOo2EZw.js";
3
- import "./http-transport-BxJhcXjy.js";
2
+ import { i as ObjectsOfBundles, s as StandardsOf, t as AnyBundle } from "./create-standards-YjhWkQYe.js";
3
+ import "./app-TCIe_XWO.js";
4
4
  import { ExtractRecord, ExtractRecordInputStrict, ObjectBuilderLike } from "@standards/schema";
5
5
  /**
6
6
  * A filter rule the in-memory workspace does not serve. The server answers
@@ -42,7 +42,7 @@ export type TestSeed<TBuilder> = Omit<ExtractRecordInputStrict<TBuilder>, Pinned
42
42
  };
43
43
  export interface TestStandards<TObjects extends readonly ObjectBuilderLike[]> {
44
44
  /** The real client over the in-memory workspace: pass it wherever the app takes `createStandards`'s. */
45
- db: Standards & ObjectsOf<TObjects>;
45
+ db: StandardsOf<TObjects>;
46
46
  /**
47
47
  * Store records directly, without a request; ids and timestamps are filled
48
48
  * in unless given. Keyed by the object's name, as `from()` is.
@@ -60,7 +60,9 @@ export interface TestStandards<TObjects extends readonly ObjectBuilderLike[]> {
60
60
  * app ships — over a transport that answers like the records API: pages of 20
61
61
  * by default and 1000 at most, newest first, the server's filter operators and
62
62
  * sort order. An operator it does not serve throws
63
- * `UnsupportedFilterOperatorError`; any other route answers `501`.
63
+ * `UnsupportedFilterOperatorError`. `update` with `metadata` is served (its
64
+ * single `record.set` step of `POST /operations`), the metadata not kept; any
65
+ * other route answers `501`.
64
66
  *
65
67
  * @example
66
68
  * const { db, seed } = createTestStandards({ bundles: [helpdesk] });
package/dist/testing.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./create-standards-Bl-VDgXY.js"),t=require("./http-transport-Dr0ZiTG1.js");let n=require("@standards/schema"),r=require("@standards/schema/api");var UnsupportedFilterOperatorError=class extends Error{constructor(e,t){super(`The in-memory test workspace does not serve the "${e}" operator (on "${t}"). Test it against a real workspace.`),this.name=`UnsupportedFilterOperatorError`,this.operator=e}};const i=/* @__PURE__ */ new Set([`id`,`createdAt`,`updatedAt`]),a=/* @__PURE__ */ new Set([`createdAt`,`updatedAt`]),o=/* @__PURE__ */ new Set([`number`,`currency`]),s=/* @__PURE__ */ new Set([`select`,`status`]),c=/^\d{4}-\d{2}-\d{2}/;function attributeValue(e,t){if(i.has(t))return e[t];let n=e.values[t];return typeof n==`object`&&n&&`value`in n&&!Array.isArray(n)?n.value:n}function isEmptyValue(e){return e==null||e===``||Array.isArray(e)&&e.length===0}function textOf(e){return e==null?null:e instanceof Date?e.toISOString():typeof e==`string`?e:JSON.stringify(e)}function members(e){return Array.isArray(e)?e.map(String):null}function dayOf(e){let t=textOf(e);if(t===null||!c.test(t))return null;let n=t.slice(0,10);return Number.isNaN(Date.parse(`${n}T00:00:00.000Z`))?null:n}function nextDay(e){let t=/* @__PURE__ */ new Date(`${e}T00:00:00.000Z`);return t.setUTCDate(t.getUTCDate()+1),t.toISOString().slice(0,10)}function isUnmodelledDate(e){if(e?.type!==`date`)return!1;let t=e;return t.endDate===!0||t.includeTime===!0}function matchesDay(e,t,n,r){let i=dayOf(n);if(i===null)return!1;let a=textOf(t),o=nextDay(i),s=r?textOf(n)??i:i;switch(e){case`is`:return a!==null&&a>=s&&a<o;case`is_not`:return a===null||a<s||a>=o;case`greater_than`:return a!==null&&a>=o;case`greater_or_equal`:return a!==null&&a>=s;case`less_than`:return a!==null&&a<s;default:return a!==null&&a<o}}function compare(e,t,n){let r=textOf(e),i=textOf(t);if(r===null||i===null)return null;if(n){let e=Number(r),t=Number(i);return r===``||Number.isNaN(e)||Number.isNaN(t)?null:e-t}return r<i?-1:+(r>i)}function matchesRule(e,t,r){let i=r.attributes.find(e=>e.name===t.attribute)?.type,s=attributeValue(e,t.attribute),c=i!==void 0&&o.has(i),l=textOf(t.value),u=l===null?void 0:(0,n.foldText)(l),d=textOf(s),f=d===null?null:(0,n.foldText)(d);if((i===`date`||a.has(t.attribute))&&[`is`,`is_not`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`].includes(t.operator))return matchesDay(t.operator,s,t.value,a.has(t.attribute));switch(t.operator){case`is`:return i===`checkbox`||i===void 0&&typeof t.value==`boolean`?t.value===!0?s===!0:s!==!0:textOf(s)!==null&&textOf(s)===textOf(t.value);case`is_not`:return textOf(s)===null||textOf(s)!==textOf(t.value);case`contains`:return Array.isArray(s)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>s.map(String).includes(e)):f!==null&&u!==void 0&&f.includes(u);case`not_contains`:return s==null||!matchesRule(e,{...t,operator:`contains`},r);case`starts_with`:return f!==null&&u!==void 0&&f.startsWith(u);case`ends_with`:return f!==null&&u!==void 0&&f.endsWith(u);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(s,t.value,c);return e===null?!1:t.operator===`greater_than`?e>0:t.operator===`greater_or_equal`?e>=0:t.operator===`less_than`?e<0:e<=0}case`is_empty`:return isEmptyValue(s);case`is_not_empty`:return!isEmptyValue(s);case`any_of`:{let e=members(t.value);return e===null||e.length===0||s==null?!1:Array.isArray(s)?s.some(t=>e.includes(String(t))):e.includes(textOf(s)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||s==null?!0:Array.isArray(s)?!s.some(t=>e.includes(String(t))):!e.includes(textOf(s)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const l=/* @__PURE__ */ new Set([`is`,`is_not`,`contains`,`not_contains`,`starts_with`,`ends_with`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`,`is_empty`,`is_not_empty`,`any_of`,`none_of`]);function assertServedOperators(e,t){for(let n of e?.rules??[])if(!l.has(n.operator)||isUnmodelledDate(t.attributes.find(e=>e.name===n.attribute))&&n.operator!==`is_empty`&&n.operator!==`is_not_empty`)throw new UnsupportedFilterOperatorError(n.operator,n.attribute)}function matchesFilters(e,t,n){let r=t?.rules??[];if(r.length===0)return!0;let i=r.map(t=>matchesRule(e,t,n));return t?.combinator===`or`?i.some(Boolean):i.every(Boolean)}function matchesSearch(e,t){let n=t.trim().toLowerCase();return n===``||Object.values(e.values).some(e=>(Array.isArray(e)?e:[e]).some(e=>typeof e==`string`&&e.toLowerCase().includes(n)))}function sortKey(e,t,n){let r=attributeValue(e,t),i=n.attributes.find(e=>e.name===t);if(i&&s.has(i.type)){let e=(i.options??[]).findIndex(e=>e.value===r);return{position:e===-1?null:e,value:r}}return r}function isOptionKey(e){return typeof e==`object`&&!!e&&`position`in e}function compareOptionKeys(e,t,n){let r=n===`desc`?-1:1;return e.position!==null&&t.position!==null?r*(e.position-t.position):e.position!==null||t.position!==null?e.position===null?1:-1:r*(compare(e.value,t.value,!1)??0)}function compareRecords(e,t){let n=e&&e.length>0?[...e]:[{attribute:`createdAt`,direction:`desc`}];return n.some(e=>e.attribute===`id`)||n.push({attribute:`id`,direction:`asc`}),(e,r)=>{for(let i of n){let n=t.attributes.find(e=>e.name===i.attribute)?.type,a=sortKey(e,i.attribute,t),s=sortKey(r,i.attribute,t),c=isOptionKey(a)?a.value:a,l=isOptionKey(s)?s.value:s,u=textOf(c)===null,d=textOf(l)===null;if(u||d){if(u&&d)continue;return u?1:-1}if(isOptionKey(a)&&isOptionKey(s)){let e=compareOptionKeys(a,s,i.direction);if(e!==0)return e;continue}let f=compare(a,s,n!==void 0&&o.has(n))??0;if(f!==0)return i.direction===`desc`?-f:f}return 0}}const u=`SCHEMA_RECORD_NOT_FOUND`,d=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,f=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...(0,n.getObjectSystemAttributes)(e)]}}function withoutSystemKeys(e){let t={...e};for(let e of f)delete t[e];return t}function boundOf(e,n,r){if(e==null)return r;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new t._(400,`${n} must be a non-negative integer`);return e}function errorFor(e,n,r){return e===401||e===403?new t.h(e,n,r):new t._(e,n,r)}function asTheServerValidates(e){try{e()}catch(e){throw e instanceof n.ValidationError?new t._(400,e.message,e.code):e}}function notServed(e,n){return new t._(501,`The in-memory test workspace does not serve ${e} ${n}: only the records API is in memory.`)}function isoOf(e,t){return e===void 0?t:e instanceof Date?e.toISOString():new Date(e).toISOString()}function wire(e){return JSON.parse(JSON.stringify(e))}function createInMemoryApi(i){let a=/* @__PURE__ */ new Map;for(let t of i.builders){let n=e.a(t);a.set(n.name,n)}let o=new Map([...a.keys()].map(e=>[e,[]])),s=/* @__PURE__ */ new Set,c=null,l=0,f=1;function now(){return l=Math.max(Date.now(),l+1),new Date(l).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(f++).toString(16).padStart(12,`0`)}`;while(s.has(e));return e}function objectOf(e){let n=a.get(e),r=o.get(e);if(!(n&&r))throw new t._(404,`Object "${e}" not found. Make sure the object exists and you have access to it.`);return{definition:n,records:r}}function insert(t,n){let{records:r}=objectOf(t),{id:i,createdAt:a,updatedAt:o,...c}=n,l=now(),u={id:i??newId(),values:wire(e.s(c)),createdAt:isoOf(a,l),updatedAt:isoOf(o,isoOf(a,l)),visibility:`workspace`,ownedBy:null,metadata:{}};return r.push(u),s.add(u.id),u}function find(e,n){let r=objectOf(e).records.find(e=>e.id===n);if(!r)throw new t._(404,readNotFound(n),u);return r}function requireWritable(e,n){if(!objectOf(e).records.some(e=>e.id===n))throw new t._(404,writeNotFound(n),u)}function update(e,n,r){let i=objectOf(e).records.find(e=>e.id===n);if(!i)throw new t._(404,writeNotFound(n),u);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(e,n){let{records:r}=objectOf(e),i=r.findIndex(e=>e.id===n);if(i===-1)throw new t._(404,writeNotFound(n),u);r.splice(i,1)}function list(e,t,r){let{definition:i,records:a}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>(0,n.validateQualifiedRule)(structuredClone(e),{attributes:i.attributes}));assertServedOperators(t.filters,i);let o=Math.min(boundOf(t.limit,`limit`,20),1e3),s=boundOf(t.offset,`offset`,0);if(o===0)return{data:[],page:{hasMore:!1,total:null,countMode:`none`}};let c=r?t.q:void 0,l=a.filter(e=>matchesFilters(e,t.filters,i)).filter(e=>c===void 0||matchesSearch(e,c)).sort(compareRecords(t.sorts,i)),u=l.slice(s,s+o);return{data:u,page:{hasMore:s+u.length<l.length,total:null,countMode:`none`}}}function bulk(e,r,i){let a=i.records??i.updates??i.ids;if(!Array.isArray(a)||a.length>100)throw new t._(400,`A bulk request carries at most 100 items.`);let o=withSystemAttributes(objectOf(e).definition);if(r===`bulk-create`){let r=[],i=[];for(let[s,c]of a.entries())if(!(0,n.isPlainRecord)(c))i.push({index:s,error:`Record data must be an object`});else try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(insert(e,withoutSystemKeys(c)))}catch(e){if(!(e instanceof t._))throw e;i.push({index:s,error:e.message})}return{created:r,errors:i}}if(r===`bulk-update`){let r=[],i=[];for(let{id:s,data:c}of a)try{if(!(0,n.isPlainRecord)(c))throw new t._(400,`Update data must be an object`,d);requireWritable(e,s),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(update(e,s,c))}catch(e){if(!(e instanceof t._))throw e;i.push({id:s,error:e.message,code:e.code??d})}return{updated:r,errors:i}}let s=[],c=[];for(let t of a)try{remove(e,t),s.push(t)}catch{c.push({id:t,error:writeNotFound(t),code:u})}return{deleted:s,errors:c}}function route(e,r,i){let[a,o,s,...c]=r.replace(/^\/+/,``).split(`/`);if(a!==`records`||o===void 0||c.length>0)throw notServed(e,r);let l=decodeURIComponent(o),u=s===void 0?void 0:decodeURIComponent(s),d=(0,n.isPlainRecord)(i)?i:{};if(e===`POST`&&u===void 0){let e=(0,n.isPlainRecord)(d.data)?d.data:{};return asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(e===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(e===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(e,r);if(e===`GET`)return find(l,u);if(e===`PUT`||e===`PATCH`){if(Object.keys(d).length===0)throw new t._(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(e===`DELETE`)return remove(l,u),null;throw notServed(e,r)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(c){let{status:e,failure:t}=c;throw c=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let p={call:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=(0,r.splitOperationInput)(e,t??{});throw notServed(e.method,n)}),get:e=>request(`GET`,e),post:(e,t)=>request(`POST`,e,t),patch:(e,t)=>request(`PATCH`,e,t),put:(e,t)=>request(`PUT`,e,t),delete:e=>request(`DELETE`,e),getText:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`GET`,e)}),postRaw:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`POST`,e)}),postMultipart:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`POST`,e)})};return{transport:p,get:p.get,post:p.post,definitionOf:e=>objectOf(e).definition,seed:(e,t)=>t.map(t=>insert(e,t)),records:e=>objectOf(e).records,failNextRequestWith(e,t={}){c={status:e,failure:t}}}}function createTestStandards(t){let n=t.bundles.flatMap(e=>e.objectBuilders),r=createInMemoryApi({builders:n}),flatten=(t,n)=>e.o(r.definitionOf(t),JSON.parse(JSON.stringify(n)));return{db:e.t(r.transport,n),seed:(e,t)=>r.seed(e,t).map(t=>flatten(e,t)),records:e=>r.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>r.failNextRequestWith(e,t)}}exports.UnsupportedFilterOperatorError=UnsupportedFilterOperatorError,exports.createTestStandards=createTestStandards;
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./create-standards-CqOOm8eg.js"),t=require("./app-d25WfBqA.js");let n=require("@standards/schema"),r=require("@standards/schema/api");var UnsupportedFilterOperatorError=class extends Error{constructor(e,t){super(`The in-memory test workspace does not serve the "${e}" operator (on "${t}"). Test it against a real workspace.`),this.name=`UnsupportedFilterOperatorError`,this.operator=e}};const i=/* @__PURE__ */ new Set([`id`,`createdAt`,`updatedAt`]),a=/* @__PURE__ */ new Set([`createdAt`,`updatedAt`]),o=/* @__PURE__ */ new Set([`number`,`currency`]),s=/* @__PURE__ */ new Set([`select`,`status`]),c=/^\d{4}-\d{2}-\d{2}/,l=/^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:[T ]((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,6})?)?)(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;function attributeValue(e,t){if(i.has(t))return e[t];let n=e.values[t];return typeof n==`object`&&n&&`value`in n&&!Array.isArray(n)?n.value:n}function isEmptyValue(e){return e==null||e===``||Array.isArray(e)&&e.length===0}function textOf(e){return e==null?null:e instanceof Date?e.toISOString():typeof e==`string`?e:JSON.stringify(e)}function members(e){return Array.isArray(e)?e.map(String):null}function dayOf(e){let t=textOf(e);if(t===null||!c.test(t))return null;let n=t.slice(0,10);return Number.isNaN(Date.parse(`${n}T00:00:00.000Z`))?null:n}const u=Date.parse(`0001-01-01T00:00:00Z`);function instantOf(e){let t=typeof e==`object`&&e&&`start`in e?e.start:e,n=typeof t==`string`?l.exec(t):null;if(!n)return null;let[,r=``,i=`00:00`,a=`Z`]=n;if(r.startsWith(`0000`))return null;let o=a===`Z`?`Z`:`${a.slice(0,3)}:${a.slice(3).replace(`:`,``)||`00`}`,s=Date.parse(`${r}T${i}${o}`);return Number.isNaN(s)||(/* @__PURE__ */ new Date(`${r}T00:00:00Z`)).toISOString().slice(0,10)!==r||s<u?null:s}function nextDay(e){let t=/* @__PURE__ */ new Date(`${e}T00:00:00.000Z`);return t.setUTCDate(t.getUTCDate()+1),t.toISOString().slice(0,10)}function isUnmodelledDate(e){if(e?.type!==`date`)return!1;let t=e;return t.endDate===!0||t.includeTime===!0}function isTimedDate(e){return e?.type===`date`&&e.includeTime===!0}function matchesDay(e,t,n,r){let i=dayOf(n);if(i===null)return!1;let a=textOf(t),o=nextDay(i),s=r?textOf(n)??i:i;switch(e){case`is`:return a!==null&&a>=s&&a<o;case`is_not`:return a===null||a<s||a>=o;case`greater_than`:return a!==null&&a>=o;case`greater_or_equal`:return a!==null&&a>=s;case`less_than`:return a!==null&&a<s;default:return a!==null&&a<o}}function compare(e,t,n){let r=textOf(e),i=textOf(t);if(r===null||i===null)return null;if(n){let e=Number(r),t=Number(i);return r===``||Number.isNaN(e)||Number.isNaN(t)?null:e-t}return r<i?-1:+(r>i)}function matchesRule(e,t,r){let i=r.attributes.find(e=>e.name===t.attribute)?.type,s=attributeValue(e,t.attribute),c=i!==void 0&&o.has(i),l=textOf(t.value),u=l===null?void 0:(0,n.foldText)(l),d=textOf(s),f=d===null?null:(0,n.foldText)(d);if((i===`date`||a.has(t.attribute))&&[`is`,`is_not`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`].includes(t.operator))return matchesDay(t.operator,s,t.value,a.has(t.attribute));switch(t.operator){case`is`:return i===`checkbox`||i===void 0&&typeof t.value==`boolean`?t.value===!0?s===!0:s!==!0:textOf(s)!==null&&textOf(s)===textOf(t.value);case`is_not`:return textOf(s)===null||textOf(s)!==textOf(t.value);case`contains`:return Array.isArray(s)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>s.map(String).includes(e)):f!==null&&u!==void 0&&f.includes(u);case`not_contains`:return s==null||!matchesRule(e,{...t,operator:`contains`},r);case`starts_with`:return f!==null&&u!==void 0&&f.startsWith(u);case`ends_with`:return f!==null&&u!==void 0&&f.endsWith(u);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(s,t.value,c);return e===null?!1:t.operator===`greater_than`?e>0:t.operator===`greater_or_equal`?e>=0:t.operator===`less_than`?e<0:e<=0}case`is_empty`:return isEmptyValue(s);case`is_not_empty`:return!isEmptyValue(s);case`any_of`:{let e=members(t.value);return e===null||e.length===0||s==null?!1:Array.isArray(s)?s.some(t=>e.includes(String(t))):e.includes(textOf(s)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||s==null?!0:Array.isArray(s)?!s.some(t=>e.includes(String(t))):!e.includes(textOf(s)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const d=/* @__PURE__ */ new Set([`is`,`is_not`,`contains`,`not_contains`,`starts_with`,`ends_with`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`,`is_empty`,`is_not_empty`,`any_of`,`none_of`]);function assertServedOperators(e,t){for(let n of e?.rules??[])if(!d.has(n.operator)||n.attribute.startsWith(`metadata.`)||isUnmodelledDate(t.attributes.find(e=>e.name===n.attribute))&&n.operator!==`is_empty`&&n.operator!==`is_not_empty`)throw new UnsupportedFilterOperatorError(n.operator,n.attribute)}function matchesFilters(e,t,n){let r=t?.rules??[];if(r.length===0)return!0;let i=r.map(t=>matchesRule(e,t,n));return t?.combinator===`or`?i.some(Boolean):i.every(Boolean)}function matchesSearch(e,t){let n=t.trim().toLowerCase();return n===``||Object.values(e.values).some(e=>(Array.isArray(e)?e:[e]).some(e=>typeof e==`string`&&e.toLowerCase().includes(n)))}function sortKey(e,t,n){let r=attributeValue(e,t),i=n.attributes.find(e=>e.name===t);if(i&&s.has(i.type)){let e=(i.options??[]).findIndex(e=>e.value===r);return{position:e===-1?null:e,value:r}}return r}function isOptionKey(e){return typeof e==`object`&&!!e&&`position`in e}function compareOptionKeys(e,t,n){let r=n===`desc`?-1:1;return e.position!==null&&t.position!==null?r*(e.position-t.position):e.position!==null||t.position!==null?e.position===null?1:-1:r*(compare(e.value,t.value,!1)??0)}function compareInstants(e,t,n){let r=instantOf(e.values[n.attribute]),i=instantOf(t.values[n.attribute]);return r===i?0:r===null||i===null?r===null?1:-1:n.direction===`desc`?i-r:r-i}function compareRecords(e,t){let n=e&&e.length>0?[...e]:[{attribute:`createdAt`,direction:`desc`}];return n.some(e=>e.attribute===`id`)||n.push({attribute:`id`,direction:`asc`}),(e,r)=>{for(let i of n){let n=t.attributes.find(e=>e.name===i.attribute),a=n?.type;if(isTimedDate(n)){let t=compareInstants(e,r,i);if(t!==0)return t;continue}let s=sortKey(e,i.attribute,t),c=sortKey(r,i.attribute,t),l=isOptionKey(s)?s.value:s,u=isOptionKey(c)?c.value:c,d=textOf(l)===null,f=textOf(u)===null;if(d||f){if(d&&f)continue;return d?1:-1}if(isOptionKey(s)&&isOptionKey(c)){let e=compareOptionKeys(s,c,i.direction);if(e!==0)return e;continue}let p=compare(s,c,a!==void 0&&o.has(a))??0;if(p!==0)return i.direction===`desc`?-p:p}return 0}}const f=`SCHEMA_RECORD_NOT_FOUND`,p=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,m=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...(0,n.getObjectSystemAttributes)(e)]}}function withoutSystemKeys(e){let t={...e};for(let e of m)delete t[e];return t}function boundOf(e,n,r){if(e==null)return r;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new t.h(400,`${n} must be a non-negative integer`);return e}function errorFor(e,n,r){return e===401||e===403?new t.p(e,n,r):new t.h(e,n,r)}function asTheServerValidates(e){try{e()}catch(e){throw e instanceof n.ValidationError?new t.h(400,e.message,e.code):e}}function notServed(e,n){return new t.h(501,`The in-memory test workspace does not serve ${e} ${n}: only the records API is in memory.`)}function isoOf(e,t){return e===void 0?t:e instanceof Date?e.toISOString():new Date(e).toISOString()}function wire(e){return JSON.parse(JSON.stringify(e))}function createInMemoryApi(i){let a=/* @__PURE__ */ new Map;for(let t of i.builders){let n=e.i(t);a.set(n.name,n)}let o=new Map([...a.keys()].map(e=>[e,[]])),s=/* @__PURE__ */ new Set,c=null,l=0,u=1;function now(){return l=Math.max(Date.now(),l+1),new Date(l).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(u++).toString(16).padStart(12,`0`)}`;while(s.has(e));return e}function objectOf(e){let n=a.get(e),r=o.get(e);if(!(n&&r))throw new t.h(404,`Object "${e}" not found. Make sure the object exists and you have access to it.`);return{definition:n,records:r}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:i,updatedAt:a,...o}=t,c=now(),l={id:r??newId(),values:wire(o),createdAt:isoOf(i,c),updatedAt:isoOf(a,isoOf(i,c)),visibility:`workspace`,ownedBy:null,metadata:{},objectId:objectOf(e).definition.id??e,label:``,parentId:null,ancestorIds:[],trashedWithRecordId:null,schemaVersion:1};return n.push(l),s.add(l.id),l}function find(e,n){let r=objectOf(e).records.find(e=>e.id===n);if(!r)throw new t.h(404,readNotFound(n),f);return r}function requireWritable(e,n){if(!objectOf(e).records.some(e=>e.id===n))throw new t.h(404,writeNotFound(n),f)}function update(e,n,r){let i=objectOf(e).records.find(e=>e.id===n);if(!i)throw new t.h(404,writeNotFound(n),f);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(e,n){let{records:r}=objectOf(e),i=r.findIndex(e=>e.id===n);if(i===-1)throw new t.h(404,writeNotFound(n),f);r.splice(i,1)}function list(e,t,r){let{definition:i,records:a}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>(0,n.validateQualifiedRule)(structuredClone(e),{attributes:i.attributes}));assertServedOperators(t.filters,i);let o=Math.min(boundOf(t.limit,`limit`,20),1e3),s=boundOf(t.offset,`offset`,0);if(o===0)return{data:[],page:{hasMore:!1,total:null,countMode:`none`}};let c=r?t.q:void 0,l=a.filter(e=>matchesFilters(e,t.filters,i)).filter(e=>c===void 0||matchesSearch(e,c)).sort(compareRecords(t.sorts,i)),u=l.slice(s,s+o);return{data:u,page:{hasMore:s+u.length<l.length,total:null,countMode:`none`}}}function bulk(e,r,i){let a=i.records??i.updates??i.ids;if(!Array.isArray(a)||a.length>100)throw new t.h(400,`A bulk request carries at most 100 items.`);let o=withSystemAttributes(objectOf(e).definition);if(r===`bulk-create`){let r=[],i=[];for(let[s,c]of a.entries())if(!(0,n.isPlainRecord)(c))i.push({index:s,error:`Record data must be an object`});else try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(insert(e,withoutSystemKeys(c)))}catch(e){if(!(e instanceof t.h))throw e;i.push({index:s,error:e.message})}return{created:r,errors:i}}if(r===`bulk-update`){let r=[],i=[];for(let{id:s,data:c}of a)try{if(!(0,n.isPlainRecord)(c))throw new t.h(400,`Update data must be an object`,p);requireWritable(e,s),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(update(e,s,c))}catch(e){if(!(e instanceof t.h))throw e;i.push({id:s,error:e.message,code:e.code??p})}return{updated:r,errors:i}}let s=[],c=[];for(let t of a)try{remove(e,t),s.push(t)}catch{c.push({id:t,error:writeNotFound(t),code:f})}return{deleted:s,errors:c}}function operation(e,r,i){let o=Array.isArray(i.steps)?i.steps:[],[s]=o;if(o.length!==1||!(0,n.isPlainRecord)(s)||s.kind!==`record.set`)throw notServed(e,r);let c=String(s.recordId),l=(0,n.isPlainRecord)(s.values)?s.values:{},u=[...a].find(([e,t])=>(t.id??e)===s.objectId)?.[0],answer=e=>({opId:i.opId,steps:[e],inverse:null});if(u===void 0||!objectOf(u).records.some(e=>e.id===c))return answer({status:`error`,recordId:c,code:f});try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(u).definition),l))}catch(e){if(!(e instanceof t.h))throw e;let n=e.code??p;return answer({status:`error`,recordId:c,code:n,...n===p&&{message:e.message}})}return answer({status:`applied`,record:update(u,c,l)})}function route(e,r,i){let[a,o,s,...c]=r.replace(/^\/+/,``).split(`/`);if(e===`POST`&&a===`operations`&&o===void 0)return operation(e,r,(0,n.isPlainRecord)(i)?i:{});if(a!==`records`||o===void 0||c.length>0)throw notServed(e,r);let l=decodeURIComponent(o),u=s===void 0?void 0:decodeURIComponent(s),d=(0,n.isPlainRecord)(i)?i:{};if(e===`POST`&&u===void 0){let e=(0,n.isPlainRecord)(d.data)?d.data:{};return asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(e===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(e===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(e,r);if(e===`GET`)return find(l,u);if(e===`PUT`||e===`PATCH`){if(Object.keys(d).length===0)throw new t.h(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(e===`DELETE`)return remove(l,u),null;throw notServed(e,r)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(c){let{status:e,failure:t}=c;throw c=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let d={call:(e,t)=>Promise.resolve().then(()=>{let{path:n,body:i}=(0,r.splitOperationInput)(e,t??{});return request(e.method,n,i).then(t=>(0,r.decodeOperationOutput)(e,t??null))}),stream:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=(0,r.splitOperationInput)(e,t??{});throw notServed(e.method,n)}),get:e=>request(`GET`,e),post:(e,t)=>request(`POST`,e,t),patch:(e,t)=>request(`PATCH`,e,t),put:(e,t)=>request(`PUT`,e,t),delete:e=>request(`DELETE`,e),getText:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`GET`,e)}),postRaw:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`POST`,e)}),postMultipart:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`POST`,e)})};return{transport:d,get:d.get,post:d.post,definitionOf:e=>objectOf(e).definition,seed:(e,t)=>t.map(t=>insert(e,t)),records:e=>objectOf(e).records,failNextRequestWith(e,t={}){c={status:e,failure:t}}}}function createTestStandards(t){let n=t.bundles.flatMap(e=>e.objectBuilders),i=createInMemoryApi({builders:n}),flatten=(t,n)=>e.a(i.definitionOf(t),(0,r.decodeOperationOutput)(r.recordsOperations.get,JSON.parse(JSON.stringify(n))));return{db:e.t(i.transport,n),seed:(e,t)=>i.seed(e,t).map(t=>flatten(e,t)),records:e=>i.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>i.failNextRequestWith(e,t)}}exports.UnsupportedFilterOperatorError=UnsupportedFilterOperatorError,exports.createTestStandards=createTestStandards;