@standards/client 1.0.0-alpha.392 → 1.0.0-alpha.394
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -10
- package/dist/app.d.mts +10 -3
- package/dist/app.d.ts +10 -3
- package/dist/app.js +1 -1
- package/dist/app.mjs +1 -1
- package/dist/create-standards-CM5ebx80.mjs +4 -0
- package/dist/create-standards-DbyGn7AW.js +4 -0
- package/dist/{create-standards-3ODOXxRV.d.ts → create-standards-DoPZqxf5.d.mts} +35 -108
- package/dist/{create-standards-Cl_Lxvy3.d.mts → create-standards-Z58KKZjG.d.ts} +35 -108
- package/dist/http-transport-BxgXm4Oi.mjs +2 -0
- package/dist/{http-transport-DBgedLFQ.d.mts → http-transport-C1u5UGkC.d.mts} +9 -9
- package/dist/{http-transport-DBgedLFQ.d.ts → http-transport-C1u5UGkC.d.ts} +9 -9
- package/dist/http-transport-CAPVZuiv.js +2 -0
- package/dist/index.d.mts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/testing.d.mts +12 -12
- package/dist/testing.d.ts +12 -12
- package/dist/testing.js +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/create-standards-DVK0prD0.js +0 -2
- package/dist/create-standards-p0dGJXSu.mjs +0 -2
- package/dist/http-transport-17TmxnFl.mjs +0 -2
- package/dist/http-transport-DHbErYa4.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
+
import{DRAFT_CONFLICT_KINDS as e,SchemaErrorCode as t,ValidationError as n}from"@standards/schema";import{encodePathSegment as r,splitOperationInput as i}from"@standards/schema/api";var StandardsRequestError=class extends Error{constructor(e,t,n,r){super(t),this.name=`StandardsRequestError`,this.status=e,this.code=n,this.details=r}},StandardsAuthError=class extends StandardsRequestError{constructor(e,t,n,r){super(e,t,n,r),this.name=`StandardsAuthError`}},BundleConflictError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleConflictError`;let r=/"([^"]+)" is owned by (\S+)/.exec(t);this.objectName=r?.[1]??``,this.owner=r?.[2]??``}},BundleValidationError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleValidationError`}},StandardsConfigurationError=class extends Error{constructor(e){super(e),this.name=`StandardsConfigurationError`}};function schemaApiErrorCode(e){if(typeof e!=`object`||!e||!(`code`in e))return;let{code:t}=e;return typeof t==`string`?t:void 0}const a=new Set([t.CONFIGURATION_REQUIRED]);function isPermanentRefusal(e){let t=schemaApiErrorCode(e);return t!==void 0&&a.has(t)}function isObjectNotFound(e){if(typeof e!=`object`||!e)return!1;let{code:n,status:r}=e;return n===t.OBJECT_NOT_FOUND||r===404}function isDraftRevisionConflict(e){return schemaApiErrorCode(e)===t.DRAFT_REVISION_CONFLICT}const o=new Set(e);function draftConflictChanges(e){if(!isDraftRevisionConflict(e))return[];let t=e.details?.changes;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.key==`string`&&typeof e.label==`string`&&typeof e.seen==`string`&&o.has(e.kind)):[]}function isViewNotFound(e){return typeof e!=`object`||!e?!1:e.status===404}function parseContentDispositionFilename(e){if(!e)return;let t=e.match(/filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/i);if(t?.[1])try{return decodeURIComponent(t[1].trim())}catch{}let n=e.match(/filename\s*=\s*"([^"]*)"|filename\s*=\s*([^;]+)/i);return(n?.[1]??n?.[2])?.trim()||void 0}function recordsPath(e,...t){return[`/records`,...[e,...t].map(r)].join(`/`)}function resolveWithinBase(e,t){let r=e.endsWith(`/`)?e:`${e}/`,i=new URL(r),a=t.replace(/^\/+/,``),[o]=a.split(/[?#]/);if((o??``).split(`/`).some(e=>e===`..`||e===`.`))throw new n(`Request path "${t}" walks outside its own collection`,[]);let s=new URL(a,i);if(s.origin!==i.origin||!s.pathname.startsWith(i.pathname))throw new n(`Request path "${t}" resolves outside the API base "${i.pathname}"`,[]);return s}function readJson(e){return e.status===204||e.headers.get(`content-length`)===`0`?null:e.json()}async function readDownload(e){let t=await e.blob();return{blob:t,filename:parseContentDispositionFilename(e.headers.get(`Content-Disposition`)),mimeType:e.headers.get(`Content-Type`)??t.type}}function multipartBody(e,t){let n=new FormData;for(let[r,i]of Object.entries(t??{}))if(i!=null){if(r===e)for(let t of Array.isArray(i)?i:[i]){let r=t.name;typeof r==`string`?n.append(e,t,r):n.append(e,t)}else n.append(r,String(i))}return n}function headerRecord(e){return e===void 0?{}:e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}}function withoutContentType(e){return Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`content-type`))}function parseJsonObject(e){try{let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return}}function refusalFrom(e,t,n){let r=parseJsonObject(t),i=r?.message??r?.error??r?.detail,a=i==null?n&&r===void 0&&t?t:`Request failed with status ${e}`:String(i),o=typeof r?.code==`string`?r.code:void 0;return new(e===401||e===403?StandardsAuthError:StandardsRequestError)(e,a,o,r?.details)}function refusalOf(e,t){return refusalFrom(e,t,!1)}async function readRefusal(e){return refusalOf(e.status,await e.text().catch(()=>``))}function isTimeout(e){return e instanceof DOMException&&e.name===`TimeoutError`}function trimSlashes(e,t){let n=0,r=e.length;for(;t&&n<r&&e[n]===`/`;)n+=1;for(;r>n&&e[r-1]===`/`;)--r;return e.slice(n,r)}function backoff(e){return new Promise(t=>setTimeout(t,1e3*2**e))}function abortReason(e){return e?.aborted?e.reason:new DOMException(`The operation was aborted.`,`AbortError`)}function canReportUploadProgress(e){return typeof XMLHttpRequest>`u`?!1:e.fetch===void 0||e.uploadAuthorization!==void 0}function sendWithProgress(e,t){let{signal:n}=e;return n?.aborted?Promise.reject(abortReason(n)):new Promise((r,i)=>{let a=new XMLHttpRequest;a.open(e.method,e.url);for(let[t,n]of Object.entries(e.headers))a.setRequestHeader(t,n);let o=Object.keys(e.headers).some(e=>e.toLowerCase()===`authorization`);e.token&&!o&&a.setRequestHeader(`Authorization`,`Bearer ${e.token}`),a.upload.addEventListener(`progress`,t=>{t.lengthComputable&&e.onUploadProgress({loaded:t.loaded,total:t.total})});let onAbort=()=>a.abort();n?.addEventListener(`abort`,onAbort,{once:!0});let settle=()=>n?.removeEventListener(`abort`,onAbort);a.addEventListener(`load`,()=>{if(settle(),a.status<200||a.status>=300){i(refusalOf(a.status,a.responseText));return}try{r(t(a.responseText))}catch(e){i(e)}}),a.addEventListener(`error`,()=>{settle(),i(new StandardsRequestError(0,`Network request failed`))}),a.addEventListener(`abort`,()=>{settle(),i(abortReason(n))}),a.send(e.form)})}function createHttpTransport(e){let{baseUrl:t,onUnauthorized:n,getRetries:r=0}=e,a=e.timeoutMs??3e4,o=e.apiPrefix===void 0?void 0:trimSlashes(e.apiPrefix,!0),s=o?`${trimSlashes(t,!1)}/${o}`:t;function buildUrl(e,t){let n=resolveWithinBase(s,e);for(let[e,r]of Object.entries(t??{}))r!=null&&n.searchParams.set(e,String(r));return n.toString()}async function headersFor(t){let n={"Content-Type":`application/json`,...headerRecord(await e.headers?.()),...headerRecord(t.headers)};return t.body instanceof FormData?withoutContentType(n):n}function observe(t){try{e.onResponse?.(t)}catch{}}async function fetchOnce(t,n,r){let i=n.signal??void 0;i?.throwIfAborted();let a=r===null?void 0:AbortSignal.timeout(r),o=new AbortController,expire=()=>o.abort(a?.reason);a?.addEventListener(`abort`,expire,{once:!0});let s=i?AbortSignal.any([i,o.signal]):o.signal,c=new Promise((e,t)=>{s.addEventListener(`abort`,()=>t(s.reason),{once:!0})});try{let r=e.fetch??fetch,i=await headersFor(n);return await Promise.race([r(t,{...n,headers:i,signal:s}),c])}catch(e){throw i?.aborted?i.reason:e}finally{a?.removeEventListener(`abort`,expire)}}function connectionFailure(e){return e instanceof TypeError||isTimeout(e)?new StandardsRequestError(0,`Could not connect to ${t}`):e}async function refreshAndRetry(e,t,r){try{if(!await n?.())return;let i=await fetchOnce(e,t,r);return observe(i),i}catch{if(t.signal?.aborted)throw t.signal.reason;return}}async function readRefusalWithin(e){let t,n=new Promise(n=>{t=setTimeout(()=>n(refusalFrom(e.status,``,!1)),1500)});try{let t=e.text().catch(()=>``).then(t=>refusalFrom(e.status,t,!1));return await Promise.race([t,n])}finally{clearTimeout(t)}}async function send(e,t,i,o){let s=buildUrl(e,i.params),c=(t.method??`GET`).toUpperCase(),l=i.maxRetries??(c===`GET`?r:0),u=i.timeoutMs===void 0?a:i.timeoutMs;for(let e=0;;e++){let r=e<l,a;try{a=await fetchOnce(s,t,u)}catch(n){if(r&&n instanceof TypeError&&!t.signal?.aborted){await backoff(e);continue}throw connectionFailure(n)}if(observe(a),a.status>=500&&r){let t=await readRefusalWithin(a);if(isPermanentRefusal(t))throw t;await backoff(e);continue}if(a.status===401&&n&&(a=await refreshAndRetry(s,t,u)??a),!a.ok){let e=await a.text().catch(()=>``);throw refusalFrom(a.status,e,i.plainTextRefusal??!1)}return await o(a)}}async function stream(t,r,a={}){let{path:o,query:s,body:c,headers:l}=i(t,r??{}),u=buildUrl(o,s),{signal:d,onRequest:f}=a,p=e.fetch??fetch,attempt=async()=>(f?.(),await p(u,{method:t.method,body:c===void 0?void 0:JSON.stringify(c),signal:d,headers:await headersFor({headers:{...l,...a.headers}})})),m=await attempt();if(m.status===401){let e=await readRefusal(m);if(e.code===`MFA_REQUIRED`||!n||!await n().catch(()=>!1))throw e;d?.throwIfAborted(),m=await attempt()}if(!m.ok)throw await readRefusal(m);return m}async function json(e,t,n){return await send(t,{method:e,body:n?JSON.stringify(n):void 0},{},readJson)}return{async call(t,n,r={}){if(t.response===`events`)return await stream(t,n,{signal:r.signal});let{path:a,query:o,body:s,headers:c}=i(t,n??{});if(t.upload!==void 0&&r.onUploadProgress&&canReportUploadProgress(e)){r.signal?.throwIfAborted();let n=await e.uploadAuthorization?.()??null;return await sendWithProgress({url:buildUrl(a,o),method:t.method,headers:withoutContentType({...headerRecord(await e.headers?.()),...c}),token:n,form:multipartBody(t.upload.field,s),onUploadProgress:r.onUploadProgress,signal:r.signal},e=>e?JSON.parse(e):null)}let l=t.upload===void 0?s===void 0?void 0:JSON.stringify(s):multipartBody(t.upload.field,s),u=t.response===`bytes`?readDownload:readJson;return await send(a,{method:t.method,body:l,signal:r.signal,...c?{headers:c}:{},...r.keepalive?{keepalive:!0}:{}},{params:o,maxRetries:r.maxRetries,timeoutMs:r.timeoutMs},u)},stream,async get(e,t){return await send(e,{method:`GET`},{params:t},readJson)},post:(e,t)=>json(`POST`,e,t),patch:(e,t)=>json(`PATCH`,e,t),put:(e,t)=>json(`PUT`,e,t),delete:e=>json(`DELETE`,e),async getText(e,t){return await send(e,{method:`GET`},{params:t,plainTextRefusal:!0},e=>e.text())},async postRaw(e,t){return await send(e,{method:`POST`,body:JSON.stringify(t)},{plainTextRefusal:!0},e=>e)},async postMultipart(e,t,n={}){return await send(e,{method:`POST`,body:t},{timeoutMs:n.timeoutMs},readJson)}}}function createTransport(e){let{baseUrl:t,apiKey:n,tenantId:r,timeoutMs:i}=e,a={Authorization:`Bearer ${n}`,...r?{"X-Tenant-ID":r}:{}};return createHttpTransport({baseUrl:t,timeoutMs:i,headers:()=>a})}export{StandardsRequestError as _,recordsPath as a,isDraftRevisionConflict as c,isViewNotFound as d,schemaApiErrorCode as f,StandardsConfigurationError as g,StandardsAuthError as h,refusalOf as i,isObjectNotFound as l,BundleValidationError as m,createTransport as n,parseContentDispositionFilename as o,BundleConflictError as p,readRefusal as r,draftConflictChanges as s,createHttpTransport as t,isPermanentRefusal as u};
|
|
@@ -16,20 +16,20 @@ declare class StandardsAuthError extends StandardsRequestError {
|
|
|
16
16
|
constructor(status: number, message: string, code?: string, details?: unknown);
|
|
17
17
|
}
|
|
18
18
|
/**
|
|
19
|
-
* 409 from `PUT /
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
19
|
+
* 409 from `PUT /bundles/:name`: a name this bundle declares is owned by core or another bundle.
|
|
20
|
+
* A declared view that clashes with the workspace's views (a second default for the same object
|
|
21
|
+
* and context, or a name held by a system view) is a 409 too; its message names no owner, so
|
|
22
|
+
* `objectName` and `owner` are empty.
|
|
23
23
|
*/
|
|
24
|
-
declare class
|
|
24
|
+
declare class BundleConflictError extends StandardsRequestError {
|
|
25
25
|
/** The object or `object:view` name that clashed. */
|
|
26
26
|
readonly objectName: string;
|
|
27
|
-
/** `core
|
|
27
|
+
/** `core` or `bundle:<name>`. */
|
|
28
28
|
readonly owner: string;
|
|
29
29
|
constructor(status: number, message: string, code: string | undefined);
|
|
30
30
|
}
|
|
31
|
-
/** 400 from `PUT /
|
|
32
|
-
declare class
|
|
31
|
+
/** 400 from `PUT /bundles/:name`: bad name, oversize payload, hash mismatch, invalid definition, or an unresolved migration. */
|
|
32
|
+
declare class BundleValidationError extends StandardsRequestError {
|
|
33
33
|
constructor(status: number, message: string, code: string | undefined);
|
|
34
34
|
}
|
|
35
35
|
/** The client was constructed in a way it refuses to run (e.g. an API key in a browser). */
|
|
@@ -162,4 +162,4 @@ declare function createHttpTransport(config: HttpTransportConfig): HttpTransport
|
|
|
162
162
|
*/
|
|
163
163
|
declare function createTransport(config: TransportConfig): HttpTransport;
|
|
164
164
|
//#endregion
|
|
165
|
-
export { StandardsRequestError as _, OperationStreamOptions as a, UploadProgress as c, readRefusal as d, refusalOf as f, StandardsConfigurationError as g, StandardsAuthError as h, OperationCallOptions as i, createHttpTransport as l,
|
|
165
|
+
export { StandardsRequestError as _, OperationStreamOptions as a, UploadProgress as c, readRefusal as d, refusalOf as f, StandardsConfigurationError as g, StandardsAuthError as h, OperationCallOptions as i, createHttpTransport as l, BundleValidationError as m, HttpTransportConfig as n, Transport as o, BundleConflictError as p, MultipartRequestOptions as r, TransportConfig as s, HttpTransport as t, createTransport as u };
|
|
@@ -16,20 +16,20 @@ declare class StandardsAuthError extends StandardsRequestError {
|
|
|
16
16
|
constructor(status: number, message: string, code?: string, details?: unknown);
|
|
17
17
|
}
|
|
18
18
|
/**
|
|
19
|
-
* 409 from `PUT /
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
19
|
+
* 409 from `PUT /bundles/:name`: a name this bundle declares is owned by core or another bundle.
|
|
20
|
+
* A declared view that clashes with the workspace's views (a second default for the same object
|
|
21
|
+
* and context, or a name held by a system view) is a 409 too; its message names no owner, so
|
|
22
|
+
* `objectName` and `owner` are empty.
|
|
23
23
|
*/
|
|
24
|
-
declare class
|
|
24
|
+
declare class BundleConflictError extends StandardsRequestError {
|
|
25
25
|
/** The object or `object:view` name that clashed. */
|
|
26
26
|
readonly objectName: string;
|
|
27
|
-
/** `core
|
|
27
|
+
/** `core` or `bundle:<name>`. */
|
|
28
28
|
readonly owner: string;
|
|
29
29
|
constructor(status: number, message: string, code: string | undefined);
|
|
30
30
|
}
|
|
31
|
-
/** 400 from `PUT /
|
|
32
|
-
declare class
|
|
31
|
+
/** 400 from `PUT /bundles/:name`: bad name, oversize payload, hash mismatch, invalid definition, or an unresolved migration. */
|
|
32
|
+
declare class BundleValidationError extends StandardsRequestError {
|
|
33
33
|
constructor(status: number, message: string, code: string | undefined);
|
|
34
34
|
}
|
|
35
35
|
/** The client was constructed in a way it refuses to run (e.g. an API key in a browser). */
|
|
@@ -162,4 +162,4 @@ declare function createHttpTransport(config: HttpTransportConfig): HttpTransport
|
|
|
162
162
|
*/
|
|
163
163
|
declare function createTransport(config: TransportConfig): HttpTransport;
|
|
164
164
|
//#endregion
|
|
165
|
-
export { StandardsRequestError as _, OperationStreamOptions as a, UploadProgress as c, readRefusal as d, refusalOf as f, StandardsConfigurationError as g, StandardsAuthError as h, OperationCallOptions as i, createHttpTransport as l,
|
|
165
|
+
export { StandardsRequestError as _, OperationStreamOptions as a, UploadProgress as c, readRefusal as d, refusalOf as f, StandardsConfigurationError as g, StandardsAuthError as h, OperationCallOptions as i, createHttpTransport as l, BundleValidationError as m, HttpTransportConfig as n, Transport as o, BundleConflictError as p, MultipartRequestOptions as r, TransportConfig as s, HttpTransport as t, createTransport as u };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
+
let e=require("@standards/schema"),t=require("@standards/schema/api");var StandardsRequestError=class extends Error{constructor(e,t,n,r){super(t),this.name=`StandardsRequestError`,this.status=e,this.code=n,this.details=r}},StandardsAuthError=class extends StandardsRequestError{constructor(e,t,n,r){super(e,t,n,r),this.name=`StandardsAuthError`}},BundleConflictError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleConflictError`;let r=/"([^"]+)" is owned by (\S+)/.exec(t);this.objectName=r?.[1]??``,this.owner=r?.[2]??``}},BundleValidationError=class extends StandardsRequestError{constructor(e,t,n){super(e,t,n),this.name=`BundleValidationError`}},StandardsConfigurationError=class extends Error{constructor(e){super(e),this.name=`StandardsConfigurationError`}};function schemaApiErrorCode(e){if(typeof e!=`object`||!e||!(`code`in e))return;let{code:t}=e;return typeof t==`string`?t:void 0}const n=new Set([e.SchemaErrorCode.CONFIGURATION_REQUIRED]);function isPermanentRefusal(e){let t=schemaApiErrorCode(e);return t!==void 0&&n.has(t)}function isObjectNotFound(t){if(typeof t!=`object`||!t)return!1;let{code:n,status:r}=t;return n===e.SchemaErrorCode.OBJECT_NOT_FOUND||r===404}function isDraftRevisionConflict(t){return schemaApiErrorCode(t)===e.SchemaErrorCode.DRAFT_REVISION_CONFLICT}const r=new Set(e.DRAFT_CONFLICT_KINDS);function draftConflictChanges(e){if(!isDraftRevisionConflict(e))return[];let t=e.details?.changes;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.key==`string`&&typeof e.label==`string`&&typeof e.seen==`string`&&r.has(e.kind)):[]}function isViewNotFound(e){return typeof e!=`object`||!e?!1:e.status===404}function parseContentDispositionFilename(e){if(!e)return;let t=e.match(/filename\*\s*=\s*(?:UTF-8|utf-8)''([^;]+)/i);if(t?.[1])try{return decodeURIComponent(t[1].trim())}catch{}let n=e.match(/filename\s*=\s*"([^"]*)"|filename\s*=\s*([^;]+)/i);return(n?.[1]??n?.[2])?.trim()||void 0}function recordsPath(e,...n){return[`/records`,...[e,...n].map(t.encodePathSegment)].join(`/`)}function resolveWithinBase(t,n){let r=t.endsWith(`/`)?t:`${t}/`,i=new URL(r),a=n.replace(/^\/+/,``),[o]=a.split(/[?#]/);if((o??``).split(`/`).some(e=>e===`..`||e===`.`))throw new e.ValidationError(`Request path "${n}" walks outside its own collection`,[]);let s=new URL(a,i);if(s.origin!==i.origin||!s.pathname.startsWith(i.pathname))throw new e.ValidationError(`Request path "${n}" resolves outside the API base "${i.pathname}"`,[]);return s}function readJson(e){return e.status===204||e.headers.get(`content-length`)===`0`?null:e.json()}async function readDownload(e){let t=await e.blob();return{blob:t,filename:parseContentDispositionFilename(e.headers.get(`Content-Disposition`)),mimeType:e.headers.get(`Content-Type`)??t.type}}function multipartBody(e,t){let n=new FormData;for(let[r,i]of Object.entries(t??{}))if(i!=null){if(r===e)for(let t of Array.isArray(i)?i:[i]){let r=t.name;typeof r==`string`?n.append(e,t,r):n.append(e,t)}else n.append(r,String(i))}return n}function headerRecord(e){return e===void 0?{}:e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}}function withoutContentType(e){return Object.fromEntries(Object.entries(e).filter(([e])=>e.toLowerCase()!==`content-type`))}function parseJsonObject(e){try{let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return}}function refusalFrom(e,t,n){let r=parseJsonObject(t),i=r?.message??r?.error??r?.detail,a=i==null?n&&r===void 0&&t?t:`Request failed with status ${e}`:String(i),o=typeof r?.code==`string`?r.code:void 0;return new(e===401||e===403?StandardsAuthError:StandardsRequestError)(e,a,o,r?.details)}function refusalOf(e,t){return refusalFrom(e,t,!1)}async function readRefusal(e){return refusalOf(e.status,await e.text().catch(()=>``))}function isTimeout(e){return e instanceof DOMException&&e.name===`TimeoutError`}function trimSlashes(e,t){let n=0,r=e.length;for(;t&&n<r&&e[n]===`/`;)n+=1;for(;r>n&&e[r-1]===`/`;)--r;return e.slice(n,r)}function backoff(e){return new Promise(t=>setTimeout(t,1e3*2**e))}function abortReason(e){return e?.aborted?e.reason:new DOMException(`The operation was aborted.`,`AbortError`)}function canReportUploadProgress(e){return typeof XMLHttpRequest>`u`?!1:e.fetch===void 0||e.uploadAuthorization!==void 0}function sendWithProgress(e,t){let{signal:n}=e;return n?.aborted?Promise.reject(abortReason(n)):new Promise((r,i)=>{let a=new XMLHttpRequest;a.open(e.method,e.url);for(let[t,n]of Object.entries(e.headers))a.setRequestHeader(t,n);let o=Object.keys(e.headers).some(e=>e.toLowerCase()===`authorization`);e.token&&!o&&a.setRequestHeader(`Authorization`,`Bearer ${e.token}`),a.upload.addEventListener(`progress`,t=>{t.lengthComputable&&e.onUploadProgress({loaded:t.loaded,total:t.total})});let onAbort=()=>a.abort();n?.addEventListener(`abort`,onAbort,{once:!0});let settle=()=>n?.removeEventListener(`abort`,onAbort);a.addEventListener(`load`,()=>{if(settle(),a.status<200||a.status>=300){i(refusalOf(a.status,a.responseText));return}try{r(t(a.responseText))}catch(e){i(e)}}),a.addEventListener(`error`,()=>{settle(),i(new StandardsRequestError(0,`Network request failed`))}),a.addEventListener(`abort`,()=>{settle(),i(abortReason(n))}),a.send(e.form)})}function createHttpTransport(e){let{baseUrl:n,onUnauthorized:r,getRetries:i=0}=e,a=e.timeoutMs??3e4,o=e.apiPrefix===void 0?void 0:trimSlashes(e.apiPrefix,!0),s=o?`${trimSlashes(n,!1)}/${o}`:n;function buildUrl(e,t){let n=resolveWithinBase(s,e);for(let[e,r]of Object.entries(t??{}))r!=null&&n.searchParams.set(e,String(r));return n.toString()}async function headersFor(t){let n={"Content-Type":`application/json`,...headerRecord(await e.headers?.()),...headerRecord(t.headers)};return t.body instanceof FormData?withoutContentType(n):n}function observe(t){try{e.onResponse?.(t)}catch{}}async function fetchOnce(t,n,r){let i=n.signal??void 0;i?.throwIfAborted();let a=r===null?void 0:AbortSignal.timeout(r),o=new AbortController,expire=()=>o.abort(a?.reason);a?.addEventListener(`abort`,expire,{once:!0});let s=i?AbortSignal.any([i,o.signal]):o.signal,c=new Promise((e,t)=>{s.addEventListener(`abort`,()=>t(s.reason),{once:!0})});try{let r=e.fetch??fetch,i=await headersFor(n);return await Promise.race([r(t,{...n,headers:i,signal:s}),c])}catch(e){throw i?.aborted?i.reason:e}finally{a?.removeEventListener(`abort`,expire)}}function connectionFailure(e){return e instanceof TypeError||isTimeout(e)?new StandardsRequestError(0,`Could not connect to ${n}`):e}async function refreshAndRetry(e,t,n){try{if(!await r?.())return;let i=await fetchOnce(e,t,n);return observe(i),i}catch{if(t.signal?.aborted)throw t.signal.reason;return}}async function readRefusalWithin(e){let t,n=new Promise(n=>{t=setTimeout(()=>n(refusalFrom(e.status,``,!1)),1500)});try{let t=e.text().catch(()=>``).then(t=>refusalFrom(e.status,t,!1));return await Promise.race([t,n])}finally{clearTimeout(t)}}async function send(e,t,n,o){let s=buildUrl(e,n.params),c=(t.method??`GET`).toUpperCase(),l=n.maxRetries??(c===`GET`?i:0),u=n.timeoutMs===void 0?a:n.timeoutMs;for(let e=0;;e++){let i=e<l,a;try{a=await fetchOnce(s,t,u)}catch(n){if(i&&n instanceof TypeError&&!t.signal?.aborted){await backoff(e);continue}throw connectionFailure(n)}if(observe(a),a.status>=500&&i){let t=await readRefusalWithin(a);if(isPermanentRefusal(t))throw t;await backoff(e);continue}if(a.status===401&&r&&(a=await refreshAndRetry(s,t,u)??a),!a.ok){let e=await a.text().catch(()=>``);throw refusalFrom(a.status,e,n.plainTextRefusal??!1)}return await o(a)}}async function stream(n,i,a={}){let{path:o,query:s,body:c,headers:l}=(0,t.splitOperationInput)(n,i??{}),u=buildUrl(o,s),{signal:d,onRequest:f}=a,p=e.fetch??fetch,attempt=async()=>(f?.(),await p(u,{method:n.method,body:c===void 0?void 0:JSON.stringify(c),signal:d,headers:await headersFor({headers:{...l,...a.headers}})})),m=await attempt();if(m.status===401){let e=await readRefusal(m);if(e.code===`MFA_REQUIRED`||!r||!await r().catch(()=>!1))throw e;d?.throwIfAborted(),m=await attempt()}if(!m.ok)throw await readRefusal(m);return m}async function json(e,t,n){return await send(t,{method:e,body:n?JSON.stringify(n):void 0},{},readJson)}return{async call(n,r,i={}){if(n.response===`events`)return await stream(n,r,{signal:i.signal});let{path:a,query:o,body:s,headers:c}=(0,t.splitOperationInput)(n,r??{});if(n.upload!==void 0&&i.onUploadProgress&&canReportUploadProgress(e)){i.signal?.throwIfAborted();let t=await e.uploadAuthorization?.()??null;return await sendWithProgress({url:buildUrl(a,o),method:n.method,headers:withoutContentType({...headerRecord(await e.headers?.()),...c}),token:t,form:multipartBody(n.upload.field,s),onUploadProgress:i.onUploadProgress,signal:i.signal},e=>e?JSON.parse(e):null)}let l=n.upload===void 0?s===void 0?void 0:JSON.stringify(s):multipartBody(n.upload.field,s),u=n.response===`bytes`?readDownload:readJson;return await send(a,{method:n.method,body:l,signal:i.signal,...c?{headers:c}:{},...i.keepalive?{keepalive:!0}:{}},{params:o,maxRetries:i.maxRetries,timeoutMs:i.timeoutMs},u)},stream,async get(e,t){return await send(e,{method:`GET`},{params:t},readJson)},post:(e,t)=>json(`POST`,e,t),patch:(e,t)=>json(`PATCH`,e,t),put:(e,t)=>json(`PUT`,e,t),delete:e=>json(`DELETE`,e),async getText(e,t){return await send(e,{method:`GET`},{params:t,plainTextRefusal:!0},e=>e.text())},async postRaw(e,t){return await send(e,{method:`POST`,body:JSON.stringify(t)},{plainTextRefusal:!0},e=>e)},async postMultipart(e,t,n={}){return await send(e,{method:`POST`,body:t},{timeoutMs:n.timeoutMs},readJson)}}}function createTransport(e){let{baseUrl:t,apiKey:n,tenantId:r,timeoutMs:i}=e,a={Authorization:`Bearer ${n}`,...r?{"X-Tenant-ID":r}:{}};return createHttpTransport({baseUrl:t,timeoutMs:i,headers:()=>a})}Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return StandardsRequestError}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return recordsPath}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return isDraftRevisionConflict}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return isViewNotFound}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return schemaApiErrorCode}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return StandardsConfigurationError}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return StandardsAuthError}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return refusalOf}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return isObjectNotFound}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return BundleValidationError}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createTransport}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return parseContentDispositionFilename}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return BundleConflictError}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return readRefusal}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return draftConflictChanges}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return createHttpTransport}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return isPermanentRefusal}});
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
|
|
2
|
-
import { _ as StandardsRequestError, g as StandardsConfigurationError, h as StandardsAuthError, m as
|
|
3
|
-
import { A as
|
|
4
|
-
import { Attribute, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, NotFoundError, ObjectDefinition, ObjectDefinition as ObjectDefinition$1, RecordAccessRole, RecordAudience, RecordMetadata,
|
|
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";
|
|
5
5
|
import { encodePathSegment } from "@standards/schema/api";
|
|
6
6
|
//#region src/records/revive.d.ts
|
|
7
7
|
/**
|
|
@@ -14,9 +14,9 @@ export declare function reviveRecord<T extends Record<string, unknown>>(definiti
|
|
|
14
14
|
//#region src/path.d.ts
|
|
15
15
|
/**
|
|
16
16
|
* Every caller-supplied path segment is percent-encoded: `objectName` and `id`
|
|
17
|
-
* come from the application, and an id such as `../../
|
|
17
|
+
* come from the application, and an id such as `../../bundles/x` must
|
|
18
18
|
* never leave `/records/<object>/`.
|
|
19
19
|
*/
|
|
20
20
|
export declare function recordsPath(objectName: string, ...segments: string[]): string;
|
|
21
21
|
//#endregion
|
|
22
|
-
export { type AttachToRecordInput, type AttachToRecordResult, type Attribute, 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
|
|
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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
|
|
2
|
-
import { _ as StandardsRequestError, g as StandardsConfigurationError, h as StandardsAuthError, m as
|
|
3
|
-
import { A as
|
|
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";
|
|
4
4
|
import { encodePathSegment } from "@standards/schema/api";
|
|
5
|
-
import { Attribute, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, NotFoundError, ObjectDefinition, ObjectDefinition as ObjectDefinition$1, RecordAccessRole, RecordAudience, RecordMetadata,
|
|
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";
|
|
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
|
|
@@ -14,9 +14,9 @@ export declare function reviveRecord<T extends Record<string, unknown>>(definiti
|
|
|
14
14
|
//#region src/path.d.ts
|
|
15
15
|
/**
|
|
16
16
|
* Every caller-supplied path segment is percent-encoded: `objectName` and `id`
|
|
17
|
-
* come from the application, and an id such as `../../
|
|
17
|
+
* come from the application, and an id such as `../../bundles/x` must
|
|
18
18
|
* never leave `/records/<object>/`.
|
|
19
19
|
*/
|
|
20
20
|
export declare function recordsPath(objectName: string, ...segments: string[]): string;
|
|
21
21
|
//#endregion
|
|
22
|
-
export { type AttachToRecordInput, type AttachToRecordResult, type Attribute, 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
|
|
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 };
|
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-
|
|
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}});
|
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{
|
|
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};
|
package/dist/testing.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
|
|
2
|
-
import "./http-transport-
|
|
3
|
-
import {
|
|
4
|
-
import { ExtractRecord, ExtractRecordInputStrict, FilterRule, ObjectDefinition } from "@standards/schema";
|
|
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";
|
|
4
|
+
import { ExtractRecord, ExtractRecordInputStrict, FilterRule, ObjectBuilderLike, ObjectDefinition } from "@standards/schema";
|
|
5
5
|
//#region src/testing/record-filters.d.ts
|
|
6
6
|
/**
|
|
7
7
|
* A filter rule the in-memory workspace does not serve. The server answers
|
|
@@ -26,9 +26,9 @@ type NameOf<B> = B extends {
|
|
|
26
26
|
name: infer N extends string;
|
|
27
27
|
};
|
|
28
28
|
} ? N : never;
|
|
29
|
-
/** The object names
|
|
30
|
-
export type ObjectNameOf<TObjects extends readonly ObjectBuilderLike
|
|
31
|
-
type BuilderNamed<TObjects extends readonly ObjectBuilderLike
|
|
29
|
+
/** The object names the bundles declare — what `seed` and `records` take. */
|
|
30
|
+
export type ObjectNameOf<TObjects extends readonly ObjectBuilderLike[]> = NameOf<TObjects[number]>;
|
|
31
|
+
type BuilderNamed<TObjects extends readonly ObjectBuilderLike[], TName> = Extract<TObjects[number], {
|
|
32
32
|
_types: {
|
|
33
33
|
name: TName;
|
|
34
34
|
};
|
|
@@ -45,7 +45,7 @@ export type TestSeed<TBuilder> = Omit<ExtractRecordInputStrict<TBuilder>, Pinned
|
|
|
45
45
|
createdAt?: Date | string;
|
|
46
46
|
updatedAt?: Date | string;
|
|
47
47
|
};
|
|
48
|
-
export interface TestStandards<TObjects extends readonly ObjectBuilderLike
|
|
48
|
+
export interface TestStandards<TObjects extends readonly ObjectBuilderLike[]> {
|
|
49
49
|
/** The real client over the in-memory workspace: pass it wherever the app takes `createStandards`'s. */
|
|
50
50
|
db: Standards & ObjectsOf<TObjects>;
|
|
51
51
|
/**
|
|
@@ -59,7 +59,7 @@ export interface TestStandards<TObjects extends readonly ObjectBuilderLike$1[]>
|
|
|
59
59
|
failNextRequestWith(status: number, failure?: InjectedFailure): void;
|
|
60
60
|
}
|
|
61
61
|
/**
|
|
62
|
-
* An in-memory Standards workspace for tests, typed by the app's
|
|
62
|
+
* An in-memory Standards workspace for tests, typed by the app's bundles.
|
|
63
63
|
*
|
|
64
64
|
* `db` is the real client — the same query layer, revival and bulk chunking an
|
|
65
65
|
* app ships — over a transport that answers like the records API: pages of 20
|
|
@@ -68,12 +68,12 @@ export interface TestStandards<TObjects extends readonly ObjectBuilderLike$1[]>
|
|
|
68
68
|
* `UnsupportedFilterOperatorError`; any other route answers `501`.
|
|
69
69
|
*
|
|
70
70
|
* @example
|
|
71
|
-
* const { db, seed } = createTestStandards({
|
|
71
|
+
* const { db, seed } = createTestStandards({ bundles: [helpdesk] });
|
|
72
72
|
* seed("tickets", [{ title: "Login fails" }]);
|
|
73
73
|
* await db.tickets.contains("title", "login").fetch();
|
|
74
74
|
*/
|
|
75
|
-
export declare function createTestStandards<const
|
|
76
|
-
|
|
77
|
-
}): TestStandards<
|
|
75
|
+
export declare function createTestStandards<const TBundles extends readonly AnyBundle[]>(config: {
|
|
76
|
+
bundles: TBundles;
|
|
77
|
+
}): TestStandards<ObjectsOfBundles<TBundles>>;
|
|
78
78
|
//#endregion
|
|
79
79
|
export type { InjectedFailure };
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
|
|
2
|
-
import "./http-transport-
|
|
3
|
-
import {
|
|
4
|
-
import { ExtractRecord, ExtractRecordInputStrict, FilterRule, ObjectDefinition } from "@standards/schema";
|
|
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";
|
|
4
|
+
import { ExtractRecord, ExtractRecordInputStrict, FilterRule, ObjectBuilderLike, ObjectDefinition } from "@standards/schema";
|
|
5
5
|
//#region src/testing/record-filters.d.ts
|
|
6
6
|
/**
|
|
7
7
|
* A filter rule the in-memory workspace does not serve. The server answers
|
|
@@ -26,9 +26,9 @@ type NameOf<B> = B extends {
|
|
|
26
26
|
name: infer N extends string;
|
|
27
27
|
};
|
|
28
28
|
} ? N : never;
|
|
29
|
-
/** The object names
|
|
30
|
-
export type ObjectNameOf<TObjects extends readonly ObjectBuilderLike
|
|
31
|
-
type BuilderNamed<TObjects extends readonly ObjectBuilderLike
|
|
29
|
+
/** The object names the bundles declare — what `seed` and `records` take. */
|
|
30
|
+
export type ObjectNameOf<TObjects extends readonly ObjectBuilderLike[]> = NameOf<TObjects[number]>;
|
|
31
|
+
type BuilderNamed<TObjects extends readonly ObjectBuilderLike[], TName> = Extract<TObjects[number], {
|
|
32
32
|
_types: {
|
|
33
33
|
name: TName;
|
|
34
34
|
};
|
|
@@ -45,7 +45,7 @@ export type TestSeed<TBuilder> = Omit<ExtractRecordInputStrict<TBuilder>, Pinned
|
|
|
45
45
|
createdAt?: Date | string;
|
|
46
46
|
updatedAt?: Date | string;
|
|
47
47
|
};
|
|
48
|
-
export interface TestStandards<TObjects extends readonly ObjectBuilderLike
|
|
48
|
+
export interface TestStandards<TObjects extends readonly ObjectBuilderLike[]> {
|
|
49
49
|
/** The real client over the in-memory workspace: pass it wherever the app takes `createStandards`'s. */
|
|
50
50
|
db: Standards & ObjectsOf<TObjects>;
|
|
51
51
|
/**
|
|
@@ -59,7 +59,7 @@ export interface TestStandards<TObjects extends readonly ObjectBuilderLike$1[]>
|
|
|
59
59
|
failNextRequestWith(status: number, failure?: InjectedFailure): void;
|
|
60
60
|
}
|
|
61
61
|
/**
|
|
62
|
-
* An in-memory Standards workspace for tests, typed by the app's
|
|
62
|
+
* An in-memory Standards workspace for tests, typed by the app's bundles.
|
|
63
63
|
*
|
|
64
64
|
* `db` is the real client — the same query layer, revival and bulk chunking an
|
|
65
65
|
* app ships — over a transport that answers like the records API: pages of 20
|
|
@@ -68,12 +68,12 @@ export interface TestStandards<TObjects extends readonly ObjectBuilderLike$1[]>
|
|
|
68
68
|
* `UnsupportedFilterOperatorError`; any other route answers `501`.
|
|
69
69
|
*
|
|
70
70
|
* @example
|
|
71
|
-
* const { db, seed } = createTestStandards({
|
|
71
|
+
* const { db, seed } = createTestStandards({ bundles: [helpdesk] });
|
|
72
72
|
* seed("tickets", [{ title: "Login fails" }]);
|
|
73
73
|
* await db.tickets.contains("title", "login").fetch();
|
|
74
74
|
*/
|
|
75
|
-
export declare function createTestStandards<const
|
|
76
|
-
|
|
77
|
-
}): TestStandards<
|
|
75
|
+
export declare function createTestStandards<const TBundles extends readonly AnyBundle[]>(config: {
|
|
76
|
+
bundles: TBundles;
|
|
77
|
+
}): TestStandards<ObjectsOfBundles<TBundles>>;
|
|
78
78
|
//#endregion
|
|
79
79
|
export type { InjectedFailure };
|
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-DHbErYa4.js"),t=require("./create-standards-DVK0prD0.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);return i&&s.has(i.type)?(i.options??[]).find(e=>e.value===r)?.label??r:r}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=textOf(a)===null,l=textOf(s)===null;if(c||l){if(c&&l)continue;return c?1:-1}let u=compare(a,s,n!==void 0&&o.has(n))??0;if(u!==0)return i.direction===`desc`?-u:u}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.g(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.m(t,n,r):new e.g(t,n,r)}function asTheServerValidates(t){try{t()}catch(t){throw t instanceof n.ValidationError?new e.g(400,t.message,t.code):t}}function notServed(t,n){return new e.g(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.schema.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.g(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.g(404,readNotFound(n),u);return r}function requireWritable(t,n){if(!objectOf(t).records.some(e=>e.id===n))throw new e.g(404,writeNotFound(n),u)}function update(t,n,r){let i=objectOf(t).records.find(e=>e.id===n);if(!i)throw new e.g(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.g(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.g(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.g))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.g(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.g))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.g(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=createInMemoryApi({schema:e.schema}),flatten=(e,r)=>t.o(n.definitionOf(e),JSON.parse(JSON.stringify(r)));return{db:t.t(n.transport,e.schema),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)}}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-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);return i&&s.has(i.type)?(i.options??[]).find(e=>e.value===r)?.label??r:r}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=textOf(a)===null,l=textOf(s)===null;if(c||l){if(c&&l)continue;return c?1:-1}let u=compare(a,s,n!==void 0&&o.has(n))??0;if(u!==0)return i.direction===`desc`?-u:u}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;
|
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{g as e,m as t}from"./http-transport-17TmxnFl.mjs";import{a as n,o as r,s as i,t as a}from"./create-standards-p0dGJXSu.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);return i&&m.has(i.type)?(i.options??[]).find(e=>e.value===r)?.label??r:r}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=textOf(a)===null,c=textOf(o)===null;if(s||c){if(s&&c)continue;return s?1:-1}let l=compare(a,o,n!==void 0&&p.has(n))??0;if(l!==0)return i.direction===`desc`?-l:l}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.schema.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=createInMemoryApi({schema:e.schema}),flatten=(e,n)=>r(t.definitionOf(e),JSON.parse(JSON.stringify(n)));return{db:a(t.transport,e.schema),seed:(e,n)=>t.seed(e,n).map(t=>flatten(e,t)),records:e=>t.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,n)=>t.failNextRequestWith(e,n)}}export{UnsupportedFilterOperatorError,createTestStandards};
|
|
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);return i&&m.has(i.type)?(i.options??[]).find(e=>e.value===r)?.label??r:r}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=textOf(a)===null,c=textOf(o)===null;if(s||c){if(s&&c)continue;return s?1:-1}let l=compare(a,o,n!==void 0&&p.has(n))??0;if(l!==0)return i.direction===`desc`?-l:l}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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@standards/client",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.394",
|
|
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.
|
|
50
|
+
"@standards/schema": "1.0.0-alpha.394"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@types/node": "^25.6.0",
|
|
@@ -1,2 +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-DHbErYa4.js");let t=require("@standards/schema"),n=require("@standards/schema/api");function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const r=new Set([`from`,`files`,`documents`,`schema`]);function assertObjectKeys(t){let n=new Map;for(let i of t){if(i.includes(`--`)||i.endsWith(`-`))throw new e.h(`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.h(`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.h(`Objects "${a}" and "${i}" both map to the client key "${t}". Rename one of them.`);n.set(t,i)}}function buildView(e){let n=`build`in e&&typeof e.build==`function`?e.build():e,r=`kind`in n&&n.kind===`view`?n.definition:n,i=t.contentViewDefinitionSchema.safeParse(r);if(i.success)return i.data;let a=typeof r==`object`&&r&&`name`in r?String(r.name):`(unnamed)`,o=t.ValidationError.fromZodErrors(i.error.issues.map(e=>({path:e.path.map(String),message:e.message})));throw new t.ValidationError(`View "${a}" is invalid. ${o.message}`,o.errors)}async function hashSchemaSource(e){let n=new TextEncoder().encode((0,t.canonicalStringify)(e)),r=await crypto.subtle.digest(`SHA-256`,n);return Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,`0`)).join(``)}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)}function defineSchemaSource(e){return{id:e.id??null,builders:e.objects,views:e.views??[],label:e.label??null,icon:e.icon??null}}const i=new WeakMap;async function resolveOnce(e){e.id!==null&&(0,t.assertSchemaSourceId)(e.id);let n=(0,t.parseSchemaGroupPresentation)({label:e.label??void 0,icon:e.icon??void 0}),r=e.builders.map(e=>e.build());assertObjectNames(r.map(e=>e.name));let i=e.views.map(buildView);return{id:e.id,hash:await hashSchemaSource({objects:r,views:i}),objects:r,views:i,label:n.label??null,icon:n.icon??null}}function resolveSchemaSource(e){let t=i.get(e);return t===void 0&&(t=resolveOnce(e),i.set(e,t)),t}function sourceIdFromPackageName(n){let r=n.toLowerCase().replace(/^@/,``).replace(/\//g,`-`);try{(0,t.assertSchemaSourceId)(r)}catch{throw new e.h(`package.json name "${n}" is not a usable schema source id. Add id: "<lowercase-slug>" to defineSchemaSource.`)}return r}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}}const a=[`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 a)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 o=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.h(`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 s=new WeakMap;function definitionOf(e){let t=s.get(e);if(t)return t;let n=e.build();return s.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new o(e,t,null);let n=definitionOf(t);return new o(e,n.name,n)}async function syncSchemaSource(t,n,r={}){let i=await resolveSchemaSource(n);if(i.id===null)throw new e.h(`This schema source has no id. Add id: "<lowercase-slug>" to defineSchemaSource, or derive one with sourceIdFromPackageName(packageJson.name).`);let a=`/schema/sources/${encodeURIComponent(i.id)}`,o;try{o=await t.get(a)}catch(t){if(t instanceof e.g&&t.status===404)o=null;else throw t}if(o?.hash===i.hash&&(i.label===null||(o.label??null)===i.label)&&(i.icon===null||(o.icon??null)===i.icon))return{applied:!1,hash:i.hash};let s={hash:i.hash,objects:i.objects,views:i.views};i.label!==null&&(s.label=i.label),i.icon!==null&&(s.icon=i.icon),r.resolutions&&r.resolutions.length>0&&(s.resolutions=r.resolutions);try{return await t.put(a,s)}catch(t){throw t instanceof e.g&&t.status===409?new e.f(t.status,t.message,t.code):t instanceof e.g&&t.status===400?new e.p(t.status,t.message,t.code):t}}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.h(`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.h(`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.h(`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.h(`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{schema:n,...r}=t;return buildStandards(e.n(resolveConfig(r)),n)}function buildStandards(e,t){let n={schema:{sync:(t,n)=>syncSchemaSource(e,t,n)},from:t=>createRecordsQuery(e,t),files:createFilesApi(e),documents:createDocumentsApi(e)};if(t!==void 0){let r=t.builders.map(e=>definitionOf(e).name);assertObjectNames(r),t.builders.forEach((t,i)=>{n[objectKeyOf(r[i])]=createRecordsQuery(e,t)})}return n}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return definitionOf}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return createFilesApi}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return hashSchemaSource}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return resolveSchemaSource}}),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,"p",{enumerable:!0,get:function(){return sourceIdFromPackageName}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return syncSchemaSource}}),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 defineSchemaSource}});
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
import{f as e,g as t,h as n,n as r,p as i}from"./http-transport-17TmxnFl.mjs";import{AggregateValidationError as a,DuplicateError as o,RecordQuery as s,SchemaErrorCode as c,ValidationError as l,assertSchemaSourceId as u,canonicalStringify as d,contentViewDefinitionSchema as f,parseSchemaGroupPresentation as p}from"@standards/schema";import{buildOperationPath as m,documentsOperations as h,filesOperations as g,recordAccessOperations as _,recordsOperations as v}from"@standards/schema/api";function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const y=new Set([`from`,`files`,`documents`,`schema`]);function assertObjectKeys(e){let t=new Map;for(let r of e){if(r.includes(`--`)||r.endsWith(`-`))throw new n(`Object "${r}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let e=objectKeyOf(r);if(y.has(e))throw new n(`Object "${r}" maps to the client key "${e}", which is reserved. Rename the object.`);let i=t.get(e);if(i!==void 0&&i!==r)throw new n(`Objects "${i}" and "${r}" both map to the client key "${e}". Rename one of them.`);t.set(e,r)}}function buildView(e){let t=`build`in e&&typeof e.build==`function`?e.build():e,n=`kind`in t&&t.kind===`view`?t.definition:t,r=f.safeParse(n);if(r.success)return r.data;let i=typeof n==`object`&&n&&`name`in n?String(n.name):`(unnamed)`,a=l.fromZodErrors(r.error.issues.map(e=>({path:e.path.map(String),message:e.message})));throw new l(`View "${i}" is invalid. ${a.message}`,a.errors)}async function hashSchemaSource(e){let t=new TextEncoder().encode(d(e)),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``)}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)}function defineSchemaSource(e){return{id:e.id??null,builders:e.objects,views:e.views??[],label:e.label??null,icon:e.icon??null}}const b=new WeakMap;async function resolveOnce(e){e.id!==null&&u(e.id);let t=p({label:e.label??void 0,icon:e.icon??void 0}),n=e.builders.map(e=>e.build());assertObjectNames(n.map(e=>e.name));let r=e.views.map(buildView);return{id:e.id,hash:await hashSchemaSource({objects:n,views:r}),objects:n,views:r,label:t.label??null,icon:t.icon??null}}function resolveSchemaSource(e){let t=b.get(e);return t===void 0&&(t=resolveOnce(e),b.set(e,t)),t}function sourceIdFromPackageName(e){let t=e.toLowerCase().replace(/^@/,``).replace(/\//g,`-`);try{u(t)}catch{throw new n(`package.json name "${e}" is not a usable schema source id. Add id: "<lowercase-slug>" to defineSchemaSource.`)}return 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=m(v.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(m(h.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(g.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(g.signedUrl,{id:t});return n}return{upload,getDownloadUrl}}const x=[`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 x)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 S=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,t={}){if(!this.transport.postRaw)throw new n(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:r,sorts:i}=this.body(),{ids:a,locale:o,filename:s}=t;return await this.transport.postRaw(m(v.export,{objectName:this.objectName}),{q:this.state.search??``,...r?{filters:r}:{},...i?{sorts:i}:{},columns:e,...a?{ids:a}:{},...o?{locale:o}:{},timezone:t.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...s?{filename:s}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new 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(m(v.aggregate,{objectName:this.objectName}),t)}async fetchPage(){let e=this.state.search===void 0?`list`:`search`,t=await this.transport.post(m(v[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(m(v.get,{objectName:this.objectName,id:e}));return this.revive(t)}async create(e){let t=await this.transport.post(m(v.create,{objectName:this.objectName}),{data:serializeInput(e)});return this.revive(t)}async update(e,t){let n=await this.transport.put(m(v.update,{objectName:this.objectName,id:e}),serializeInput(t));return this.revive(n)}async delete(e){await this.transport.delete(m(v.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(m(v.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(m(v.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(m(v.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(m(_.list,{objectName:this.objectName,recordId:e}))}async grantAccess(e,t,n){return await this.transport.put(m(_.grant,{objectName:this.objectName,recordId:e,actorId:t}),{role:n})}async revokeAccess(e,t){return await this.transport.delete(m(_.revoke,{objectName:this.objectName,recordId:e,actorId:t}))}async clearAccess(e){return await this.transport.delete(m(_.clear,{objectName:this.objectName,recordId:e}))}};const C=new WeakMap;function definitionOf(e){let t=C.get(e);if(t)return t;let n=e.build();return C.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new S(e,t,null);let n=definitionOf(t);return new S(e,n.name,n)}async function syncSchemaSource(r,a,o={}){let s=await resolveSchemaSource(a);if(s.id===null)throw new n(`This schema source has no id. Add id: "<lowercase-slug>" to defineSchemaSource, or derive one with sourceIdFromPackageName(packageJson.name).`);let c=`/schema/sources/${encodeURIComponent(s.id)}`,l;try{l=await r.get(c)}catch(e){if(e instanceof t&&e.status===404)l=null;else throw e}if(l?.hash===s.hash&&(s.label===null||(l.label??null)===s.label)&&(s.icon===null||(l.icon??null)===s.icon))return{applied:!1,hash:s.hash};let u={hash:s.hash,objects:s.objects,views:s.views};s.label!==null&&(u.label=s.label),s.icon!==null&&(u.icon=s.icon),o.resolutions&&o.resolutions.length>0&&(u.resolutions=o.resolutions);try{return await r.put(c,u)}catch(n){throw n instanceof t&&n.status===409?new e(n.status,n.message,n.code):n instanceof t&&n.status===400?new i(n.status,n.message,n.code):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 n(`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 n(`createStandards needs an explicit baseUrl in a browser context: STANDARDS_API_URL and STANDARDS_API_KEY are never read from the environment there.`);return{...e,baseUrl:e.baseUrl,apiKey:``}}let t=readEnvironment(),r=e.baseUrl??t.baseUrl;if(r===void 0)throw new n(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let i=e.apiKey??t.apiKey;if(i===void 0)throw new n(`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{schema:t,...n}=e;return buildStandards(r(resolveConfig(n)),t)}function buildStandards(e,t){let n={schema:{sync:(t,n)=>syncSchemaSource(e,t,n)},from:t=>createRecordsQuery(e,t),files:createFilesApi(e),documents:createDocumentsApi(e)};if(t!==void 0){let r=t.builders.map(e=>definitionOf(e).name);assertObjectNames(r),t.builders.forEach((t,i)=>{n[objectKeyOf(r[i])]=createRecordsQuery(e,t)})}return n}export{definitionOf as a,createFilesApi as c,hashSchemaSource as d,resolveSchemaSource as f,createRecordsQuery as i,createDocumentsApi as l,createStandards as n,reviveRecord as o,sourceIdFromPackageName as p,syncSchemaSource as r,serializeInput as s,buildStandards as t,defineSchemaSource as u};
|