@standards/client 1.0.0-alpha.401 → 1.0.0-alpha.403

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.
@@ -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{_ as e,g as t,m as n,n as r,p as i}from"./http-transport-BxgXm4Oi.mjs";import{AggregateValidationError as a,DuplicateError as o,RecordQuery as s,SchemaErrorCode as c,ValidationError as l}from"@standards/schema";import{aiOperations as u,buildOperationPath as d,bundlesOperations as f,documentsOperations as p,filesOperations as m,recordAccessOperations as h,recordsOperations as g}from"@standards/schema/api";async function readInstalled(t,n){try{return await t.get(n)}catch(t){if(t instanceof e&&t.status===404)return null;throw t}}async function syncBundle(t,r,a={}){let o=await r.build(),s=d(f.sync,{name:o.name}),c=await readInstalled(t,s);if(c?.hash===o.hash&&c.label===o.label&&c.description===o.description&&c.uses.join(`
3
+ `)===o.uses.join(`
4
+ `))return{applied:!1,hash:o.hash};let l=a.resolutions&&a.resolutions.length>0?{...o,resolutions:a.resolutions}:o;try{return await t.put(s,l)}catch(t){throw t instanceof e&&t.status===409?new i(t.status,t.message,t.code):t instanceof e&&t.status===400?new n(t.status,t.message,t.code):t}}function assertTimeout(e){if(e!==void 0&&!(Number.isFinite(e)&&e>0))throw new l(`timeoutMs must be a positive number of milliseconds`,[{path:[`timeoutMs`],message:`Expected a positive, finite number`}])}function assertFileInput(e,t){if(!(e instanceof Blob))throw new l(`${t} must be a Blob or File`,[{path:[t],message:`Expected a Blob or File`}]);let n=e.name;if(typeof n!=`string`||n===``)throw new l(`${t} needs a filename`,[{path:[t,`name`],message:`Expected a non-empty filename`}]);if(e.type===``)throw new l(`${t} "${n}" needs a MIME type`,[{path:[t,`type`],message:`Expected a non-empty MIME type`}])}function reviveDocumentFile(e){return{...e,processedAt:e.processedAt===null?null:new Date(e.processedAt)}}function createDocumentsApi(e){async function attachToRecord(t){let{file:n}=t;assertFileInput(n,`file`),assertTimeout(t.timeoutMs);let r=d(g.attachDocument,{objectName:t.objectName,id:t.recordId}),i=new FormData;i.append(`files`,n,n.name),t.attributeName!==void 0&&i.append(`attributeName`,t.attributeName),t.documentId!==void 0&&i.append(`documentId`,t.documentId),t.title!==void 0&&i.append(`title`,t.title);let a=await e.postMultipart(r,i,{timeoutMs:t.timeoutMs});return{document:{id:a.document.id,title:a.document.title},file:reviveDocumentFile(a.file),action:a.action}}async function listFiles(t){return(await e.get(d(p.files,{id:t}))).map(reviveDocumentFile)}return{attachToRecord,listFiles}}function toUploadedFile(e){let t={id:e.id,name:e.name,mimeType:e.mimeType,size:e.size};return e.isPublic===!0&&typeof e.publicUrl==`string`?{...t,isPublic:!0,publicUrl:e.publicUrl}:{...t,isPublic:!1}}function createFilesApi(e){async function upload(t){assertFileInput(t.file,`file`),assertTimeout(t.timeoutMs);let[n]=await e.call(m.upload,{files:[t.file],public:t.public===!0?`true`:`false`,folderPath:t.folderPath},{timeoutMs:t.timeoutMs});return toUploadedFile(n)}async function getDownloadUrl(t){let{url:n}=await e.call(m.signedUrl,{id:t});return n}return{upload,getDownloadUrl}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const _=new Set([`from`,`files`,`documents`,`bundles`,`usage`]);function assertObjectKeys(e){let n=new Map;for(let r of e){if(r.includes(`--`)||r.endsWith(`-`))throw new t(`Object "${r}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let e=objectKeyOf(r);if(_.has(e))throw new t(`Object "${r}" maps to the client key "${e}", which is reserved. Rename the object.`);let i=n.get(e);if(i!==void 0&&i!==r)throw new t(`Objects "${i}" and "${r}" both map to the client key "${e}". Rename one of them.`);n.set(e,r)}}function assertObjectNames(e){let t=new Set;for(let n of e){if(t.has(n))throw new o(`object`,n);t.add(n)}assertObjectKeys(e)}const v=[`createdAt`,`updatedAt`,`deletedAt`];function dateAttributeNames(e){let t=new Set;for(let n of e?.attributes??[])n.type===`date`&&t.add(n.name);return t}function isRange(e){return typeof e==`object`&&!!e&&`start`in e&&`end`in e}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function flattenValues(e){let{values:t,...n}=e;return{...n,...isRecord(t)?t:{}}}function toDate(e){return typeof e==`string`?new Date(e):isRange(e)?{start:toDate(e.start),end:toDate(e.end)}:e}function reviveRecord(e,t){let n=dateAttributeNames(e),r=flattenValues(t);for(let e of v)e in r&&(r[e]=toDate(r[e]));for(let e of n)e in r&&(r[e]=toDate(r[e]));return r}function serializeInput(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t instanceof Date?t.toISOString():t]))}var y=class RecordsQueryImpl extends s{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 reviveRecord(this.definition,e)}async export(e,n={}){if(!this.transport.postRaw)throw new t(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:r,sorts:i}=this.body(),{ids:a,locale:o,filename:s}=n;return await this.transport.postRaw(d(g.export,{objectName:this.objectName}),{q:this.state.search??``,...r?{filters:r}:{},...i?{sorts:i}:{},columns:e,...a?{ids:a}:{},...o?{locale:o}:{},timezone:n.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...s?{filename:s}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new a(c.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.post(d(g.aggregate,{objectName:this.objectName}),t)}async fetchPage(){let e=this.state.search===void 0?`list`:`search`,t=await this.transport.post(d(g[e],{objectName:this.objectName}),this.body());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.get(d(g.get,{objectName:this.objectName,id:e}));return this.revive(t)}async create(e){let t=await this.transport.post(d(g.create,{objectName:this.objectName}),{data:serializeInput(e)});return this.revive(t)}async update(e,t){let n=await this.transport.put(d(g.update,{objectName:this.objectName,id:e}),serializeInput(t));return this.revive(n)}async delete(e){await this.transport.delete(d(g.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.post(d(g.bulkCreate,{objectName:this.objectName}),{records:e.map(serializeInput)});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.post(d(g.bulkUpdate,{objectName:this.objectName}),{updates:e.map(({id:e,data:t})=>({id:e,data:serializeInput(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.post(d(g.bulkDelete,{objectName:this.objectName}),{ids:e});t.deleted.push(...n.deleted),t.errors.push(...n.errors)}),t}async listAccess(e){return await this.transport.get(d(h.list,{objectName:this.objectName,recordId:e}))}async grantAccess(e,t,n){return await this.transport.put(d(h.grant,{objectName:this.objectName,recordId:e,actorId:t}),{role:n})}async revokeAccess(e,t){return await this.transport.delete(d(h.revoke,{objectName:this.objectName,recordId:e,actorId:t}))}async clearAccess(e){return await this.transport.delete(d(h.clear,{objectName:this.objectName,recordId:e}))}};const b=new WeakMap;function definitionOf(e){let t=b.get(e);if(t)return t;let n=e.build();return b.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new y(e,t,null);let n=definitionOf(t);return new y(e,n.name,n)}function createUsageApi(e){return{report:({from:t,to:n,scope:r=`me`})=>e.call(u.usage,{from:t,to:n,scope:r})}}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 t(`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 t(`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 n=readEnvironment(),r=e.baseUrl??n.baseUrl;if(r===void 0)throw new t(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let i=e.apiKey??n.apiKey;if(i===void 0)throw new t(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...e,baseUrl:r,apiKey:i}}function createStandards(e={}){let{bundles:t=[],...n}=e;return buildStandards(r(resolveConfig(n)),t.flatMap(e=>e.objectBuilders))}function buildStandards(e,t){let n={bundles:{sync:(t,n)=>syncBundle(e,t,n)},from:t=>createRecordsQuery(e,t),files:createFilesApi(e),documents:createDocumentsApi(e),usage:createUsageApi(e)},r=t.map(e=>definitionOf(e).name);return assertObjectNames(r),t.forEach((t,i)=>{n[objectKeyOf(r[i])]=createRecordsQuery(e,t)}),n}export{definitionOf as a,createFilesApi as c,createRecordsQuery as i,createDocumentsApi as l,createStandards as n,reviveRecord as o,createUsageApi as r,serializeInput as s,buildStandards as t,syncBundle as u};
@@ -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
+ const e=require("./http-transport-CAPVZuiv.js");let t=require("@standards/schema"),n=require("@standards/schema/api");async function readInstalled(t,n){try{return await t.get(n)}catch(t){if(t instanceof e._&&t.status===404)return null;throw t}}async function syncBundle(t,r,i={}){let a=await r.build(),o=(0,n.buildOperationPath)(n.bundlesOperations.sync,{name:a.name}),s=await readInstalled(t,o);if(s?.hash===a.hash&&s.label===a.label&&s.description===a.description&&s.uses.join(`
3
+ `)===a.uses.join(`
4
+ `))return{applied:!1,hash:a.hash};let c=i.resolutions&&i.resolutions.length>0?{...a,resolutions:i.resolutions}:a;try{return await t.put(o,c)}catch(t){throw t instanceof e._&&t.status===409?new e.p(t.status,t.message,t.code):t instanceof e._&&t.status===400?new e.m(t.status,t.message,t.code):t}}function assertTimeout(e){if(e!==void 0&&!(Number.isFinite(e)&&e>0))throw new t.ValidationError(`timeoutMs must be a positive number of milliseconds`,[{path:[`timeoutMs`],message:`Expected a positive, finite number`}])}function assertFileInput(e,n){if(!(e instanceof Blob))throw new t.ValidationError(`${n} must be a Blob or File`,[{path:[n],message:`Expected a Blob or File`}]);let r=e.name;if(typeof r!=`string`||r===``)throw new t.ValidationError(`${n} needs a filename`,[{path:[n,`name`],message:`Expected a non-empty filename`}]);if(e.type===``)throw new t.ValidationError(`${n} "${r}" needs a MIME type`,[{path:[n,`type`],message:`Expected a non-empty MIME type`}])}function reviveDocumentFile(e){return{...e,processedAt:e.processedAt===null?null:new Date(e.processedAt)}}function createDocumentsApi(e){async function attachToRecord(t){let{file:r}=t;assertFileInput(r,`file`),assertTimeout(t.timeoutMs);let i=(0,n.buildOperationPath)(n.recordsOperations.attachDocument,{objectName:t.objectName,id:t.recordId}),a=new FormData;a.append(`files`,r,r.name),t.attributeName!==void 0&&a.append(`attributeName`,t.attributeName),t.documentId!==void 0&&a.append(`documentId`,t.documentId),t.title!==void 0&&a.append(`title`,t.title);let o=await e.postMultipart(i,a,{timeoutMs:t.timeoutMs});return{document:{id:o.document.id,title:o.document.title},file:reviveDocumentFile(o.file),action:o.action}}async function listFiles(t){return(await e.get((0,n.buildOperationPath)(n.documentsOperations.files,{id:t}))).map(reviveDocumentFile)}return{attachToRecord,listFiles}}function toUploadedFile(e){let t={id:e.id,name:e.name,mimeType:e.mimeType,size:e.size};return e.isPublic===!0&&typeof e.publicUrl==`string`?{...t,isPublic:!0,publicUrl:e.publicUrl}:{...t,isPublic:!1}}function createFilesApi(e){async function upload(t){assertFileInput(t.file,`file`),assertTimeout(t.timeoutMs);let[r]=await e.call(n.filesOperations.upload,{files:[t.file],public:t.public===!0?`true`:`false`,folderPath:t.folderPath},{timeoutMs:t.timeoutMs});return toUploadedFile(r)}async function getDownloadUrl(t){let{url:r}=await e.call(n.filesOperations.signedUrl,{id:t});return r}return{upload,getDownloadUrl}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const r=new Set([`from`,`files`,`documents`,`bundles`,`usage`]);function assertObjectKeys(t){let n=new Map;for(let i of t){if(i.includes(`--`)||i.endsWith(`-`))throw new e.g(`Object "${i}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let t=objectKeyOf(i);if(r.has(t))throw new e.g(`Object "${i}" maps to the client key "${t}", which is reserved. Rename the object.`);let a=n.get(t);if(a!==void 0&&a!==i)throw new e.g(`Objects "${a}" and "${i}" both map to the client key "${t}". Rename one of them.`);n.set(t,i)}}function assertObjectNames(e){let n=new Set;for(let r of e){if(n.has(r))throw new t.DuplicateError(`object`,r);n.add(r)}assertObjectKeys(e)}const i=[`createdAt`,`updatedAt`,`deletedAt`];function dateAttributeNames(e){let t=new Set;for(let n of e?.attributes??[])n.type===`date`&&t.add(n.name);return t}function isRange(e){return typeof e==`object`&&!!e&&`start`in e&&`end`in e}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function flattenValues(e){let{values:t,...n}=e;return{...n,...isRecord(t)?t:{}}}function toDate(e){return typeof e==`string`?new Date(e):isRange(e)?{start:toDate(e.start),end:toDate(e.end)}:e}function reviveRecord(e,t){let n=dateAttributeNames(e),r=flattenValues(t);for(let e of i)e in r&&(r[e]=toDate(r[e]));for(let e of n)e in r&&(r[e]=toDate(r[e]));return r}function serializeInput(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t instanceof Date?t.toISOString():t]))}var a=class RecordsQueryImpl extends t.RecordQuery{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 reviveRecord(this.definition,e)}async export(t,r={}){if(!this.transport.postRaw)throw new e.g(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:i,sorts:a}=this.body(),{ids:o,locale:s,filename:c}=r;return await this.transport.postRaw((0,n.buildOperationPath)(n.recordsOperations.export,{objectName:this.objectName}),{q:this.state.search??``,...i?{filters:i}:{},...a?{sorts:a}:{},columns:t,...o?{ids:o}:{},...s?{locale:s}:{},timezone:r.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...c?{filename:c}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new t.AggregateValidationError(t.SchemaErrorCode.AGGREGATE_SEARCH_UNSUPPORTED,`An aggregate cannot be narrowed by a search; use filters instead`);let r={...e,query:this.toDefinition(),timezone:e.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone};return await this.transport.post((0,n.buildOperationPath)(n.recordsOperations.aggregate,{objectName:this.objectName}),r)}async fetchPage(){let e=this.state.search===void 0?`list`:`search`,t=await this.transport.post((0,n.buildOperationPath)(n.recordsOperations[e],{objectName:this.objectName}),this.body());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.get((0,n.buildOperationPath)(n.recordsOperations.get,{objectName:this.objectName,id:e}));return this.revive(t)}async create(e){let t=await this.transport.post((0,n.buildOperationPath)(n.recordsOperations.create,{objectName:this.objectName}),{data:serializeInput(e)});return this.revive(t)}async update(e,t){let r=await this.transport.put((0,n.buildOperationPath)(n.recordsOperations.update,{objectName:this.objectName,id:e}),serializeInput(t));return this.revive(r)}async delete(e){await this.transport.delete((0,n.buildOperationPath)(n.recordsOperations.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,r)=>{let i=await this.transport.post((0,n.buildOperationPath)(n.recordsOperations.bulkCreate,{objectName:this.objectName}),{records:e.map(serializeInput)});t.created.push(...i.created.map(e=>this.revive(e))),t.errors.push(...i.errors.map(e=>({...e,index:e.index+r})))}),t}async updateMany(e){let t={updated:[],errors:[]};return await this.inChunks(e,async e=>{let r=await this.transport.post((0,n.buildOperationPath)(n.recordsOperations.bulkUpdate,{objectName:this.objectName}),{updates:e.map(({id:e,data:t})=>({id:e,data:serializeInput(t)}))});t.updated.push(...r.updated.map(e=>this.revive(e))),t.errors.push(...r.errors)}),t}async deleteMany(e){let t={deleted:[],errors:[]};return await this.inChunks(e,async e=>{let r=await this.transport.post((0,n.buildOperationPath)(n.recordsOperations.bulkDelete,{objectName:this.objectName}),{ids:e});t.deleted.push(...r.deleted),t.errors.push(...r.errors)}),t}async listAccess(e){return await this.transport.get((0,n.buildOperationPath)(n.recordAccessOperations.list,{objectName:this.objectName,recordId:e}))}async grantAccess(e,t,r){return await this.transport.put((0,n.buildOperationPath)(n.recordAccessOperations.grant,{objectName:this.objectName,recordId:e,actorId:t}),{role:r})}async revokeAccess(e,t){return await this.transport.delete((0,n.buildOperationPath)(n.recordAccessOperations.revoke,{objectName:this.objectName,recordId:e,actorId:t}))}async clearAccess(e){return await this.transport.delete((0,n.buildOperationPath)(n.recordAccessOperations.clear,{objectName:this.objectName,recordId:e}))}};const o=new WeakMap;function definitionOf(e){let t=o.get(e);if(t)return t;let n=e.build();return o.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new a(e,t,null);let n=definitionOf(t);return new a(e,n.name,n)}function createUsageApi(e){return{report:({from:t,to:r,scope:i=`me`})=>e.call(n.aiOperations.usage,{from:t,to:r,scope:i})}}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(t){if(globalThis.window!==void 0){if(t.apiKey)throw new e.g(`createStandards received an apiKey in a browser context. API keys belong to server code only (Route Handlers, Server Components, scripts).`);if(t.baseUrl===void 0)throw new e.g(`createStandards needs an explicit baseUrl in a browser context: STANDARDS_API_URL and STANDARDS_API_KEY are never read from the environment there.`);return{...t,baseUrl:t.baseUrl,apiKey:``}}let n=readEnvironment(),r=t.baseUrl??n.baseUrl;if(r===void 0)throw new e.g(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let i=t.apiKey??n.apiKey;if(i===void 0)throw new e.g(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...t,baseUrl:r,apiKey:i}}function createStandards(t={}){let{bundles:n=[],...r}=t;return buildStandards(e.n(resolveConfig(r)),n.flatMap(e=>e.objectBuilders))}function buildStandards(e,t){let n={bundles:{sync:(t,n)=>syncBundle(e,t,n)},from:t=>createRecordsQuery(e,t),files:createFilesApi(e),documents:createDocumentsApi(e),usage:createUsageApi(e)},r=t.map(e=>definitionOf(e).name);return assertObjectNames(r),t.forEach((t,i)=>{n[objectKeyOf(r[i])]=createRecordsQuery(e,t)}),n}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return definitionOf}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return createFilesApi}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return createRecordsQuery}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return createDocumentsApi}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createStandards}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return reviveRecord}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return createUsageApi}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return serializeInput}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return buildStandards}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return syncBundle}});
@@ -1,6 +1,6 @@
1
1
 
2
2
  import { r as MultipartRequestOptions, s as TransportConfig, t as HttpTransport } from "./http-transport-C1u5UGkC.mjs";
3
- import { AggregateRecordsOptions, BundleBuilder, DocumentFile, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, ObjectDefinition, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult } from "@standards/schema";
3
+ import { AggregateRecordsOptions, BundleBuilder, DocumentFile, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, ObjectDefinition, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult, UsageReport, UsageScope } from "@standards/schema";
4
4
  //#region src/bundle-sync.d.ts
5
5
  /**
6
6
  * What a sync carries besides the bundle itself.
@@ -328,6 +328,23 @@ interface RecordsTransport {
328
328
  declare function createRecordsQuery<TBuilder extends ObjectBuilderLike>(transport: RecordsTransport, target: TBuilder): RecordsQuery<TBuilder>;
329
329
  declare function createRecordsQuery(transport: RecordsTransport, target: string): UntypedRecordsQuery;
330
330
  //#endregion
331
+ //#region src/usage/usage-api.d.ts
332
+ interface UsageReportInput {
333
+ /** First day of the window, `YYYY-MM-DD` (UTC, inclusive). */
334
+ from: string;
335
+ /** Last day of the window, `YYYY-MM-DD` (UTC, inclusive); at most 366 days after `from`. */
336
+ to: string;
337
+ /** `me` (the default): the caller's own usage. `workspace`: every member's, gated on `billing:read`. */
338
+ scope?: UsageScope;
339
+ }
340
+ interface UsageApi {
341
+ /** AI usage and cost over an inclusive UTC day window (`GET /ai/usage`). */
342
+ report(input: UsageReportInput): Promise<UsageReport>;
343
+ }
344
+ /** The one verb this module needs: the `ai.usage` operation. */
345
+ type UsageTransport = Pick<HttpTransport, "call">;
346
+ declare function createUsageApi(transport: UsageTransport): UsageApi;
347
+ //#endregion
331
348
  //#region src/create-standards.d.ts
332
349
  type NameOf<B> = B extends {
333
350
  _types: {
@@ -351,6 +368,8 @@ interface Standards {
351
368
  files: FilesApi;
352
369
  /** Attach uploads to a record's document attribute and list a document's files. */
353
370
  documents: DocumentsApi;
371
+ /** AI usage and cost of the caller or the whole workspace. */
372
+ usage: UsageApi;
354
373
  }
355
374
  /**
356
375
  * The options `createStandards` takes. Every field of `TransportConfig` is
@@ -363,4 +382,4 @@ declare function createStandards<const TBundles extends readonly AnyBundle[]>(co
363
382
  }): Standards & ObjectsOf<ObjectsOfBundles<TBundles>>;
364
383
  declare function createStandards(config?: StandardsConfig): Standards;
365
384
  //#endregion
366
- export { UploadPublicFileInput as A, SyncBundleOptions as B, CamelCase as C, PublicUploadedFile as D, PrivateUploadedFile as E, DocumentsApi as F, syncBundle as H, DocumentsTransport as I, createDocumentsApi as L, createFilesApi as M, AttachToRecordInput as N, UploadFileInput as O, AttachToRecordResult as P, FileInput as R, createRecordsQuery as S, FilesTransport as T, SyncTransport as V, UntypedBuilder as _, StandardsConfig as a, UpdateManyError as b, CreateManyResult as c, FetchResult as d, RecordInput as f, RecordsQuery as g, RecordsExportOptions as h, Standards as i, UploadedFile as j, UploadPrivateFileInput as k, DeleteManyError as l, RecordsAggregateOptions as m, ObjectsOf as n, createStandards as o, RecordUpdate as p, ObjectsOfBundles as r, CreateManyError as s, AnyBundle as t, DeleteManyResult as u, UntypedRecordsQuery as v, FilesApi as w, UpdateManyResult as x, UpdateManyEntry as y, UploadTimeoutOption as z };
385
+ 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 };
@@ -1,6 +1,6 @@
1
1
 
2
2
  import { r as MultipartRequestOptions, s as TransportConfig, t as HttpTransport } from "./http-transport-C1u5UGkC.js";
3
- import { AggregateRecordsOptions, BundleBuilder, DocumentFile, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, ObjectDefinition, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult } from "@standards/schema";
3
+ import { AggregateRecordsOptions, BundleBuilder, DocumentFile, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, ObjectDefinition, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult, UsageReport, UsageScope } from "@standards/schema";
4
4
  //#region src/bundle-sync.d.ts
5
5
  /**
6
6
  * What a sync carries besides the bundle itself.
@@ -328,6 +328,23 @@ interface RecordsTransport {
328
328
  declare function createRecordsQuery<TBuilder extends ObjectBuilderLike>(transport: RecordsTransport, target: TBuilder): RecordsQuery<TBuilder>;
329
329
  declare function createRecordsQuery(transport: RecordsTransport, target: string): UntypedRecordsQuery;
330
330
  //#endregion
331
+ //#region src/usage/usage-api.d.ts
332
+ interface UsageReportInput {
333
+ /** First day of the window, `YYYY-MM-DD` (UTC, inclusive). */
334
+ from: string;
335
+ /** Last day of the window, `YYYY-MM-DD` (UTC, inclusive); at most 366 days after `from`. */
336
+ to: string;
337
+ /** `me` (the default): the caller's own usage. `workspace`: every member's, gated on `billing:read`. */
338
+ scope?: UsageScope;
339
+ }
340
+ interface UsageApi {
341
+ /** AI usage and cost over an inclusive UTC day window (`GET /ai/usage`). */
342
+ report(input: UsageReportInput): Promise<UsageReport>;
343
+ }
344
+ /** The one verb this module needs: the `ai.usage` operation. */
345
+ type UsageTransport = Pick<HttpTransport, "call">;
346
+ declare function createUsageApi(transport: UsageTransport): UsageApi;
347
+ //#endregion
331
348
  //#region src/create-standards.d.ts
332
349
  type NameOf<B> = B extends {
333
350
  _types: {
@@ -351,6 +368,8 @@ interface Standards {
351
368
  files: FilesApi;
352
369
  /** Attach uploads to a record's document attribute and list a document's files. */
353
370
  documents: DocumentsApi;
371
+ /** AI usage and cost of the caller or the whole workspace. */
372
+ usage: UsageApi;
354
373
  }
355
374
  /**
356
375
  * The options `createStandards` takes. Every field of `TransportConfig` is
@@ -363,4 +382,4 @@ declare function createStandards<const TBundles extends readonly AnyBundle[]>(co
363
382
  }): Standards & ObjectsOf<ObjectsOfBundles<TBundles>>;
364
383
  declare function createStandards(config?: StandardsConfig): Standards;
365
384
  //#endregion
366
- export { UploadPublicFileInput as A, SyncBundleOptions as B, CamelCase as C, PublicUploadedFile as D, PrivateUploadedFile as E, DocumentsApi as F, syncBundle as H, DocumentsTransport as I, createDocumentsApi as L, createFilesApi as M, AttachToRecordInput as N, UploadFileInput as O, AttachToRecordResult as P, FileInput as R, createRecordsQuery as S, FilesTransport as T, SyncTransport as V, UntypedBuilder as _, StandardsConfig as a, UpdateManyError as b, CreateManyResult as c, FetchResult as d, RecordInput as f, RecordsQuery as g, RecordsExportOptions as h, Standards as i, UploadedFile as j, UploadPrivateFileInput as k, DeleteManyError as l, RecordsAggregateOptions as m, ObjectsOf as n, createStandards as o, RecordUpdate as p, ObjectsOfBundles as r, CreateManyError as s, AnyBundle as t, DeleteManyResult as u, UntypedRecordsQuery as v, FilesApi as w, UpdateManyResult as x, UpdateManyEntry as y, UploadTimeoutOption as z };
385
+ 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 };
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
 
2
2
  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-C1u5UGkC.mjs";
3
- import { A as UploadPublicFileInput, B as SyncBundleOptions, C as CamelCase, D as PublicUploadedFile, E as PrivateUploadedFile, F as DocumentsApi, H as syncBundle, I as DocumentsTransport, L as createDocumentsApi, M as createFilesApi, N as AttachToRecordInput, O as UploadFileInput, P as AttachToRecordResult, R as FileInput, S as createRecordsQuery, T as FilesTransport, V as SyncTransport, _ as UntypedBuilder, a as StandardsConfig, b as UpdateManyError, c as CreateManyResult, d as FetchResult, f as RecordInput, g as RecordsQuery, h as RecordsExportOptions, i as Standards, j as UploadedFile, k as UploadPrivateFileInput, l as DeleteManyError, m as RecordsAggregateOptions, n as ObjectsOf, o as createStandards, p as RecordUpdate, r as ObjectsOfBundles, s as CreateManyError, t as AnyBundle, u as DeleteManyResult, v as UntypedRecordsQuery, w as FilesApi, x as UpdateManyResult, y as UpdateManyEntry, z as UploadTimeoutOption } from "./create-standards-DoPZqxf5.mjs";
4
- import { 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, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, 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";
3
+ 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-ClcULv5H.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";
5
5
  import { encodePathSegment } from "@standards/schema/api";
6
6
  //#region src/records/revive.d.ts
7
7
  /**
@@ -19,4 +19,4 @@ export declare function reviveRecord<T extends Record<string, unknown>>(definiti
19
19
  */
20
20
  export declare function recordsPath(objectName: string, ...segments: string[]): string;
21
21
  //#endregion
22
- export { 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, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, assertBundleName, bundle, canonicalStringify, checkbox, content, createDocumentsApi, createFilesApi, 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 };
22
+ 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 };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
 
2
2
  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-C1u5UGkC.js";
3
- import { A as UploadPublicFileInput, B as SyncBundleOptions, C as CamelCase, D as PublicUploadedFile, E as PrivateUploadedFile, F as DocumentsApi, H as syncBundle, I as DocumentsTransport, L as createDocumentsApi, M as createFilesApi, N as AttachToRecordInput, O as UploadFileInput, P as AttachToRecordResult, R as FileInput, S as createRecordsQuery, T as FilesTransport, V as SyncTransport, _ as UntypedBuilder, a as StandardsConfig, b as UpdateManyError, c as CreateManyResult, d as FetchResult, f as RecordInput, g as RecordsQuery, h as RecordsExportOptions, i as Standards, j as UploadedFile, k as UploadPrivateFileInput, l as DeleteManyError, m as RecordsAggregateOptions, n as ObjectsOf, o as createStandards, p as RecordUpdate, r as ObjectsOfBundles, s as CreateManyError, t as AnyBundle, u as DeleteManyResult, v as UntypedRecordsQuery, w as FilesApi, x as UpdateManyResult, y as UpdateManyEntry, z as UploadTimeoutOption } from "./create-standards-Z58KKZjG.js";
3
+ 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-DN982-FF.js";
4
4
  import { encodePathSegment } from "@standards/schema/api";
5
- import { 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, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, 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
+ 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";
6
6
  //#region src/records/revive.d.ts
7
7
  /**
8
8
  * JSON delivers dates as ISO strings; the client knows the definition, so it
@@ -19,4 +19,4 @@ export declare function reviveRecord<T extends Record<string, unknown>>(definiti
19
19
  */
20
20
  export declare function recordsPath(objectName: string, ...segments: string[]): string;
21
21
  //#endregion
22
- export { 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, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, assertBundleName, bundle, canonicalStringify, checkbox, content, createDocumentsApi, createFilesApi, 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 };
22
+ 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 };
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("./http-transport-CAPVZuiv.js"),t=require("./create-standards-DbyGn7AW.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=e.p,exports.BundleValidationError=e.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=e.h,exports.StandardsConfigurationError=e.g,exports.StandardsRequestError=e._,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=t.c,exports.createFilesApi=t.s,exports.createRecordsQuery=t.r,exports.createStandards=t.n,exports.createTransport=e.n,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=e.a,Object.defineProperty(exports,"relation",{enumerable:!0,get:function(){return r.relation}}),exports.reviveRecord=t.a,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=t.l,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("./http-transport-CAPVZuiv.js"),t=require("./create-standards-CjO1pFmM.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=e.p,exports.BundleValidationError=e.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=e.h,exports.StandardsConfigurationError=e.g,exports.StandardsRequestError=e._,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=t.l,exports.createFilesApi=t.c,exports.createRecordsQuery=t.i,exports.createStandards=t.n,exports.createTransport=e.n,exports.createUsageApi=t.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=e.a,Object.defineProperty(exports,"relation",{enumerable:!0,get:function(){return r.relation}}),exports.reviveRecord=t.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=t.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}});
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{_ as e,a as t,g as n,h as r,m as i,n as a,p as o}from"./http-transport-BxgXm4Oi.mjs";import{a as s,c,l,n as u,r as d,s as f}from"./create-standards-CM5ebx80.mjs";import{BUNDLE_NAME_PATTERN as p,DuplicateError as m,ForbiddenError as h,NotFoundError as g,SchemaError as _,SchemaErrorCode as v,ValidationError as y,assertBundleName as b,bundle as x,canonicalStringify as S,checkbox as C,content as w,currency as T,currentActor as E,date as D,detailView as O,document as k,formula as A,group as j,listView as M,location as N,multiselect as P,now as F,number as I,object as L,phone as R,query as z,relation as B,richtext as V,rollup as H,select as U,status as W,text as G,today as K,user as q}from"@standards/schema";import{encodePathSegment as J}from"@standards/schema/api";export{p as BUNDLE_NAME_PATTERN,o as BundleConflictError,i as BundleValidationError,m as DuplicateError,h as ForbiddenError,g as NotFoundError,_ as SchemaError,v as SchemaErrorCode,r as StandardsAuthError,n as StandardsConfigurationError,e as StandardsRequestError,y as ValidationError,b as assertBundleName,x as bundle,S as canonicalStringify,C as checkbox,w as content,c as createDocumentsApi,f as createFilesApi,d as createRecordsQuery,u as createStandards,a as createTransport,T as currency,E as currentActor,D as date,O as detailView,k as document,J as encodePathSegment,A as formula,j as group,M as listView,N as location,P as multiselect,F as now,I as number,L as object,R as phone,z as query,t as recordsPath,B as relation,s as reviveRecord,V as richtext,H as rollup,U as select,W as status,l as syncBundle,G as text,K as today,q as user};
2
+ import{_ as e,a as t,g as n,h as r,m as i,n as a,p as o}from"./http-transport-BxgXm4Oi.mjs";import{c as s,i as c,l,n as u,o as d,r as f,u as p}from"./create-standards-CEL4N0C_.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,o as BundleConflictError,i as BundleValidationError,h as DuplicateError,g as ForbiddenError,_ as NotFoundError,v as SchemaError,y as SchemaErrorCode,r as StandardsAuthError,n as StandardsConfigurationError,e as StandardsRequestError,b as ValidationError,x as assertBundleName,S as bundle,C as canonicalStringify,w as checkbox,T as content,l as createDocumentsApi,s as createFilesApi,c as createRecordsQuery,u as createStandards,a as createTransport,f 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,t as recordsPath,V as relation,d as reviveRecord,H as richtext,U as rollup,W as select,G as status,p as syncBundle,K as text,q as today,J as user};
@@ -1,6 +1,6 @@
1
1
 
2
2
  import "./http-transport-C1u5UGkC.mjs";
3
- import { i as Standards, n as ObjectsOf, r as ObjectsOfBundles, t as AnyBundle } from "./create-standards-DoPZqxf5.mjs";
3
+ import { i as Standards, n as ObjectsOf, r as ObjectsOfBundles, t as AnyBundle } from "./create-standards-ClcULv5H.mjs";
4
4
  import { ExtractRecord, ExtractRecordInputStrict, FilterRule, ObjectBuilderLike, ObjectDefinition } from "@standards/schema";
5
5
  //#region src/testing/record-filters.d.ts
6
6
  /**
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
2
  import "./http-transport-C1u5UGkC.js";
3
- import { i as Standards, n as ObjectsOf, r as ObjectsOfBundles, t as AnyBundle } from "./create-standards-Z58KKZjG.js";
3
+ import { i as Standards, n as ObjectsOf, r as ObjectsOfBundles, t as AnyBundle } from "./create-standards-DN982-FF.js";
4
4
  import { ExtractRecord, ExtractRecordInputStrict, FilterRule, ObjectBuilderLike, ObjectDefinition } from "@standards/schema";
5
5
  //#region src/testing/record-filters.d.ts
6
6
  /**
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("./http-transport-CAPVZuiv.js"),t=require("./create-standards-DbyGn7AW.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=new Set([`id`,`createdAt`,`updatedAt`]),a=new Set([`createdAt`,`updatedAt`]),o=new Set([`number`,`currency`]),s=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=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,n){let r=n.attributes.find(e=>e.name===t.attribute)?.type,i=attributeValue(e,t.attribute),s=r!==void 0&&o.has(r),c=textOf(t.value)?.toLowerCase(),l=textOf(i)?.toLowerCase()??null;if((r===`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,i,t.value,a.has(t.attribute));switch(t.operator){case`is`:return r===`checkbox`||r===void 0&&typeof t.value==`boolean`?t.value===!0?i===!0:i!==!0:textOf(i)!==null&&textOf(i)===textOf(t.value);case`is_not`:return textOf(i)===null||textOf(i)!==textOf(t.value);case`contains`:return Array.isArray(i)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>i.map(String).includes(e)):l!==null&&c!==void 0&&l.includes(c);case`not_contains`:return i==null||!matchesRule(e,{...t,operator:`contains`},n);case`starts_with`:return l!==null&&c!==void 0&&l.startsWith(c);case`ends_with`:return l!==null&&c!==void 0&&l.endsWith(c);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(i,t.value,s);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(i);case`is_not_empty`:return!isEmptyValue(i);case`any_of`:{let e=members(t.value);return e===null||e.length===0||i==null?!1:Array.isArray(i)?i.some(t=>e.includes(String(t))):e.includes(textOf(i)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||i==null?!0:Array.isArray(i)?!i.some(t=>e.includes(String(t))):!e.includes(textOf(i)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const l=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.getSystemAttributeList)()]}}function withoutSystemKeys(e){let t={...e};for(let e of f)delete t[e];return t}function boundOf(t,n,r){if(t==null)return r;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw new e._(400,`${n} must be a non-negative integer`);return t}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function errorFor(t,n,r){return t===401||t===403?new e.h(t,n,r):new e._(t,n,r)}function asTheServerValidates(t){try{t()}catch(t){throw t instanceof n.ValidationError?new e._(400,t.message,t.code):t}}function notServed(t,n){return new e._(501,`The in-memory test workspace does not serve ${t} ${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=new Map;for(let e of i.builders){let n=t.i(e);a.set(n.name,n)}let o=new Map([...a.keys()].map(e=>[e,[]])),s=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(t){let n=a.get(t),r=o.get(t);if(!(n&&r))throw new e._(404,`Object "${t}" not found. Make sure the object exists and you have access to it.`);return{definition:n,records:r}}function insert(e,n){let{records:r}=objectOf(e),{id:i,createdAt:a,updatedAt:o,...c}=n,l=now(),u={id:i??newId(),values:wire(t.o(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(t,n){let r=objectOf(t).records.find(e=>e.id===n);if(!r)throw new e._(404,readNotFound(n),u);return r}function requireWritable(t,n){if(!objectOf(t).records.some(e=>e.id===n))throw new e._(404,writeNotFound(n),u)}function update(t,n,r){let i=objectOf(t).records.find(e=>e.id===n);if(!i)throw new e._(404,writeNotFound(n),u);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(t,n){let{records:r}=objectOf(t),i=r.findIndex(e=>e.id===n);if(i===-1)throw new e._(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(t,r,i){let a=i.records??i.updates??i.ids;if(!Array.isArray(a)||a.length>100)throw new e._(400,`A bulk request carries at most 100 items.`);let o=withSystemAttributes(objectOf(t).definition);if(r===`bulk-create`){let r=[],i=[];for(let[s,c]of a.entries()){if(!isObject(c)){i.push({index:s,error:`Record data must be an object`});continue}try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(insert(t,withoutSystemKeys(c)))}catch(t){if(!(t instanceof e._))throw t;i.push({index:s,error:t.message})}}return{created:r,errors:i}}if(r===`bulk-update`){let r=[],i=[];for(let{id:s,data:c}of a)try{if(!isObject(c))throw new e._(400,`Update data must be an object`,d);requireWritable(t,s),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(update(t,s,c))}catch(t){if(!(t instanceof e._))throw t;i.push({id:s,error:t.message,code:t.code??d})}return{updated:r,errors:i}}let s=[],c=[];for(let e of a)try{remove(t,e),s.push(e)}catch{c.push({id:e,error:writeNotFound(e),code:u})}return{deleted:s,errors:c}}function route(t,r,i){let[a,o,s,...c]=r.replace(/^\/+/,``).split(`/`);if(a!==`records`||o===void 0||c.length>0)throw notServed(t,r);let l=decodeURIComponent(o),u=s===void 0?void 0:decodeURIComponent(s),d=isObject(i)?i:{};if(t===`POST`&&u===void 0){let e=isObject(d.data)?d.data:{};return asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(t===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(t===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(t,r);if(t===`GET`)return find(l,u);if(t===`PUT`||t===`PATCH`){if(Object.keys(d).length===0)throw new e._(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(t===`DELETE`)return remove(l,u),null;throw notServed(t,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(e){let n=e.bundles.flatMap(e=>e.objectBuilders),r=createInMemoryApi({builders:n}),flatten=(e,n)=>t.a(r.definitionOf(e),JSON.parse(JSON.stringify(n)));return{db:t.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("./http-transport-CAPVZuiv.js"),t=require("./create-standards-CjO1pFmM.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=new Set([`id`,`createdAt`,`updatedAt`]),a=new Set([`createdAt`,`updatedAt`]),o=new Set([`number`,`currency`]),s=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=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,n){let r=n.attributes.find(e=>e.name===t.attribute)?.type,i=attributeValue(e,t.attribute),s=r!==void 0&&o.has(r),c=textOf(t.value)?.toLowerCase(),l=textOf(i)?.toLowerCase()??null;if((r===`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,i,t.value,a.has(t.attribute));switch(t.operator){case`is`:return r===`checkbox`||r===void 0&&typeof t.value==`boolean`?t.value===!0?i===!0:i!==!0:textOf(i)!==null&&textOf(i)===textOf(t.value);case`is_not`:return textOf(i)===null||textOf(i)!==textOf(t.value);case`contains`:return Array.isArray(i)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>i.map(String).includes(e)):l!==null&&c!==void 0&&l.includes(c);case`not_contains`:return i==null||!matchesRule(e,{...t,operator:`contains`},n);case`starts_with`:return l!==null&&c!==void 0&&l.startsWith(c);case`ends_with`:return l!==null&&c!==void 0&&l.endsWith(c);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(i,t.value,s);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(i);case`is_not_empty`:return!isEmptyValue(i);case`any_of`:{let e=members(t.value);return e===null||e.length===0||i==null?!1:Array.isArray(i)?i.some(t=>e.includes(String(t))):e.includes(textOf(i)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||i==null?!0:Array.isArray(i)?!i.some(t=>e.includes(String(t))):!e.includes(textOf(i)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const l=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.getSystemAttributeList)()]}}function withoutSystemKeys(e){let t={...e};for(let e of f)delete t[e];return t}function boundOf(t,n,r){if(t==null)return r;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw new e._(400,`${n} must be a non-negative integer`);return t}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function errorFor(t,n,r){return t===401||t===403?new e.h(t,n,r):new e._(t,n,r)}function asTheServerValidates(t){try{t()}catch(t){throw t instanceof n.ValidationError?new e._(400,t.message,t.code):t}}function notServed(t,n){return new e._(501,`The in-memory test workspace does not serve ${t} ${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=new Map;for(let e of i.builders){let n=t.a(e);a.set(n.name,n)}let o=new Map([...a.keys()].map(e=>[e,[]])),s=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(t){let n=a.get(t),r=o.get(t);if(!(n&&r))throw new e._(404,`Object "${t}" not found. Make sure the object exists and you have access to it.`);return{definition:n,records:r}}function insert(e,n){let{records:r}=objectOf(e),{id:i,createdAt:a,updatedAt:o,...c}=n,l=now(),u={id:i??newId(),values:wire(t.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(t,n){let r=objectOf(t).records.find(e=>e.id===n);if(!r)throw new e._(404,readNotFound(n),u);return r}function requireWritable(t,n){if(!objectOf(t).records.some(e=>e.id===n))throw new e._(404,writeNotFound(n),u)}function update(t,n,r){let i=objectOf(t).records.find(e=>e.id===n);if(!i)throw new e._(404,writeNotFound(n),u);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(t,n){let{records:r}=objectOf(t),i=r.findIndex(e=>e.id===n);if(i===-1)throw new e._(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(t,r,i){let a=i.records??i.updates??i.ids;if(!Array.isArray(a)||a.length>100)throw new e._(400,`A bulk request carries at most 100 items.`);let o=withSystemAttributes(objectOf(t).definition);if(r===`bulk-create`){let r=[],i=[];for(let[s,c]of a.entries()){if(!isObject(c)){i.push({index:s,error:`Record data must be an object`});continue}try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(insert(t,withoutSystemKeys(c)))}catch(t){if(!(t instanceof e._))throw t;i.push({index:s,error:t.message})}}return{created:r,errors:i}}if(r===`bulk-update`){let r=[],i=[];for(let{id:s,data:c}of a)try{if(!isObject(c))throw new e._(400,`Update data must be an object`,d);requireWritable(t,s),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(update(t,s,c))}catch(t){if(!(t instanceof e._))throw t;i.push({id:s,error:t.message,code:t.code??d})}return{updated:r,errors:i}}let s=[],c=[];for(let e of a)try{remove(t,e),s.push(e)}catch{c.push({id:e,error:writeNotFound(e),code:u})}return{deleted:s,errors:c}}function route(t,r,i){let[a,o,s,...c]=r.replace(/^\/+/,``).split(`/`);if(a!==`records`||o===void 0||c.length>0)throw notServed(t,r);let l=decodeURIComponent(o),u=s===void 0?void 0:decodeURIComponent(s),d=isObject(i)?i:{};if(t===`POST`&&u===void 0){let e=isObject(d.data)?d.data:{};return asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(t===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(t===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(t,r);if(t===`GET`)return find(l,u);if(t===`PUT`||t===`PATCH`){if(Object.keys(d).length===0)throw new e._(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(t===`DELETE`)return remove(l,u),null;throw notServed(t,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(e){let n=e.bundles.flatMap(e=>e.objectBuilders),r=createInMemoryApi({builders:n}),flatten=(e,n)=>t.o(r.definitionOf(e),JSON.parse(JSON.stringify(n)));return{db:t.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;
package/dist/testing.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{_ as e,h as t}from"./http-transport-BxgXm4Oi.mjs";import{a as n,i as r,o as i,t as a}from"./create-standards-CM5ebx80.mjs";import{ValidationError as o,getSystemAttributeList as s,rejectUnknownAttributesOrThrow as c,validateQualifiedRule as l}from"@standards/schema";import{splitOperationInput as u}from"@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 d=new Set([`id`,`createdAt`,`updatedAt`]),f=new Set([`createdAt`,`updatedAt`]),p=new Set([`number`,`currency`]),m=new Set([`select`,`status`]),h=/^\d{4}-\d{2}-\d{2}/;function attributeValue(e,t){if(d.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||!h.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=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,n){let r=n.attributes.find(e=>e.name===t.attribute)?.type,i=attributeValue(e,t.attribute),a=r!==void 0&&p.has(r),o=textOf(t.value)?.toLowerCase(),s=textOf(i)?.toLowerCase()??null;if((r===`date`||f.has(t.attribute))&&[`is`,`is_not`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`].includes(t.operator))return matchesDay(t.operator,i,t.value,f.has(t.attribute));switch(t.operator){case`is`:return r===`checkbox`||r===void 0&&typeof t.value==`boolean`?t.value===!0?i===!0:i!==!0:textOf(i)!==null&&textOf(i)===textOf(t.value);case`is_not`:return textOf(i)===null||textOf(i)!==textOf(t.value);case`contains`:return Array.isArray(i)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>i.map(String).includes(e)):s!==null&&o!==void 0&&s.includes(o);case`not_contains`:return i==null||!matchesRule(e,{...t,operator:`contains`},n);case`starts_with`:return s!==null&&o!==void 0&&s.startsWith(o);case`ends_with`:return s!==null&&o!==void 0&&s.endsWith(o);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(i,t.value,a);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(i);case`is_not_empty`:return!isEmptyValue(i);case`any_of`:{let e=members(t.value);return e===null||e.length===0||i==null?!1:Array.isArray(i)?i.some(t=>e.includes(String(t))):e.includes(textOf(i)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||i==null?!0:Array.isArray(i)?!i.some(t=>e.includes(String(t))):!e.includes(textOf(i)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const g=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(!g.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&&m.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),o=sortKey(r,i.attribute,t),s=isOptionKey(a)?a.value:a,c=isOptionKey(o)?o.value:o,l=textOf(s)===null,u=textOf(c)===null;if(l||u){if(l&&u)continue;return l?1:-1}if(isOptionKey(a)&&isOptionKey(o)){let e=compareOptionKeys(a,o,i.direction);if(e!==0)return e;continue}let d=compare(a,o,n!==void 0&&p.has(n))??0;if(d!==0)return i.direction===`desc`?-d:d}return 0}}const _=`SCHEMA_RECORD_NOT_FOUND`,v=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,y=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...s()]}}function withoutSystemKeys(e){let t={...e};for(let e of y)delete t[e];return t}function boundOf(t,n,r){if(t==null)return r;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw new e(400,`${n} must be a non-negative integer`);return t}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function errorFor(n,r,i){return n===401||n===403?new t(n,r,i):new e(n,r,i)}function asTheServerValidates(t){try{t()}catch(t){throw t instanceof o?new e(400,t.message,t.code):t}}function notServed(t,n){return new e(501,`The in-memory test workspace does not serve ${t} ${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(t){let n=new Map;for(let e of t.builders){let t=r(e);n.set(t.name,t)}let a=new Map([...n.keys()].map(e=>[e,[]])),o=new Set,s=null,d=0,f=1;function now(){return d=Math.max(Date.now(),d+1),new Date(d).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(f++).toString(16).padStart(12,`0`)}`;while(o.has(e));return e}function objectOf(t){let r=n.get(t),i=a.get(t);if(!(r&&i))throw new e(404,`Object "${t}" not found. Make sure the object exists and you have access to it.`);return{definition:r,records:i}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:a,updatedAt:s,...c}=t,l=now(),u={id:r??newId(),values:wire(i(c)),createdAt:isoOf(a,l),updatedAt:isoOf(s,isoOf(a,l)),visibility:`workspace`,ownedBy:null,metadata:{}};return n.push(u),o.add(u.id),u}function find(t,n){let r=objectOf(t).records.find(e=>e.id===n);if(!r)throw new e(404,readNotFound(n),_);return r}function requireWritable(t,n){if(!objectOf(t).records.some(e=>e.id===n))throw new e(404,writeNotFound(n),_)}function update(t,n,r){let i=objectOf(t).records.find(e=>e.id===n);if(!i)throw new e(404,writeNotFound(n),_);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(t,n){let{records:r}=objectOf(t),i=r.findIndex(e=>e.id===n);if(i===-1)throw new e(404,writeNotFound(n),_);r.splice(i,1)}function list(e,t,n){let{definition:r,records:i}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>l(structuredClone(e),{attributes:r.attributes}));assertServedOperators(t.filters,r);let a=Math.min(boundOf(t.limit,`limit`,20),1e3),o=boundOf(t.offset,`offset`,0);if(a===0)return{data:[],page:{hasMore:!1,total:null,countMode:`none`}};let s=n?t.q:void 0,c=i.filter(e=>matchesFilters(e,t.filters,r)).filter(e=>s===void 0||matchesSearch(e,s)).sort(compareRecords(t.sorts,r)),u=c.slice(o,o+a);return{data:u,page:{hasMore:o+u.length<c.length,total:null,countMode:`none`}}}function bulk(t,n,r){let i=r.records??r.updates??r.ids;if(!Array.isArray(i)||i.length>100)throw new e(400,`A bulk request carries at most 100 items.`);let a=withSystemAttributes(objectOf(t).definition);if(n===`bulk-create`){let n=[],r=[];for(let[o,s]of i.entries()){if(!isObject(s)){r.push({index:o,error:`Record data must be an object`});continue}try{asTheServerValidates(()=>c(a,s)),n.push(insert(t,withoutSystemKeys(s)))}catch(t){if(!(t instanceof e))throw t;r.push({index:o,error:t.message})}}return{created:n,errors:r}}if(n===`bulk-update`){let n=[],r=[];for(let{id:o,data:s}of i)try{if(!isObject(s))throw new e(400,`Update data must be an object`,v);requireWritable(t,o),asTheServerValidates(()=>c(a,s)),n.push(update(t,o,s))}catch(t){if(!(t instanceof e))throw t;r.push({id:o,error:t.message,code:t.code??v})}return{updated:n,errors:r}}let o=[],s=[];for(let e of i)try{remove(t,e),o.push(e)}catch{s.push({id:e,error:writeNotFound(e),code:_})}return{deleted:o,errors:s}}function route(t,n,r){let[i,a,o,...s]=n.replace(/^\/+/,``).split(`/`);if(i!==`records`||a===void 0||s.length>0)throw notServed(t,n);let l=decodeURIComponent(a),u=o===void 0?void 0:decodeURIComponent(o),d=isObject(r)?r:{};if(t===`POST`&&u===void 0){let e=isObject(d.data)?d.data:{};return asTheServerValidates(()=>c(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(t===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(t===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(t,n);if(t===`GET`)return find(l,u);if(t===`PUT`||t===`PATCH`){if(Object.keys(d).length===0)throw new e(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>c(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(t===`DELETE`)return remove(l,u),null;throw notServed(t,n)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(s){let{status:e,failure:t}=s;throw s=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let p={call:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=u(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={}){s={status:e,failure:t}}}}function createTestStandards(e){let t=e.bundles.flatMap(e=>e.objectBuilders),r=createInMemoryApi({builders:t}),flatten=(e,t)=>n(r.definitionOf(e),JSON.parse(JSON.stringify(t)));return{db:a(r.transport,t),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)}}export{UnsupportedFilterOperatorError,createTestStandards};
2
+ import{_ as e,h as t}from"./http-transport-BxgXm4Oi.mjs";import{a as n,o as r,s as i,t as a}from"./create-standards-CEL4N0C_.mjs";import{ValidationError as o,getSystemAttributeList as s,rejectUnknownAttributesOrThrow as c,validateQualifiedRule as l}from"@standards/schema";import{splitOperationInput as u}from"@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 d=new Set([`id`,`createdAt`,`updatedAt`]),f=new Set([`createdAt`,`updatedAt`]),p=new Set([`number`,`currency`]),m=new Set([`select`,`status`]),h=/^\d{4}-\d{2}-\d{2}/;function attributeValue(e,t){if(d.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||!h.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=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,n){let r=n.attributes.find(e=>e.name===t.attribute)?.type,i=attributeValue(e,t.attribute),a=r!==void 0&&p.has(r),o=textOf(t.value)?.toLowerCase(),s=textOf(i)?.toLowerCase()??null;if((r===`date`||f.has(t.attribute))&&[`is`,`is_not`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`].includes(t.operator))return matchesDay(t.operator,i,t.value,f.has(t.attribute));switch(t.operator){case`is`:return r===`checkbox`||r===void 0&&typeof t.value==`boolean`?t.value===!0?i===!0:i!==!0:textOf(i)!==null&&textOf(i)===textOf(t.value);case`is_not`:return textOf(i)===null||textOf(i)!==textOf(t.value);case`contains`:return Array.isArray(i)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>i.map(String).includes(e)):s!==null&&o!==void 0&&s.includes(o);case`not_contains`:return i==null||!matchesRule(e,{...t,operator:`contains`},n);case`starts_with`:return s!==null&&o!==void 0&&s.startsWith(o);case`ends_with`:return s!==null&&o!==void 0&&s.endsWith(o);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(i,t.value,a);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(i);case`is_not_empty`:return!isEmptyValue(i);case`any_of`:{let e=members(t.value);return e===null||e.length===0||i==null?!1:Array.isArray(i)?i.some(t=>e.includes(String(t))):e.includes(textOf(i)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||i==null?!0:Array.isArray(i)?!i.some(t=>e.includes(String(t))):!e.includes(textOf(i)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const g=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(!g.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&&m.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),o=sortKey(r,i.attribute,t),s=isOptionKey(a)?a.value:a,c=isOptionKey(o)?o.value:o,l=textOf(s)===null,u=textOf(c)===null;if(l||u){if(l&&u)continue;return l?1:-1}if(isOptionKey(a)&&isOptionKey(o)){let e=compareOptionKeys(a,o,i.direction);if(e!==0)return e;continue}let d=compare(a,o,n!==void 0&&p.has(n))??0;if(d!==0)return i.direction===`desc`?-d:d}return 0}}const _=`SCHEMA_RECORD_NOT_FOUND`,v=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,y=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...s()]}}function withoutSystemKeys(e){let t={...e};for(let e of y)delete t[e];return t}function boundOf(t,n,r){if(t==null)return r;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw new e(400,`${n} must be a non-negative integer`);return t}function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function errorFor(n,r,i){return n===401||n===403?new t(n,r,i):new e(n,r,i)}function asTheServerValidates(t){try{t()}catch(t){throw t instanceof o?new e(400,t.message,t.code):t}}function notServed(t,n){return new e(501,`The in-memory test workspace does not serve ${t} ${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(t){let r=new Map;for(let e of t.builders){let t=n(e);r.set(t.name,t)}let a=new Map([...r.keys()].map(e=>[e,[]])),o=new Set,s=null,d=0,f=1;function now(){return d=Math.max(Date.now(),d+1),new Date(d).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(f++).toString(16).padStart(12,`0`)}`;while(o.has(e));return e}function objectOf(t){let n=r.get(t),i=a.get(t);if(!(n&&i))throw new e(404,`Object "${t}" not found. Make sure the object exists and you have access to it.`);return{definition:n,records:i}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:a,updatedAt:s,...c}=t,l=now(),u={id:r??newId(),values:wire(i(c)),createdAt:isoOf(a,l),updatedAt:isoOf(s,isoOf(a,l)),visibility:`workspace`,ownedBy:null,metadata:{}};return n.push(u),o.add(u.id),u}function find(t,n){let r=objectOf(t).records.find(e=>e.id===n);if(!r)throw new e(404,readNotFound(n),_);return r}function requireWritable(t,n){if(!objectOf(t).records.some(e=>e.id===n))throw new e(404,writeNotFound(n),_)}function update(t,n,r){let i=objectOf(t).records.find(e=>e.id===n);if(!i)throw new e(404,writeNotFound(n),_);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(t,n){let{records:r}=objectOf(t),i=r.findIndex(e=>e.id===n);if(i===-1)throw new e(404,writeNotFound(n),_);r.splice(i,1)}function list(e,t,n){let{definition:r,records:i}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>l(structuredClone(e),{attributes:r.attributes}));assertServedOperators(t.filters,r);let a=Math.min(boundOf(t.limit,`limit`,20),1e3),o=boundOf(t.offset,`offset`,0);if(a===0)return{data:[],page:{hasMore:!1,total:null,countMode:`none`}};let s=n?t.q:void 0,c=i.filter(e=>matchesFilters(e,t.filters,r)).filter(e=>s===void 0||matchesSearch(e,s)).sort(compareRecords(t.sorts,r)),u=c.slice(o,o+a);return{data:u,page:{hasMore:o+u.length<c.length,total:null,countMode:`none`}}}function bulk(t,n,r){let i=r.records??r.updates??r.ids;if(!Array.isArray(i)||i.length>100)throw new e(400,`A bulk request carries at most 100 items.`);let a=withSystemAttributes(objectOf(t).definition);if(n===`bulk-create`){let n=[],r=[];for(let[o,s]of i.entries()){if(!isObject(s)){r.push({index:o,error:`Record data must be an object`});continue}try{asTheServerValidates(()=>c(a,s)),n.push(insert(t,withoutSystemKeys(s)))}catch(t){if(!(t instanceof e))throw t;r.push({index:o,error:t.message})}}return{created:n,errors:r}}if(n===`bulk-update`){let n=[],r=[];for(let{id:o,data:s}of i)try{if(!isObject(s))throw new e(400,`Update data must be an object`,v);requireWritable(t,o),asTheServerValidates(()=>c(a,s)),n.push(update(t,o,s))}catch(t){if(!(t instanceof e))throw t;r.push({id:o,error:t.message,code:t.code??v})}return{updated:n,errors:r}}let o=[],s=[];for(let e of i)try{remove(t,e),o.push(e)}catch{s.push({id:e,error:writeNotFound(e),code:_})}return{deleted:o,errors:s}}function route(t,n,r){let[i,a,o,...s]=n.replace(/^\/+/,``).split(`/`);if(i!==`records`||a===void 0||s.length>0)throw notServed(t,n);let l=decodeURIComponent(a),u=o===void 0?void 0:decodeURIComponent(o),d=isObject(r)?r:{};if(t===`POST`&&u===void 0){let e=isObject(d.data)?d.data:{};return asTheServerValidates(()=>c(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(t===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(t===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(t,n);if(t===`GET`)return find(l,u);if(t===`PUT`||t===`PATCH`){if(Object.keys(d).length===0)throw new e(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>c(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(t===`DELETE`)return remove(l,u),null;throw notServed(t,n)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(s){let{status:e,failure:t}=s;throw s=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let p={call:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=u(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={}){s={status:e,failure:t}}}}function createTestStandards(e){let t=e.bundles.flatMap(e=>e.objectBuilders),n=createInMemoryApi({builders:t}),flatten=(e,t)=>r(n.definitionOf(e),JSON.parse(JSON.stringify(t)));return{db:a(n.transport,t),seed:(e,t)=>n.seed(e,t).map(t=>flatten(e,t)),records:e=>n.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>n.failNextRequestWith(e,t)}}export{UnsupportedFilterOperatorError,createTestStandards};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@standards/client",
3
- "version": "1.0.0-alpha.401",
3
+ "version": "1.0.0-alpha.403",
4
4
  "description": "Public TypeScript client for Standards: declare schema sources with the fluent builders, sync them to a hosted tenant, and operate typed records over the REST API.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -47,7 +47,7 @@
47
47
  "node": ">=22"
48
48
  },
49
49
  "dependencies": {
50
- "@standards/schema": "1.0.0-alpha.401"
50
+ "@standards/schema": "1.0.0-alpha.403"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/node": "^25.6.0",
@@ -1,4 +0,0 @@
1
- /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
- import{_ as e,g as t,m as n,n as r,p as i}from"./http-transport-BxgXm4Oi.mjs";import{AggregateValidationError as a,DuplicateError as o,RecordQuery as s,SchemaErrorCode as c,ValidationError as l}from"@standards/schema";import{buildOperationPath as u,bundlesOperations as d,documentsOperations as f,filesOperations as p,recordAccessOperations as m,recordsOperations as h}from"@standards/schema/api";async function readInstalled(t,n){try{return await t.get(n)}catch(t){if(t instanceof e&&t.status===404)return null;throw t}}async function syncBundle(t,r,a={}){let o=await r.build(),s=u(d.sync,{name:o.name}),c=await readInstalled(t,s);if(c?.hash===o.hash&&c.label===o.label&&c.description===o.description&&c.uses.join(`
3
- `)===o.uses.join(`
4
- `))return{applied:!1,hash:o.hash};let l=a.resolutions&&a.resolutions.length>0?{...o,resolutions:a.resolutions}:o;try{return await t.put(s,l)}catch(t){throw t instanceof e&&t.status===409?new i(t.status,t.message,t.code):t instanceof e&&t.status===400?new n(t.status,t.message,t.code):t}}function assertTimeout(e){if(e!==void 0&&!(Number.isFinite(e)&&e>0))throw new l(`timeoutMs must be a positive number of milliseconds`,[{path:[`timeoutMs`],message:`Expected a positive, finite number`}])}function assertFileInput(e,t){if(!(e instanceof Blob))throw new l(`${t} must be a Blob or File`,[{path:[t],message:`Expected a Blob or File`}]);let n=e.name;if(typeof n!=`string`||n===``)throw new l(`${t} needs a filename`,[{path:[t,`name`],message:`Expected a non-empty filename`}]);if(e.type===``)throw new l(`${t} "${n}" needs a MIME type`,[{path:[t,`type`],message:`Expected a non-empty MIME type`}])}function reviveDocumentFile(e){return{...e,processedAt:e.processedAt===null?null:new Date(e.processedAt)}}function createDocumentsApi(e){async function attachToRecord(t){let{file:n}=t;assertFileInput(n,`file`),assertTimeout(t.timeoutMs);let r=u(h.attachDocument,{objectName:t.objectName,id:t.recordId}),i=new FormData;i.append(`files`,n,n.name),t.attributeName!==void 0&&i.append(`attributeName`,t.attributeName),t.documentId!==void 0&&i.append(`documentId`,t.documentId),t.title!==void 0&&i.append(`title`,t.title);let a=await e.postMultipart(r,i,{timeoutMs:t.timeoutMs});return{document:{id:a.document.id,title:a.document.title},file:reviveDocumentFile(a.file),action:a.action}}async function listFiles(t){return(await e.get(u(f.files,{id:t}))).map(reviveDocumentFile)}return{attachToRecord,listFiles}}function toUploadedFile(e){let t={id:e.id,name:e.name,mimeType:e.mimeType,size:e.size};return e.isPublic===!0&&typeof e.publicUrl==`string`?{...t,isPublic:!0,publicUrl:e.publicUrl}:{...t,isPublic:!1}}function createFilesApi(e){async function upload(t){assertFileInput(t.file,`file`),assertTimeout(t.timeoutMs);let[n]=await e.call(p.upload,{files:[t.file],public:t.public===!0?`true`:`false`,folderPath:t.folderPath},{timeoutMs:t.timeoutMs});return toUploadedFile(n)}async function getDownloadUrl(t){let{url:n}=await e.call(p.signedUrl,{id:t});return n}return{upload,getDownloadUrl}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const g=new Set([`from`,`files`,`documents`,`bundles`]);function assertObjectKeys(e){let n=new Map;for(let r of e){if(r.includes(`--`)||r.endsWith(`-`))throw new t(`Object "${r}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let e=objectKeyOf(r);if(g.has(e))throw new t(`Object "${r}" maps to the client key "${e}", which is reserved. Rename the object.`);let i=n.get(e);if(i!==void 0&&i!==r)throw new t(`Objects "${i}" and "${r}" both map to the client key "${e}". Rename one of them.`);n.set(e,r)}}function assertObjectNames(e){let t=new Set;for(let n of e){if(t.has(n))throw new o(`object`,n);t.add(n)}assertObjectKeys(e)}const _=[`createdAt`,`updatedAt`,`deletedAt`];function dateAttributeNames(e){let t=new Set;for(let n of e?.attributes??[])n.type===`date`&&t.add(n.name);return t}function isRange(e){return typeof e==`object`&&!!e&&`start`in e&&`end`in e}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function flattenValues(e){let{values:t,...n}=e;return{...n,...isRecord(t)?t:{}}}function toDate(e){return typeof e==`string`?new Date(e):isRange(e)?{start:toDate(e.start),end:toDate(e.end)}:e}function reviveRecord(e,t){let n=dateAttributeNames(e),r=flattenValues(t);for(let e of _)e in r&&(r[e]=toDate(r[e]));for(let e of n)e in r&&(r[e]=toDate(r[e]));return r}function serializeInput(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t instanceof Date?t.toISOString():t]))}var v=class RecordsQueryImpl extends s{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 reviveRecord(this.definition,e)}async export(e,n={}){if(!this.transport.postRaw)throw new t(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:r,sorts:i}=this.body(),{ids:a,locale:o,filename:s}=n;return await this.transport.postRaw(u(h.export,{objectName:this.objectName}),{q:this.state.search??``,...r?{filters:r}:{},...i?{sorts:i}:{},columns:e,...a?{ids:a}:{},...o?{locale:o}:{},timezone:n.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...s?{filename:s}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new a(c.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.post(u(h.aggregate,{objectName:this.objectName}),t)}async fetchPage(){let e=this.state.search===void 0?`list`:`search`,t=await this.transport.post(u(h[e],{objectName:this.objectName}),this.body());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.get(u(h.get,{objectName:this.objectName,id:e}));return this.revive(t)}async create(e){let t=await this.transport.post(u(h.create,{objectName:this.objectName}),{data:serializeInput(e)});return this.revive(t)}async update(e,t){let n=await this.transport.put(u(h.update,{objectName:this.objectName,id:e}),serializeInput(t));return this.revive(n)}async delete(e){await this.transport.delete(u(h.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.post(u(h.bulkCreate,{objectName:this.objectName}),{records:e.map(serializeInput)});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.post(u(h.bulkUpdate,{objectName:this.objectName}),{updates:e.map(({id:e,data:t})=>({id:e,data:serializeInput(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.post(u(h.bulkDelete,{objectName:this.objectName}),{ids:e});t.deleted.push(...n.deleted),t.errors.push(...n.errors)}),t}async listAccess(e){return await this.transport.get(u(m.list,{objectName:this.objectName,recordId:e}))}async grantAccess(e,t,n){return await this.transport.put(u(m.grant,{objectName:this.objectName,recordId:e,actorId:t}),{role:n})}async revokeAccess(e,t){return await this.transport.delete(u(m.revoke,{objectName:this.objectName,recordId:e,actorId:t}))}async clearAccess(e){return await this.transport.delete(u(m.clear,{objectName:this.objectName,recordId:e}))}};const y=new WeakMap;function definitionOf(e){let t=y.get(e);if(t)return t;let n=e.build();return y.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new v(e,t,null);let n=definitionOf(t);return new v(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 t(`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 t(`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 n=readEnvironment(),r=e.baseUrl??n.baseUrl;if(r===void 0)throw new t(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let i=e.apiKey??n.apiKey;if(i===void 0)throw new t(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...e,baseUrl:r,apiKey:i}}function createStandards(e={}){let{bundles:t=[],...n}=e;return buildStandards(r(resolveConfig(n)),t.flatMap(e=>e.objectBuilders))}function buildStandards(e,t){let n={bundles:{sync:(t,n)=>syncBundle(e,t,n)},from:t=>createRecordsQuery(e,t),files:createFilesApi(e),documents:createDocumentsApi(e)},r=t.map(e=>definitionOf(e).name);return assertObjectNames(r),t.forEach((t,i)=>{n[objectKeyOf(r[i])]=createRecordsQuery(e,t)}),n}export{reviveRecord as a,createDocumentsApi as c,definitionOf as i,syncBundle as l,createStandards as n,serializeInput as o,createRecordsQuery as r,createFilesApi as s,buildStandards as t};
@@ -1,4 +0,0 @@
1
- /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
- const e=require("./http-transport-CAPVZuiv.js");let t=require("@standards/schema"),n=require("@standards/schema/api");async function readInstalled(t,n){try{return await t.get(n)}catch(t){if(t instanceof e._&&t.status===404)return null;throw t}}async function syncBundle(t,r,i={}){let a=await r.build(),o=(0,n.buildOperationPath)(n.bundlesOperations.sync,{name:a.name}),s=await readInstalled(t,o);if(s?.hash===a.hash&&s.label===a.label&&s.description===a.description&&s.uses.join(`
3
- `)===a.uses.join(`
4
- `))return{applied:!1,hash:a.hash};let c=i.resolutions&&i.resolutions.length>0?{...a,resolutions:i.resolutions}:a;try{return await t.put(o,c)}catch(t){throw t instanceof e._&&t.status===409?new e.p(t.status,t.message,t.code):t instanceof e._&&t.status===400?new e.m(t.status,t.message,t.code):t}}function assertTimeout(e){if(e!==void 0&&!(Number.isFinite(e)&&e>0))throw new t.ValidationError(`timeoutMs must be a positive number of milliseconds`,[{path:[`timeoutMs`],message:`Expected a positive, finite number`}])}function assertFileInput(e,n){if(!(e instanceof Blob))throw new t.ValidationError(`${n} must be a Blob or File`,[{path:[n],message:`Expected a Blob or File`}]);let r=e.name;if(typeof r!=`string`||r===``)throw new t.ValidationError(`${n} needs a filename`,[{path:[n,`name`],message:`Expected a non-empty filename`}]);if(e.type===``)throw new t.ValidationError(`${n} "${r}" needs a MIME type`,[{path:[n,`type`],message:`Expected a non-empty MIME type`}])}function reviveDocumentFile(e){return{...e,processedAt:e.processedAt===null?null:new Date(e.processedAt)}}function createDocumentsApi(e){async function attachToRecord(t){let{file:r}=t;assertFileInput(r,`file`),assertTimeout(t.timeoutMs);let i=(0,n.buildOperationPath)(n.recordsOperations.attachDocument,{objectName:t.objectName,id:t.recordId}),a=new FormData;a.append(`files`,r,r.name),t.attributeName!==void 0&&a.append(`attributeName`,t.attributeName),t.documentId!==void 0&&a.append(`documentId`,t.documentId),t.title!==void 0&&a.append(`title`,t.title);let o=await e.postMultipart(i,a,{timeoutMs:t.timeoutMs});return{document:{id:o.document.id,title:o.document.title},file:reviveDocumentFile(o.file),action:o.action}}async function listFiles(t){return(await e.get((0,n.buildOperationPath)(n.documentsOperations.files,{id:t}))).map(reviveDocumentFile)}return{attachToRecord,listFiles}}function toUploadedFile(e){let t={id:e.id,name:e.name,mimeType:e.mimeType,size:e.size};return e.isPublic===!0&&typeof e.publicUrl==`string`?{...t,isPublic:!0,publicUrl:e.publicUrl}:{...t,isPublic:!1}}function createFilesApi(e){async function upload(t){assertFileInput(t.file,`file`),assertTimeout(t.timeoutMs);let[r]=await e.call(n.filesOperations.upload,{files:[t.file],public:t.public===!0?`true`:`false`,folderPath:t.folderPath},{timeoutMs:t.timeoutMs});return toUploadedFile(r)}async function getDownloadUrl(t){let{url:r}=await e.call(n.filesOperations.signedUrl,{id:t});return r}return{upload,getDownloadUrl}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const r=new Set([`from`,`files`,`documents`,`bundles`]);function assertObjectKeys(t){let n=new Map;for(let i of t){if(i.includes(`--`)||i.endsWith(`-`))throw new e.g(`Object "${i}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let t=objectKeyOf(i);if(r.has(t))throw new e.g(`Object "${i}" maps to the client key "${t}", which is reserved. Rename the object.`);let a=n.get(t);if(a!==void 0&&a!==i)throw new e.g(`Objects "${a}" and "${i}" both map to the client key "${t}". Rename one of them.`);n.set(t,i)}}function assertObjectNames(e){let n=new Set;for(let r of e){if(n.has(r))throw new t.DuplicateError(`object`,r);n.add(r)}assertObjectKeys(e)}const i=[`createdAt`,`updatedAt`,`deletedAt`];function dateAttributeNames(e){let t=new Set;for(let n of e?.attributes??[])n.type===`date`&&t.add(n.name);return t}function isRange(e){return typeof e==`object`&&!!e&&`start`in e&&`end`in e}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function flattenValues(e){let{values:t,...n}=e;return{...n,...isRecord(t)?t:{}}}function toDate(e){return typeof e==`string`?new Date(e):isRange(e)?{start:toDate(e.start),end:toDate(e.end)}:e}function reviveRecord(e,t){let n=dateAttributeNames(e),r=flattenValues(t);for(let e of i)e in r&&(r[e]=toDate(r[e]));for(let e of n)e in r&&(r[e]=toDate(r[e]));return r}function serializeInput(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t instanceof Date?t.toISOString():t]))}var a=class RecordsQueryImpl extends t.RecordQuery{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 reviveRecord(this.definition,e)}async export(t,r={}){if(!this.transport.postRaw)throw new e.g(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:i,sorts:a}=this.body(),{ids:o,locale:s,filename:c}=r;return await this.transport.postRaw((0,n.buildOperationPath)(n.recordsOperations.export,{objectName:this.objectName}),{q:this.state.search??``,...i?{filters:i}:{},...a?{sorts:a}:{},columns:t,...o?{ids:o}:{},...s?{locale:s}:{},timezone:r.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...c?{filename:c}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new t.AggregateValidationError(t.SchemaErrorCode.AGGREGATE_SEARCH_UNSUPPORTED,`An aggregate cannot be narrowed by a search; use filters instead`);let r={...e,query:this.toDefinition(),timezone:e.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone};return await this.transport.post((0,n.buildOperationPath)(n.recordsOperations.aggregate,{objectName:this.objectName}),r)}async fetchPage(){let e=this.state.search===void 0?`list`:`search`,t=await this.transport.post((0,n.buildOperationPath)(n.recordsOperations[e],{objectName:this.objectName}),this.body());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.get((0,n.buildOperationPath)(n.recordsOperations.get,{objectName:this.objectName,id:e}));return this.revive(t)}async create(e){let t=await this.transport.post((0,n.buildOperationPath)(n.recordsOperations.create,{objectName:this.objectName}),{data:serializeInput(e)});return this.revive(t)}async update(e,t){let r=await this.transport.put((0,n.buildOperationPath)(n.recordsOperations.update,{objectName:this.objectName,id:e}),serializeInput(t));return this.revive(r)}async delete(e){await this.transport.delete((0,n.buildOperationPath)(n.recordsOperations.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,r)=>{let i=await this.transport.post((0,n.buildOperationPath)(n.recordsOperations.bulkCreate,{objectName:this.objectName}),{records:e.map(serializeInput)});t.created.push(...i.created.map(e=>this.revive(e))),t.errors.push(...i.errors.map(e=>({...e,index:e.index+r})))}),t}async updateMany(e){let t={updated:[],errors:[]};return await this.inChunks(e,async e=>{let r=await this.transport.post((0,n.buildOperationPath)(n.recordsOperations.bulkUpdate,{objectName:this.objectName}),{updates:e.map(({id:e,data:t})=>({id:e,data:serializeInput(t)}))});t.updated.push(...r.updated.map(e=>this.revive(e))),t.errors.push(...r.errors)}),t}async deleteMany(e){let t={deleted:[],errors:[]};return await this.inChunks(e,async e=>{let r=await this.transport.post((0,n.buildOperationPath)(n.recordsOperations.bulkDelete,{objectName:this.objectName}),{ids:e});t.deleted.push(...r.deleted),t.errors.push(...r.errors)}),t}async listAccess(e){return await this.transport.get((0,n.buildOperationPath)(n.recordAccessOperations.list,{objectName:this.objectName,recordId:e}))}async grantAccess(e,t,r){return await this.transport.put((0,n.buildOperationPath)(n.recordAccessOperations.grant,{objectName:this.objectName,recordId:e,actorId:t}),{role:r})}async revokeAccess(e,t){return await this.transport.delete((0,n.buildOperationPath)(n.recordAccessOperations.revoke,{objectName:this.objectName,recordId:e,actorId:t}))}async clearAccess(e){return await this.transport.delete((0,n.buildOperationPath)(n.recordAccessOperations.clear,{objectName:this.objectName,recordId:e}))}};const o=new WeakMap;function definitionOf(e){let t=o.get(e);if(t)return t;let n=e.build();return o.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new a(e,t,null);let n=definitionOf(t);return new a(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(t){if(globalThis.window!==void 0){if(t.apiKey)throw new e.g(`createStandards received an apiKey in a browser context. API keys belong to server code only (Route Handlers, Server Components, scripts).`);if(t.baseUrl===void 0)throw new e.g(`createStandards needs an explicit baseUrl in a browser context: STANDARDS_API_URL and STANDARDS_API_KEY are never read from the environment there.`);return{...t,baseUrl:t.baseUrl,apiKey:``}}let n=readEnvironment(),r=t.baseUrl??n.baseUrl;if(r===void 0)throw new e.g(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let i=t.apiKey??n.apiKey;if(i===void 0)throw new e.g(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...t,baseUrl:r,apiKey:i}}function createStandards(t={}){let{bundles:n=[],...r}=t;return buildStandards(e.n(resolveConfig(r)),n.flatMap(e=>e.objectBuilders))}function buildStandards(e,t){let n={bundles:{sync:(t,n)=>syncBundle(e,t,n)},from:t=>createRecordsQuery(e,t),files:createFilesApi(e),documents:createDocumentsApi(e)},r=t.map(e=>definitionOf(e).name);return assertObjectNames(r),t.forEach((t,i)=>{n[objectKeyOf(r[i])]=createRecordsQuery(e,t)}),n}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return reviveRecord}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return createDocumentsApi}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return definitionOf}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return syncBundle}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createStandards}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return serializeInput}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return createRecordsQuery}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return createFilesApi}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return buildStandards}});