@standards/client 1.0.0-alpha.421 → 1.0.0-alpha.426
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/dist/{app-d25WfBqA.js → app-BgWz3r5k.js} +1 -1
- package/dist/{app-CjHQKAwu.mjs → app-TJt8rk9y.mjs} +1 -1
- package/dist/{app-TCIe_XWO.d.mts → app-_CiXRLoD.d.mts} +15 -5
- package/dist/{app-TCIe_XWO.d.ts → app-_CiXRLoD.d.ts} +15 -5
- package/dist/app.d.mts +2 -2
- package/dist/app.d.ts +2 -2
- package/dist/app.js +1 -1
- package/dist/app.mjs +1 -1
- package/dist/create-standards-2D3Tmvj1.js +4 -0
- package/dist/create-standards-CZ_ZYNz8.mjs +4 -0
- package/dist/{create-standards-B4fQnzl5.d.mts → create-standards-De7-xdtZ.d.ts} +28 -4
- package/dist/{create-standards-YjhWkQYe.d.ts → create-standards-lDN6ru8u.d.mts} +28 -4
- package/dist/index.d.mts +27 -4
- package/dist/index.d.ts +27 -4
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/testing.d.mts +2 -2
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/create-standards-CqOOm8eg.js +0 -4
- package/dist/create-standards-orKjtGR6.mjs +0 -4
|
@@ -6,4 +6,4 @@ let e=require("@standards/schema"),t=require("@standards/schema/api");function s
|
|
|
6
6
|
|
|
7
7
|
`);for(;c!==-1;){let e=o.slice(0,c);o=o.slice(c+2);let r=handleFrame(e);if(r===`delivered`&&(s=!0),t)return{delivered:s,end:`clean`};if(r===`malformed`)return n.abort(),{delivered:s,end:`malformed`};if(r===`lease-ended`)return{delivered:s,end:`lease-ended`};c=o.indexOf(`
|
|
8
8
|
|
|
9
|
-
`)}}}catch{return{delivered:s,end:`failed`}}finally{i.releaseLock()}}async function afterFailedOpen(t,n,r){if(isCursorExpired(t))try{return await e.onExpired(),r?`back-off`:`reopen`}catch{return`back-off`}return t instanceof StandardsRequestError?isTerminalRefusal(t)?(close(),e.onStatus(`error`,t),`stop`):t.status===401?(e.onStatus(`auth-blocked`,t),await waitForAuthChange(n),`reopen`):`back-off`:`back-off`}let u,d=0;async function rehydratedPastStall(t){if(e.cursor()!==t||(d=u===t?d+1:1,u=t,d<3))return!1;u=void 0,d=0;try{return await e.onExpired(),!0}catch{return!1}}function delayAfter(e,t){return e===`lease-ended`?0:e===`clean`||e===`malformed`?o:i[Math.min(t,i.length-1)]??5e3}async function run(){let r=!0,i=0,a=!1;for(;!t;){e.onStatus(r?`connecting`:`reconnecting`),r=!1;let o=new AbortController;n=o;let c=s,l=`failed`;try{let n=await e.open(e.sessionId,e.cursor(),o.signal,()=>{c=s});if(t)return;e.onStatus(`connected`);let r=e.cursor(),u=await consume(n,o);if(l=u.end,l===`malformed`&&await rehydratedPastStall(r)){if(t)return;continue}u.delivered&&(i=0,a=!1)}catch(e){if(t)return;let n=isCursorExpired(e),r=await afterFailedOpen(e,c,a);if(a=n,r===`stop`||t)return;if(r===`reopen`)continue}if(t)return;e.onStatus(`reconnecting`);let u=delayAfter(l,i);l===`failed`&&(i+=1),u>0&&await sleep(u)}}return run().catch(()=>void 0),{close,wake:endWait}}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));else 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)}else{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 r=await e.uploadAuthorization?.()??null;return await sendWithProgress({url:buildUrl(a,o),method:n.method,headers:withoutContentType({...headerRecord(await e.headers?.()),...c}),token:r,form:multipartBody(n.upload.field,s),onUploadProgress:i.onUploadProgress,signal:i.signal},e=>(0,t.decodeOperationOutput)(n,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:async e=>(0,t.decodeOperationOutput)(n,await readJson(e));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})}function asStrings(e){let t=Object.entries(e??{}).flatMap(([e,t])=>t==null?[]:[[e,String(t)]]);return Object.fromEntries(t)}async function uploadedPart(e){let t=e.name;return{name:typeof t==`string`?t:`blob`,mimeType:e.type===``?`application/octet-stream`:e.type,size:e.size,content:new Uint8Array(await e.arrayBuffer())}}async function wireRequest(e,n){let{query:r,body:i,headers:a}=(0,t.splitOperationInput)(e,n),o=Object.fromEntries((0,t.pathParamNames)(e.path).map(e=>[e,String(n[e])])),s=Object.fromEntries(Object.entries(a??{}).map(([e,t])=>[e.toLowerCase(),t])),c={params:o,query:asStrings(r),headers:s};if(e.upload===void 0)return{...c,body:i===void 0?void 0:JSON.parse(JSON.stringify(i))};let{[e.upload.field]:l,...u}=i??{},d=l==null?[]:Array.isArray(l)?l:[l];return{...c,body:asStrings(u),uploads:await Promise.all(d.map(uploadedPart))}}function downloaded(e){let t=typeof e.content==`string`?e.content:new Uint8Array(e.content);return{blob:new Blob([t],{type:e.mimeType}),filename:e.filename,mimeType:e.mimeType}}function createInProcessTransport(e){async function call(n,r,i={}){if(i.signal?.throwIfAborted(),n.response===`events`)throw Error(`Operation ${n.name} streams over HTTP only`);let a=await wireRequest(n,r??{}),o;try{o=await e.execute(n,a)}catch(e){throw(0,t.isOperationRefused)(e)?refusalOf(e.status,JSON.stringify(e.body)):e}if(n.response===`bytes`)return downloaded(o);let s=o===void 0?null:JSON.parse(JSON.stringify(o));return(0,t.decodeOperationOutput)(n,s)}return{call,stream:e=>Promise.reject(/* @__PURE__ */ Error(`Operation ${e.name} streams over HTTP only`))}}function createAppClient(e){let n={},r=Object.values(t.appOperationGroups);for(let i of r.flatMap(e=>Object.values(e))){let r=(0,t.operationGroup)(i),a=i.name.slice(r.length+1);n[r]??={},n[r][a]=(t,n)=>i.response===`events`?e.stream(i,t,n):e.call(i,t,n)}return n}Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return isDraftRevisionConflict}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return readRefusal}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return isViewNotFound}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return parseContentDispositionFilename}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return BundleConflictError}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return BundleValidationError}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return draftConflictChanges}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return StandardsRequestError}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return createTransport}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return StandardsConfigurationError}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createInProcessTransport}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return refusalOf}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return StandardsAuthError}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return createHttpTransport}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return recordsPath}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return createAppClient}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return openAgentStream}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return isObjectNotFound}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return schemaApiErrorCode}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return isPermanentRefusal}});
|
|
9
|
+
`)}}}catch{return{delivered:s,end:`failed`}}finally{i.releaseLock()}}async function afterFailedOpen(t,n,r){if(isCursorExpired(t))try{return await e.onExpired(),r?`back-off`:`reopen`}catch{return`back-off`}return t instanceof StandardsRequestError?isTerminalRefusal(t)?(close(),e.onStatus(`error`,t),`stop`):t.status===401?(e.onStatus(`auth-blocked`,t),await waitForAuthChange(n),`reopen`):`back-off`:`back-off`}let u,d=0;async function rehydratedPastStall(t){if(e.cursor()!==t||(d=u===t?d+1:1,u=t,d<3))return!1;u=void 0,d=0;try{return await e.onExpired(),!0}catch{return!1}}function delayAfter(e,t){return e===`lease-ended`?0:e===`clean`||e===`malformed`?o:i[Math.min(t,i.length-1)]??5e3}async function run(){let r=!0,i=0,a=!1;for(;!t;){e.onStatus(r?`connecting`:`reconnecting`),r=!1;let o=new AbortController;n=o;let c=s,l=`failed`;try{let n=await e.open(e.sessionId,e.cursor(),o.signal,()=>{c=s});if(t)return;e.onStatus(`connected`);let r=e.cursor(),u=await consume(n,o);if(l=u.end,l===`malformed`&&await rehydratedPastStall(r)){if(t)return;continue}u.delivered&&(i=0,a=!1)}catch(e){if(t)return;let n=isCursorExpired(e),r=await afterFailedOpen(e,c,a);if(a=n,r===`stop`||t)return;if(r===`reopen`)continue}if(t)return;e.onStatus(`reconnecting`);let u=delayAfter(l,i);l===`failed`&&(i+=1),u>0&&await sleep(u)}}return run().catch(()=>void 0),{close,wake:endWait}}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));else 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)}else{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 r=await e.uploadAuthorization?.()??null;return await sendWithProgress({url:buildUrl(a,o),method:n.method,headers:withoutContentType({...headerRecord(await e.headers?.()),...c}),token:r,form:multipartBody(n.upload.field,s),onUploadProgress:i.onUploadProgress,signal:i.signal},e=>(0,t.decodeOperationOutput)(n,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:async e=>(0,t.decodeOperationOutput)(n,await readJson(e));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})}function asStrings(e){let t=Object.entries(e??{}).flatMap(([e,t])=>t==null?[]:[[e,String(t)]]);return Object.fromEntries(t)}async function uploadedPart(e){let t=e.name;return{name:typeof t==`string`?t:`blob`,mimeType:e.type===``?`application/octet-stream`:e.type,size:e.size,content:new Uint8Array(await e.arrayBuffer())}}async function wireRequest(e,n){let{query:r,body:i,headers:a}=(0,t.splitOperationInput)(e,n),o=Object.fromEntries((0,t.pathParamNames)(e.path).map(e=>[e,String(n[e])])),s=Object.fromEntries(Object.entries(a??{}).map(([e,t])=>[e.toLowerCase(),t])),c={params:o,query:asStrings(r),headers:s};if(e.upload===void 0)return{...c,body:i===void 0?void 0:JSON.parse(JSON.stringify(i))};let{[e.upload.field]:l,...u}=i??{},d=l==null?[]:Array.isArray(l)?l:[l];return{...c,body:asStrings(u),uploads:await Promise.all(d.map(uploadedPart))}}function downloaded(e){let t=typeof e.content==`string`?e.content:new Uint8Array(e.content);return{blob:new Blob([t],{type:e.mimeType}),filename:e.filename,mimeType:e.mimeType}}function createInProcessTransport(e){return transportActingAs(e,void 0)}function transportActingAs(e,n){async function call(r,i,a={}){if(a.signal?.throwIfAborted(),r.response===`events`)throw Error(`Operation ${r.name} streams over HTTP only`);let o=await wireRequest(r,i??{}),s;try{s=await e.execute(r,o,n)}catch(e){throw(0,t.isOperationRefused)(e)?refusalOf(e.status,JSON.stringify(e.body)):e}if(r.response===`bytes`)return downloaded(s);let c=s===void 0?null:JSON.parse(JSON.stringify(s));return(0,t.decodeOperationOutput)(r,c)}return{call,stream:e=>Promise.reject(/* @__PURE__ */ Error(`Operation ${e.name} streams over HTTP only`)),withCaller:t=>transportActingAs(e,t)}}function createAppClient(e){let n={},r=Object.values(t.appOperationGroups);for(let i of r.flatMap(e=>Object.values(e))){let r=(0,t.operationGroup)(i),a=i.name.slice(r.length+1);n[r]??={},n[r][a]=(t,n)=>i.response===`events`?e.stream(i,t,n):e.call(i,t,n)}return n}Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return isDraftRevisionConflict}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return readRefusal}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return isViewNotFound}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return parseContentDispositionFilename}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return BundleConflictError}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return BundleValidationError}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return draftConflictChanges}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return StandardsRequestError}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return createTransport}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return StandardsConfigurationError}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createInProcessTransport}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return refusalOf}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return StandardsAuthError}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return createHttpTransport}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return recordsPath}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return createAppClient}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return openAgentStream}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return isObjectNotFound}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return schemaApiErrorCode}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return isPermanentRefusal}});
|
|
@@ -6,4 +6,4 @@ import{DRAFT_CONFLICT_KINDS as e,SchemaErrorCode as t,ValidationError as n,isPla
|
|
|
6
6
|
|
|
7
7
|
`);for(;c!==-1;){let e=o.slice(0,c);o=o.slice(c+2);let r=handleFrame(e);if(r===`delivered`&&(s=!0),t)return{delivered:s,end:`clean`};if(r===`malformed`)return n.abort(),{delivered:s,end:`malformed`};if(r===`lease-ended`)return{delivered:s,end:`lease-ended`};c=o.indexOf(`
|
|
8
8
|
|
|
9
|
-
`)}}}catch{return{delivered:s,end:`failed`}}finally{i.releaseLock()}}async function afterFailedOpen(t,n,r){if(isCursorExpired(t))try{return await e.onExpired(),r?`back-off`:`reopen`}catch{return`back-off`}return t instanceof StandardsRequestError?isTerminalRefusal(t)?(close(),e.onStatus(`error`,t),`stop`):t.status===401?(e.onStatus(`auth-blocked`,t),await waitForAuthChange(n),`reopen`):`back-off`:`back-off`}let l,u=0;async function rehydratedPastStall(t){if(e.cursor()!==t||(u=l===t?u+1:1,l=t,u<3))return!1;l=void 0,u=0;try{return await e.onExpired(),!0}catch{return!1}}function delayAfter(e,t){return e===`lease-ended`?0:e===`clean`||e===`malformed`?a:p[Math.min(t,p.length-1)]??5e3}async function run(){let r=!0,i=0,a=!1;for(;!t;){e.onStatus(r?`connecting`:`reconnecting`),r=!1;let s=new AbortController;n=s;let c=o,l=`failed`;try{let n=await e.open(e.sessionId,e.cursor(),s.signal,()=>{c=o});if(t)return;e.onStatus(`connected`);let r=e.cursor(),u=await consume(n,s);if(l=u.end,l===`malformed`&&await rehydratedPastStall(r)){if(t)return;continue}u.delivered&&(i=0,a=!1)}catch(e){if(t)return;let n=isCursorExpired(e),r=await afterFailedOpen(e,c,a);if(a=n,r===`stop`||t)return;if(r===`reopen`)continue}if(t)return;e.onStatus(`reconnecting`);let u=delayAfter(l,i);l===`failed`&&(i+=1),u>0&&await sleep(u)}}return run().catch(()=>void 0),{close,wake:endWait}}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(o)].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));else 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,i=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,a,o){let s=buildUrl(e,a.params),c=(t.method??`GET`).toUpperCase(),l=a.maxRetries??(c===`GET`?r:0),u=a.timeoutMs===void 0?i:a.timeoutMs;for(let e=0;;e++){let r=e<l,i;try{i=await fetchOnce(s,t,u)}catch(n){if(r&&n instanceof TypeError&&!t.signal?.aborted){await backoff(e);continue}throw connectionFailure(n)}if(observe(i),i.status>=500&&r){let t=await readRefusalWithin(i);if(isPermanentRefusal(t))throw t;await backoff(e)}else{if(i.status===401&&n&&(i=await refreshAndRetry(s,t,u)??i),!i.ok){let e=await i.text().catch(()=>``);throw refusalFrom(i.status,e,a.plainTextRefusal??!1)}return await o(i)}}}async function stream(t,r,i={}){let{path:a,query:o,body:s,headers:c}=u(t,r??{}),l=buildUrl(a,o),{signal:d,onRequest:f}=i,p=e.fetch??fetch,attempt=async()=>(f?.(),await p(l,{method:t.method,body:s===void 0?void 0:JSON.stringify(s),signal:d,headers:await headersFor({headers:{...c,...i.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:i,query:o,body:s,headers:c}=u(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(i,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=>a(t,e?JSON.parse(e):null))}let l=t.upload===void 0?s===void 0?void 0:JSON.stringify(s):multipartBody(t.upload.field,s),d=t.response===`bytes`?readDownload:async e=>a(t,await readJson(e));return await send(i,{method:t.method,body:l,signal:r.signal,...c?{headers:c}:{},...r.keepalive?{keepalive:!0}:{}},{params:o,maxRetries:r.maxRetries,timeoutMs:r.timeoutMs},d)},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})}function asStrings(e){let t=Object.entries(e??{}).flatMap(([e,t])=>t==null?[]:[[e,String(t)]]);return Object.fromEntries(t)}async function uploadedPart(e){let t=e.name;return{name:typeof t==`string`?t:`blob`,mimeType:e.type===``?`application/octet-stream`:e.type,size:e.size,content:new Uint8Array(await e.arrayBuffer())}}async function wireRequest(e,t){let{query:n,body:r,headers:i}=u(e,t),a=Object.fromEntries(l(e.path).map(e=>[e,String(t[e])])),o=Object.fromEntries(Object.entries(i??{}).map(([e,t])=>[e.toLowerCase(),t])),s={params:a,query:asStrings(n),headers:o};if(e.upload===void 0)return{...s,body:r===void 0?void 0:JSON.parse(JSON.stringify(r))};let{[e.upload.field]:c,...d}=r??{},f=c==null?[]:Array.isArray(c)?c:[c];return{...s,body:asStrings(d),uploads:await Promise.all(f.map(uploadedPart))}}function downloaded(e){let t=typeof e.content==`string`?e.content:new Uint8Array(e.content);return{blob:new Blob([t],{type:e.mimeType}),filename:e.filename,mimeType:e.mimeType}}function createInProcessTransport(e){async function call(t,n,r={}){if(r.signal?.throwIfAborted(),t.response===`events`)throw Error(`Operation ${t.name} streams over HTTP only`);let i=await wireRequest(t,n??{}),o;try{o=await e.execute(t,i)}catch(e){throw s(e)?refusalOf(e.status,JSON.stringify(e.body)):e}if(t.response===`bytes`)return downloaded(o);let c=o===void 0?null:JSON.parse(JSON.stringify(o));return a(t,c)}return{call,stream:e=>Promise.reject(/* @__PURE__ */ Error(`Operation ${e.name} streams over HTTP only`))}}function createAppClient(e){let t={},n=Object.values(i);for(let r of n.flatMap(e=>Object.values(e))){let n=c(r),i=r.name.slice(n.length+1);t[n]??={},t[n][i]=(t,n)=>r.response===`events`?e.stream(r,t,n):e.call(r,t,n)}return t}export{isDraftRevisionConflict as _,readRefusal as a,isViewNotFound as b,parseContentDispositionFilename as c,BundleConflictError as d,BundleValidationError as f,draftConflictChanges as g,StandardsRequestError as h,createTransport as i,m as l,StandardsConfigurationError as m,createInProcessTransport as n,refusalOf as o,StandardsAuthError as p,createHttpTransport as r,recordsPath as s,createAppClient as t,openAgentStream as u,isObjectNotFound as v,schemaApiErrorCode as x,isPermanentRefusal as y};
|
|
9
|
+
`)}}}catch{return{delivered:s,end:`failed`}}finally{i.releaseLock()}}async function afterFailedOpen(t,n,r){if(isCursorExpired(t))try{return await e.onExpired(),r?`back-off`:`reopen`}catch{return`back-off`}return t instanceof StandardsRequestError?isTerminalRefusal(t)?(close(),e.onStatus(`error`,t),`stop`):t.status===401?(e.onStatus(`auth-blocked`,t),await waitForAuthChange(n),`reopen`):`back-off`:`back-off`}let l,u=0;async function rehydratedPastStall(t){if(e.cursor()!==t||(u=l===t?u+1:1,l=t,u<3))return!1;l=void 0,u=0;try{return await e.onExpired(),!0}catch{return!1}}function delayAfter(e,t){return e===`lease-ended`?0:e===`clean`||e===`malformed`?a:p[Math.min(t,p.length-1)]??5e3}async function run(){let r=!0,i=0,a=!1;for(;!t;){e.onStatus(r?`connecting`:`reconnecting`),r=!1;let s=new AbortController;n=s;let c=o,l=`failed`;try{let n=await e.open(e.sessionId,e.cursor(),s.signal,()=>{c=o});if(t)return;e.onStatus(`connected`);let r=e.cursor(),u=await consume(n,s);if(l=u.end,l===`malformed`&&await rehydratedPastStall(r)){if(t)return;continue}u.delivered&&(i=0,a=!1)}catch(e){if(t)return;let n=isCursorExpired(e),r=await afterFailedOpen(e,c,a);if(a=n,r===`stop`||t)return;if(r===`reopen`)continue}if(t)return;e.onStatus(`reconnecting`);let u=delayAfter(l,i);l===`failed`&&(i+=1),u>0&&await sleep(u)}}return run().catch(()=>void 0),{close,wake:endWait}}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(o)].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));else 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,i=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,a,o){let s=buildUrl(e,a.params),c=(t.method??`GET`).toUpperCase(),l=a.maxRetries??(c===`GET`?r:0),u=a.timeoutMs===void 0?i:a.timeoutMs;for(let e=0;;e++){let r=e<l,i;try{i=await fetchOnce(s,t,u)}catch(n){if(r&&n instanceof TypeError&&!t.signal?.aborted){await backoff(e);continue}throw connectionFailure(n)}if(observe(i),i.status>=500&&r){let t=await readRefusalWithin(i);if(isPermanentRefusal(t))throw t;await backoff(e)}else{if(i.status===401&&n&&(i=await refreshAndRetry(s,t,u)??i),!i.ok){let e=await i.text().catch(()=>``);throw refusalFrom(i.status,e,a.plainTextRefusal??!1)}return await o(i)}}}async function stream(t,r,i={}){let{path:a,query:o,body:s,headers:c}=u(t,r??{}),l=buildUrl(a,o),{signal:d,onRequest:f}=i,p=e.fetch??fetch,attempt=async()=>(f?.(),await p(l,{method:t.method,body:s===void 0?void 0:JSON.stringify(s),signal:d,headers:await headersFor({headers:{...c,...i.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:i,query:o,body:s,headers:c}=u(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(i,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=>a(t,e?JSON.parse(e):null))}let l=t.upload===void 0?s===void 0?void 0:JSON.stringify(s):multipartBody(t.upload.field,s),d=t.response===`bytes`?readDownload:async e=>a(t,await readJson(e));return await send(i,{method:t.method,body:l,signal:r.signal,...c?{headers:c}:{},...r.keepalive?{keepalive:!0}:{}},{params:o,maxRetries:r.maxRetries,timeoutMs:r.timeoutMs},d)},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})}function asStrings(e){let t=Object.entries(e??{}).flatMap(([e,t])=>t==null?[]:[[e,String(t)]]);return Object.fromEntries(t)}async function uploadedPart(e){let t=e.name;return{name:typeof t==`string`?t:`blob`,mimeType:e.type===``?`application/octet-stream`:e.type,size:e.size,content:new Uint8Array(await e.arrayBuffer())}}async function wireRequest(e,t){let{query:n,body:r,headers:i}=u(e,t),a=Object.fromEntries(l(e.path).map(e=>[e,String(t[e])])),o=Object.fromEntries(Object.entries(i??{}).map(([e,t])=>[e.toLowerCase(),t])),s={params:a,query:asStrings(n),headers:o};if(e.upload===void 0)return{...s,body:r===void 0?void 0:JSON.parse(JSON.stringify(r))};let{[e.upload.field]:c,...d}=r??{},f=c==null?[]:Array.isArray(c)?c:[c];return{...s,body:asStrings(d),uploads:await Promise.all(f.map(uploadedPart))}}function downloaded(e){let t=typeof e.content==`string`?e.content:new Uint8Array(e.content);return{blob:new Blob([t],{type:e.mimeType}),filename:e.filename,mimeType:e.mimeType}}function createInProcessTransport(e){return transportActingAs(e,void 0)}function transportActingAs(e,t){async function call(n,r,i={}){if(i.signal?.throwIfAborted(),n.response===`events`)throw Error(`Operation ${n.name} streams over HTTP only`);let o=await wireRequest(n,r??{}),c;try{c=await e.execute(n,o,t)}catch(e){throw s(e)?refusalOf(e.status,JSON.stringify(e.body)):e}if(n.response===`bytes`)return downloaded(c);let l=c===void 0?null:JSON.parse(JSON.stringify(c));return a(n,l)}return{call,stream:e=>Promise.reject(/* @__PURE__ */ Error(`Operation ${e.name} streams over HTTP only`)),withCaller:t=>transportActingAs(e,t)}}function createAppClient(e){let t={},n=Object.values(i);for(let r of n.flatMap(e=>Object.values(e))){let n=c(r),i=r.name.slice(n.length+1);t[n]??={},t[n][i]=(t,n)=>r.response===`events`?e.stream(r,t,n):e.call(r,t,n)}return t}export{isDraftRevisionConflict as _,readRefusal as a,isViewNotFound as b,parseContentDispositionFilename as c,BundleConflictError as d,BundleValidationError as f,draftConflictChanges as g,StandardsRequestError as h,createTransport as i,m as l,StandardsConfigurationError as m,createInProcessTransport as n,refusalOf as o,StandardsAuthError as p,createHttpTransport as r,recordsPath as s,createAppClient as t,openAgentStream as u,isObjectNotFound as v,schemaApiErrorCode as x,isPermanentRefusal as y};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
2
|
import { AgentSessionEvent, AgentStreamControlFrame, DraftConflictChange } from "@standards/schema";
|
|
3
|
-
import { Operation, OperationHost, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
|
|
3
|
+
import { Operation, OperationCaller, OperationHost, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
|
|
4
4
|
/**
|
|
5
5
|
* Any non-2xx answer from a Standards API. `code` is the server's `SchemaErrorCode` when it sent
|
|
6
6
|
* one; `details` is the body's `details` field, kept as the server sent it.
|
|
@@ -254,18 +254,28 @@ declare function openAgentStream(options: OpenAgentStreamOptions): AgentStreamHa
|
|
|
254
254
|
* callers fall back to a client-side name.
|
|
255
255
|
*/
|
|
256
256
|
declare function parseContentDispositionFilename(header: string | null | undefined): string | undefined;
|
|
257
|
+
/**
|
|
258
|
+
* The in-process transport: an {@link OperationTransport} that can also be
|
|
259
|
+
* bound to who acts, which a transport over HTTP cannot (its identity is the
|
|
260
|
+
* API key's).
|
|
261
|
+
*/
|
|
262
|
+
interface InProcessTransport extends OperationTransport {
|
|
263
|
+
/** The same transport, every call acting as `caller`. */
|
|
264
|
+
withCaller(caller: OperationCaller): InProcessTransport;
|
|
265
|
+
}
|
|
257
266
|
/**
|
|
258
267
|
* A transport over operations run in this process (the runtime's
|
|
259
268
|
* `createOperationHost`), for a server that embeds Standards: the same
|
|
260
269
|
* `createAppClient` API, inputs, answers and errors as over HTTP, without a
|
|
261
|
-
* socket.
|
|
262
|
-
*
|
|
270
|
+
* socket. Each call acts as the actor the ambient context implies (the
|
|
271
|
+
* request's, the job's, the system where none runs), or as the one
|
|
272
|
+
* `withCaller` names, and each operation's permissions are checked as the
|
|
263
273
|
* HTTP API checks them. A refusal rejects with the `StandardsRequestError`
|
|
264
274
|
* (`StandardsAuthError` for 401/403) the HTTP transport would throw.
|
|
265
275
|
*
|
|
266
276
|
* Streams (`"events"` operations) are served over HTTP only.
|
|
267
277
|
*/
|
|
268
|
-
declare function createInProcessTransport(host: OperationHost):
|
|
278
|
+
declare function createInProcessTransport(host: OperationHost): InProcessTransport;
|
|
269
279
|
type AppOperationGroups = typeof appOperationGroups;
|
|
270
280
|
type AppOperation = { [K in keyof AppOperationGroups]: AppOperationGroups[K][keyof AppOperationGroups[K]]; }[keyof AppOperationGroups];
|
|
271
281
|
type NamespaceOf<N> = N extends `${infer G}.${string}` ? G : never;
|
|
@@ -279,4 +289,4 @@ type OperationCall<O extends Operation> = (...args: undefined extends OperationI
|
|
|
279
289
|
type AppClient = { readonly [G in NamespaceOf<AppOperation["name"]>]: { readonly [O in AppOperation as NamespaceOf<O["name"]> extends G ? VerbOf<O["name"]> : never]: OperationCall<O>; }; };
|
|
280
290
|
/** The namespaced client over every app operation: `client.apiKeys.revoke({ id })`. */
|
|
281
291
|
declare function createAppClient(transport: OperationTransport): AppClient;
|
|
282
|
-
export {
|
|
292
|
+
export { refusalOf as A, OperationTransport as C, createHttpTransport as D, UploadProgress as E, StandardsRequestError as F, BundleValidationError as M, StandardsAuthError as N, createTransport as O, StandardsConfigurationError as P, OperationStreamOptions as S, TransportConfig as T, schemaApiErrorCode as _, parseContentDispositionFilename as a, MultipartRequestOptions as b, AgentStreamStatus as c, openAgentStream as d, draftConflictChanges as f, isViewNotFound as g, isPermanentRefusal as h, createInProcessTransport as i, BundleConflictError as j, readRefusal as k, OpenAgentStreamOptions as l, isObjectNotFound as m, createAppClient as n, AgentStreamControl as o, isDraftRevisionConflict as p, InProcessTransport as r, AgentStreamHandle as s, AppClient as t, TURN_END_TYPES as u, HttpTransport as v, Transport as w, OperationCallOptions as x, HttpTransportConfig as y };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
2
|
import { AgentSessionEvent, AgentStreamControlFrame, DraftConflictChange } from "@standards/schema";
|
|
3
|
-
import { Operation, OperationHost, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
|
|
3
|
+
import { Operation, OperationCaller, OperationHost, OperationInput, OperationResult, appOperationGroups } from "@standards/schema/api";
|
|
4
4
|
/**
|
|
5
5
|
* Any non-2xx answer from a Standards API. `code` is the server's `SchemaErrorCode` when it sent
|
|
6
6
|
* one; `details` is the body's `details` field, kept as the server sent it.
|
|
@@ -254,18 +254,28 @@ declare function openAgentStream(options: OpenAgentStreamOptions): AgentStreamHa
|
|
|
254
254
|
* callers fall back to a client-side name.
|
|
255
255
|
*/
|
|
256
256
|
declare function parseContentDispositionFilename(header: string | null | undefined): string | undefined;
|
|
257
|
+
/**
|
|
258
|
+
* The in-process transport: an {@link OperationTransport} that can also be
|
|
259
|
+
* bound to who acts, which a transport over HTTP cannot (its identity is the
|
|
260
|
+
* API key's).
|
|
261
|
+
*/
|
|
262
|
+
interface InProcessTransport extends OperationTransport {
|
|
263
|
+
/** The same transport, every call acting as `caller`. */
|
|
264
|
+
withCaller(caller: OperationCaller): InProcessTransport;
|
|
265
|
+
}
|
|
257
266
|
/**
|
|
258
267
|
* A transport over operations run in this process (the runtime's
|
|
259
268
|
* `createOperationHost`), for a server that embeds Standards: the same
|
|
260
269
|
* `createAppClient` API, inputs, answers and errors as over HTTP, without a
|
|
261
|
-
* socket.
|
|
262
|
-
*
|
|
270
|
+
* socket. Each call acts as the actor the ambient context implies (the
|
|
271
|
+
* request's, the job's, the system where none runs), or as the one
|
|
272
|
+
* `withCaller` names, and each operation's permissions are checked as the
|
|
263
273
|
* HTTP API checks them. A refusal rejects with the `StandardsRequestError`
|
|
264
274
|
* (`StandardsAuthError` for 401/403) the HTTP transport would throw.
|
|
265
275
|
*
|
|
266
276
|
* Streams (`"events"` operations) are served over HTTP only.
|
|
267
277
|
*/
|
|
268
|
-
declare function createInProcessTransport(host: OperationHost):
|
|
278
|
+
declare function createInProcessTransport(host: OperationHost): InProcessTransport;
|
|
269
279
|
type AppOperationGroups = typeof appOperationGroups;
|
|
270
280
|
type AppOperation = { [K in keyof AppOperationGroups]: AppOperationGroups[K][keyof AppOperationGroups[K]]; }[keyof AppOperationGroups];
|
|
271
281
|
type NamespaceOf<N> = N extends `${infer G}.${string}` ? G : never;
|
|
@@ -279,4 +289,4 @@ type OperationCall<O extends Operation> = (...args: undefined extends OperationI
|
|
|
279
289
|
type AppClient = { readonly [G in NamespaceOf<AppOperation["name"]>]: { readonly [O in AppOperation as NamespaceOf<O["name"]> extends G ? VerbOf<O["name"]> : never]: OperationCall<O>; }; };
|
|
280
290
|
/** The namespaced client over every app operation: `client.apiKeys.revoke({ id })`. */
|
|
281
291
|
declare function createAppClient(transport: OperationTransport): AppClient;
|
|
282
|
-
export {
|
|
292
|
+
export { refusalOf as A, OperationTransport as C, createHttpTransport as D, UploadProgress as E, StandardsRequestError as F, BundleValidationError as M, StandardsAuthError as N, createTransport as O, StandardsConfigurationError as P, OperationStreamOptions as S, TransportConfig as T, schemaApiErrorCode as _, parseContentDispositionFilename as a, MultipartRequestOptions as b, AgentStreamStatus as c, openAgentStream as d, draftConflictChanges as f, isViewNotFound as g, isPermanentRefusal as h, createInProcessTransport as i, BundleConflictError as j, readRefusal as k, OpenAgentStreamOptions as l, isObjectNotFound as m, createAppClient as n, AgentStreamControl as o, isDraftRevisionConflict as p, InProcessTransport as r, AgentStreamHandle as s, AppClient as t, TURN_END_TYPES as u, HttpTransport as v, Transport as w, OperationCallOptions as x, HttpTransportConfig as y };
|
package/dist/app.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
export { type AgentStreamControl, type AgentStreamHandle, type AgentStreamStatus, AppClient, type HttpTransport, type HttpTransportConfig, type OpenAgentStreamOptions, type OperationCallOptions, type OperationStreamOptions, type OperationTransport, StandardsAuthError, StandardsRequestError, TURN_END_TYPES, type UploadProgress, createAppClient, createHttpTransport, createInProcessTransport, draftConflictChanges, isDraftRevisionConflict, isObjectNotFound, isPermanentRefusal, isViewNotFound, openAgentStream, parseContentDispositionFilename, readRefusal, refusalOf, schemaApiErrorCode };
|
|
2
|
+
import { A as refusalOf, C as OperationTransport, D as createHttpTransport, E as UploadProgress, F as StandardsRequestError, N as StandardsAuthError, S as OperationStreamOptions, _ as schemaApiErrorCode, a as parseContentDispositionFilename, c as AgentStreamStatus, d as openAgentStream, f as draftConflictChanges, g as isViewNotFound, h as isPermanentRefusal, i as createInProcessTransport, k as readRefusal, l as OpenAgentStreamOptions, m as isObjectNotFound, n as createAppClient, o as AgentStreamControl, p as isDraftRevisionConflict, r as InProcessTransport, s as AgentStreamHandle, t as AppClient, u as TURN_END_TYPES, v as HttpTransport, x as OperationCallOptions, y as HttpTransportConfig } from "./app-_CiXRLoD.mjs";
|
|
3
|
+
export { type AgentStreamControl, type AgentStreamHandle, type AgentStreamStatus, AppClient, type HttpTransport, type HttpTransportConfig, type InProcessTransport, type OpenAgentStreamOptions, type OperationCallOptions, type OperationStreamOptions, type OperationTransport, StandardsAuthError, StandardsRequestError, TURN_END_TYPES, type UploadProgress, createAppClient, createHttpTransport, createInProcessTransport, draftConflictChanges, isDraftRevisionConflict, isObjectNotFound, isPermanentRefusal, isViewNotFound, openAgentStream, parseContentDispositionFilename, readRefusal, refusalOf, schemaApiErrorCode };
|
package/dist/app.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
export { type AgentStreamControl, type AgentStreamHandle, type AgentStreamStatus, AppClient, type HttpTransport, type HttpTransportConfig, type OpenAgentStreamOptions, type OperationCallOptions, type OperationStreamOptions, type OperationTransport, StandardsAuthError, StandardsRequestError, TURN_END_TYPES, type UploadProgress, createAppClient, createHttpTransport, createInProcessTransport, draftConflictChanges, isDraftRevisionConflict, isObjectNotFound, isPermanentRefusal, isViewNotFound, openAgentStream, parseContentDispositionFilename, readRefusal, refusalOf, schemaApiErrorCode };
|
|
2
|
+
import { A as refusalOf, C as OperationTransport, D as createHttpTransport, E as UploadProgress, F as StandardsRequestError, N as StandardsAuthError, S as OperationStreamOptions, _ as schemaApiErrorCode, a as parseContentDispositionFilename, c as AgentStreamStatus, d as openAgentStream, f as draftConflictChanges, g as isViewNotFound, h as isPermanentRefusal, i as createInProcessTransport, k as readRefusal, l as OpenAgentStreamOptions, m as isObjectNotFound, n as createAppClient, o as AgentStreamControl, p as isDraftRevisionConflict, r as InProcessTransport, s as AgentStreamHandle, t as AppClient, u as TURN_END_TYPES, v as HttpTransport, x as OperationCallOptions, y as HttpTransportConfig } from "./app-_CiXRLoD.js";
|
|
3
|
+
export { type AgentStreamControl, type AgentStreamHandle, type AgentStreamStatus, AppClient, type HttpTransport, type HttpTransportConfig, type InProcessTransport, type OpenAgentStreamOptions, type OperationCallOptions, type OperationStreamOptions, type OperationTransport, StandardsAuthError, StandardsRequestError, TURN_END_TYPES, type UploadProgress, createAppClient, createHttpTransport, createInProcessTransport, draftConflictChanges, isDraftRevisionConflict, isObjectNotFound, isPermanentRefusal, isViewNotFound, openAgentStream, parseContentDispositionFilename, readRefusal, refusalOf, schemaApiErrorCode };
|
package/dist/app.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("./app-
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./app-BgWz3r5k.js");exports.StandardsAuthError=e.p,exports.StandardsRequestError=e.h,exports.TURN_END_TYPES=e.l,exports.createAppClient=e.t,exports.createHttpTransport=e.r,exports.createInProcessTransport=e.n,exports.draftConflictChanges=e.g,exports.isDraftRevisionConflict=e._,exports.isObjectNotFound=e.v,exports.isPermanentRefusal=e.y,exports.isViewNotFound=e.b,exports.openAgentStream=e.u,exports.parseContentDispositionFilename=e.c,exports.readRefusal=e.a,exports.refusalOf=e.o,exports.schemaApiErrorCode=e.x;
|
package/dist/app.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
|
-
export{p as StandardsAuthError,h as StandardsRequestError,l as TURN_END_TYPES,t as createAppClient,r as createHttpTransport,n as createInProcessTransport,g as draftConflictChanges,_ as isDraftRevisionConflict,v as isObjectNotFound,y as isPermanentRefusal,b as isViewNotFound,u as openAgentStream,c as parseContentDispositionFilename,a as readRefusal,o as refusalOf,x as schemaApiErrorCode}from"./app-
|
|
2
|
+
export{p as StandardsAuthError,h as StandardsRequestError,l as TURN_END_TYPES,t as createAppClient,r as createHttpTransport,n as createInProcessTransport,g as draftConflictChanges,_ as isDraftRevisionConflict,v as isObjectNotFound,y as isPermanentRefusal,b as isViewNotFound,u as openAgentStream,c as parseContentDispositionFilename,a as readRefusal,o as refusalOf,x as schemaApiErrorCode}from"./app-TJt8rk9y.mjs";
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
+
const e=require("./app-BgWz3r5k.js");let t=require("@standards/schema"),n=require("@standards/schema/api");async function readInstalled(t,r){try{return await t.call(n.bundlesOperations.get,{name:r})}catch(t){if(t instanceof e.h&&t.status===404)return null;throw t}}async function syncBundle(t,r,i={}){let a=await r.build(),o=await readInstalled(t,a.name);if(o?.hash===a.hash&&o.label===a.label&&o.description===a.description&&o.uses.join(`
|
|
3
|
+
`)===a.uses.join(`
|
|
4
|
+
`))return{applied:!1,hash:a.hash};let s=i.resolutions&&i.resolutions.length>0?{...a,resolutions:i.resolutions}:a;try{return await t.call(n.bundlesOperations.sync,{name:a.name,bundle:s})}catch(t){throw t instanceof e.h&&t.status===409?new e.d(t.status,t.message,t.code):t instanceof e.h&&t.status===400?new e.f(t.status,t.message,t.code):t}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const r=/* @__PURE__ */ new Set([`from`,`bundles`,`contract`,`as`]);function assertObjectKeys(t){let n=/* @__PURE__ */ new Map;for(let i of t){if(i.includes(`--`)||i.endsWith(`-`))throw new e.m(`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.m(`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.m(`Objects "${a}" and "${i}" both map to the client key "${t}". Rename one of them.`);n.set(t,i)}}function assertObjectNames(e){let n=/* @__PURE__ */ new Set;for(let r of e){if(n.has(r))throw new t.DuplicateError(`object`,r);n.add(r)}assertObjectKeys(e)}function readRecord(e,n){let{values:r,...i}=n;return(0,t.isPlainRecord)(r)?{...i,...(0,t.decodeRecordValues)(e,r)}:n}var i=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 readRecord(this.definition,e)}async export(t,r={}){if(!this.transport.postRaw)throw new e.m(`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.call(n.recordsOperations.aggregate,{objectName:this.objectName,...r})}async fetchPage(){let e={objectName:this.objectName,...this.body()},t=this.state.search===void 0?await this.transport.call(n.recordsOperations.list,e):await this.transport.call(n.recordsOperations.search,e);return{records:t.data.map(e=>this.revive(e)),page:t.page}}async fetch(){let{records:e,page:t}=await this.fetchPage();return{records:e,total:t.total}}async all(){if(this.state.limit!==void 0&&this.state.limit<0)return(await this.fetch()).records;let e=this.state.limit??1/0,t=[],n=this.state.offset??0;for(;;){let r=Math.min(1e3,e-t.length);if(r<=0)return t;let{records:i,page:a}=await this.with({limit:r,offset:n}).fetchPage();if(t.push(...i),!a.hasMore)return t;let o=a.nextOffset??n+i.length;if(o<=n)return t;n=o}}async single(){let{records:e}=await this.limit(1).fetch();return e[0]??null}async get(e){let t=await this.transport.call(n.recordsOperations.get,{objectName:this.objectName,id:e});return this.revive(t)}async create(e,{allowDraft:r,metadata:i}={}){let a={...r!==void 0&&{allowDraft:r},...i!==void 0&&{metadata:i}},o=await this.transport.call(n.recordsOperations.create,{objectName:this.objectName,data:(0,t.encodeRecordValues)(this.definition,e),...Object.keys(a).length>0&&{options:a}});return this.revive(o)}async update(r,i,{metadata:a}={}){let o=(0,t.encodeRecordValues)(this.definition,i);if(a===void 0){let e=await this.transport.call(n.recordsOperations.update,{objectName:this.objectName,id:r,values:o});return this.revive(e)}let{objectId:s}=await this.transport.call(n.recordsOperations.get,{objectName:this.objectName,id:r}),{steps:c}=await this.transport.call(n.recordOperationsOperations.execute,{opId:crypto.randomUUID(),steps:[{kind:`record.set`,objectId:s,recordId:r,values:o,metadata:a}]}),[l]=c;if(l===void 0||l.status===`error`){let n=l?.code,r=n===void 0?500:t.SCHEMA_ERROR_HTTP_STATUS[n];throw e.o(r,JSON.stringify({message:l?.message,code:n}))}let u=(0,n.decodeOperationOutput)(n.recordsOperations.get,l.record);return this.revive(u)}async delete(e){await this.transport.call(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 r={created:[],errors:[]};return await this.inChunks(e,async(e,i)=>{let a=await this.transport.call(n.recordsOperations.bulkCreate,{objectName:this.objectName,records:e.map(e=>(0,t.encodeRecordValues)(this.definition,e))});r.created.push(...a.created.map(e=>this.revive(e))),r.errors.push(...a.errors.map(e=>({...e,index:e.index+i})))}),r}async updateMany(e){let r={updated:[],errors:[]};return await this.inChunks(e,async e=>{let i=await this.transport.call(n.recordsOperations.bulkUpdate,{objectName:this.objectName,updates:e.map(({id:e,data:n})=>({id:e,data:(0,t.encodeRecordValues)(this.definition,n)}))});r.updated.push(...i.updated.map(e=>this.revive(e))),r.errors.push(...i.errors)}),r}async deleteMany(e){let t={deleted:[],errors:[]};return await this.inChunks(e,async e=>{let r=await this.transport.call(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.call(n.recordAccessOperations.list,{objectName:this.objectName,recordId:e})}async grantAccess(e,t,r){return await this.transport.call(n.recordAccessOperations.grant,{objectName:this.objectName,recordId:e,actorId:t,role:r})}async revokeAccess(e,t){return await this.transport.call(n.recordAccessOperations.revoke,{objectName:this.objectName,recordId:e,actorId:t})}async clearAccess(e){return await this.transport.call(n.recordAccessOperations.clear,{objectName:this.objectName,recordId:e})}};const a=/* @__PURE__ */ new WeakMap;function definitionOf(e){let t=a.get(e);if(t)return t;let n=e.build();return a.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new i(e,t,null);let n=definitionOf(t);return new i(e,n.name,n)}function readEnvironment(){return typeof process>`u`||!process.env?{}:{baseUrl:process.env.STANDARDS_API_URL||void 0,apiKey:process.env.STANDARDS_API_KEY||void 0}}function resolveConfig(t){if(globalThis.window!==void 0){if(t.apiKey)throw new e.m(`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.m(`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.m(`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.m(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...t,baseUrl:r,apiKey:i}}function createStandards(t={}){let{bundles:n=[],transport:r,...i}=t;if(r!==void 0&&Object.values(i).some(e=>e!==void 0))throw new e.m(`createStandards takes a transport or an HTTP connection (baseUrl, apiKey, tenantId, timeoutMs), not both.`);return buildStandards(r??e.i(resolveConfig(i)),n.flatMap(e=>e.objectBuilders))}function buildStandards(t,r){let i=e.t(t),sync=((e,n)=>isBundleBuilder(e)?syncBundle(t,e,n):i.bundles.sync(e,n)),a={...i,bundles:{...i.bundles,sync},from:e=>createRecordsQuery(t,e),contract:i},o=r.map(e=>definitionOf(e).name);assertObjectNames(o),r.forEach((e,n)=>{a[objectKeyOf(o[n])]=createRecordsQuery(t,e)});let s=t.withCaller?.bind(t);return s!==void 0&&(a.as=e=>buildStandards(s((0,n.callerOf)(e)),r)),a}function isBundleBuilder(e){return typeof e==`object`&&!!e&&`objectBuilders`in e&&typeof e.build==`function`}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return definitionOf}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return createRecordsQuery}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createStandards}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return readRecord}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return resolveConfig}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return syncBundle}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return buildStandards}});
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
+
import{d as e,f as t,h as n,i as r,m as i,o as a,t as o}from"./app-TJt8rk9y.mjs";import{AggregateValidationError as s,DuplicateError as c,RecordQuery as l,SCHEMA_ERROR_HTTP_STATUS as u,SchemaErrorCode as d,decodeRecordValues as f,encodeRecordValues as p,isPlainRecord as m}from"@standards/schema";import{buildOperationPath as h,bundlesOperations as g,callerOf as _,decodeOperationOutput as v,recordAccessOperations as y,recordOperationsOperations as b,recordsOperations as x}from"@standards/schema/api";async function readInstalled(e,t){try{return await e.call(g.get,{name:t})}catch(e){if(e instanceof n&&e.status===404)return null;throw e}}async function syncBundle(r,i,a={}){let o=await i.build(),s=await readInstalled(r,o.name);if(s?.hash===o.hash&&s.label===o.label&&s.description===o.description&&s.uses.join(`
|
|
3
|
+
`)===o.uses.join(`
|
|
4
|
+
`))return{applied:!1,hash:o.hash};let c=a.resolutions&&a.resolutions.length>0?{...o,resolutions:a.resolutions}:o;try{return await r.call(g.sync,{name:o.name,bundle:c})}catch(r){throw r instanceof n&&r.status===409?new e(r.status,r.message,r.code):r instanceof n&&r.status===400?new t(r.status,r.message,r.code):r}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const S=/* @__PURE__ */ new Set([`from`,`bundles`,`contract`,`as`]);function assertObjectKeys(e){let t=/* @__PURE__ */ new Map;for(let n of e){if(n.includes(`--`)||n.endsWith(`-`))throw new i(`Object "${n}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let e=objectKeyOf(n);if(S.has(e))throw new i(`Object "${n}" maps to the client key "${e}", which is reserved. Rename the object.`);let r=t.get(e);if(r!==void 0&&r!==n)throw new i(`Objects "${r}" and "${n}" both map to the client key "${e}". Rename one of them.`);t.set(e,n)}}function assertObjectNames(e){let t=/* @__PURE__ */ new Set;for(let n of e){if(t.has(n))throw new c(`object`,n);t.add(n)}assertObjectKeys(e)}function readRecord(e,t){let{values:n,...r}=t;return m(n)?{...r,...f(e,n)}:t}var C=class RecordsQueryImpl extends l{constructor(e,t,n,r={object:t,combinator:`and`,rules:[],sorts:[]}){super(r),this.transport=e,this.objectName=t,this.definition=n}with(e){return new RecordsQueryImpl(this.transport,this.objectName,this.definition,{...this.state,...e})}body(){let e={};return this.state.search!==void 0&&(e.q=this.state.search),this.state.rules.length>0&&(e.filters={combinator:this.state.combinator,rules:this.state.rules}),this.state.sorts.length>0&&(e.sorts=this.state.sorts),this.state.limit!==void 0&&(e.limit=this.state.limit),this.state.offset!==void 0&&(e.offset=this.state.offset),e}revive(e){return readRecord(this.definition,e)}async export(e,t={}){if(!this.transport.postRaw)throw new i(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:n,sorts:r}=this.body(),{ids:a,locale:o,filename:s}=t;return await this.transport.postRaw(h(x.export,{objectName:this.objectName}),{q:this.state.search??``,...n?{filters:n}:{},...r?{sorts:r}:{},columns:e,...a?{ids:a}:{},...o?{locale:o}:{},timezone:t.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...s?{filename:s}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new s(d.AGGREGATE_SEARCH_UNSUPPORTED,`An aggregate cannot be narrowed by a search; use filters instead`);let t={...e,query:this.toDefinition(),timezone:e.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone};return await this.transport.call(x.aggregate,{objectName:this.objectName,...t})}async fetchPage(){let e={objectName:this.objectName,...this.body()},t=this.state.search===void 0?await this.transport.call(x.list,e):await this.transport.call(x.search,e);return{records:t.data.map(e=>this.revive(e)),page:t.page}}async fetch(){let{records:e,page:t}=await this.fetchPage();return{records:e,total:t.total}}async all(){if(this.state.limit!==void 0&&this.state.limit<0)return(await this.fetch()).records;let e=this.state.limit??1/0,t=[],n=this.state.offset??0;for(;;){let r=Math.min(1e3,e-t.length);if(r<=0)return t;let{records:i,page:a}=await this.with({limit:r,offset:n}).fetchPage();if(t.push(...i),!a.hasMore)return t;let o=a.nextOffset??n+i.length;if(o<=n)return t;n=o}}async single(){let{records:e}=await this.limit(1).fetch();return e[0]??null}async get(e){let t=await this.transport.call(x.get,{objectName:this.objectName,id:e});return this.revive(t)}async create(e,{allowDraft:t,metadata:n}={}){let r={...t!==void 0&&{allowDraft:t},...n!==void 0&&{metadata:n}},i=await this.transport.call(x.create,{objectName:this.objectName,data:p(this.definition,e),...Object.keys(r).length>0&&{options:r}});return this.revive(i)}async update(e,t,{metadata:n}={}){let r=p(this.definition,t);if(n===void 0){let t=await this.transport.call(x.update,{objectName:this.objectName,id:e,values:r});return this.revive(t)}let{objectId:i}=await this.transport.call(x.get,{objectName:this.objectName,id:e}),{steps:o}=await this.transport.call(b.execute,{opId:crypto.randomUUID(),steps:[{kind:`record.set`,objectId:i,recordId:e,values:r,metadata:n}]}),[s]=o;if(s===void 0||s.status===`error`){let e=s?.code,t=e===void 0?500:u[e];throw a(t,JSON.stringify({message:s?.message,code:e}))}let c=v(x.get,s.record);return this.revive(c)}async delete(e){await this.transport.call(x.delete,{objectName:this.objectName,id:e})}async inChunks(e,t){for(let n=0;n<e.length;n+=100)await t(e.slice(n,n+100),n)}async createMany(e){let t={created:[],errors:[]};return await this.inChunks(e,async(e,n)=>{let r=await this.transport.call(x.bulkCreate,{objectName:this.objectName,records:e.map(e=>p(this.definition,e))});t.created.push(...r.created.map(e=>this.revive(e))),t.errors.push(...r.errors.map(e=>({...e,index:e.index+n})))}),t}async updateMany(e){let t={updated:[],errors:[]};return await this.inChunks(e,async e=>{let n=await this.transport.call(x.bulkUpdate,{objectName:this.objectName,updates:e.map(({id:e,data:t})=>({id:e,data:p(this.definition,t)}))});t.updated.push(...n.updated.map(e=>this.revive(e))),t.errors.push(...n.errors)}),t}async deleteMany(e){let t={deleted:[],errors:[]};return await this.inChunks(e,async e=>{let n=await this.transport.call(x.bulkDelete,{objectName:this.objectName,ids:e});t.deleted.push(...n.deleted),t.errors.push(...n.errors)}),t}async listAccess(e){return await this.transport.call(y.list,{objectName:this.objectName,recordId:e})}async grantAccess(e,t,n){return await this.transport.call(y.grant,{objectName:this.objectName,recordId:e,actorId:t,role:n})}async revokeAccess(e,t){return await this.transport.call(y.revoke,{objectName:this.objectName,recordId:e,actorId:t})}async clearAccess(e){return await this.transport.call(y.clear,{objectName:this.objectName,recordId:e})}};const w=/* @__PURE__ */ new WeakMap;function definitionOf(e){let t=w.get(e);if(t)return t;let n=e.build();return w.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new C(e,t,null);let n=definitionOf(t);return new C(e,n.name,n)}function readEnvironment(){return typeof process>`u`||!process.env?{}:{baseUrl:process.env.STANDARDS_API_URL||void 0,apiKey:process.env.STANDARDS_API_KEY||void 0}}function resolveConfig(e){if(globalThis.window!==void 0){if(e.apiKey)throw new i(`createStandards received an apiKey in a browser context. API keys belong to server code only (Route Handlers, Server Components, scripts).`);if(e.baseUrl===void 0)throw new i(`createStandards needs an explicit baseUrl in a browser context: STANDARDS_API_URL and STANDARDS_API_KEY are never read from the environment there.`);return{...e,baseUrl:e.baseUrl,apiKey:``}}let t=readEnvironment(),n=e.baseUrl??t.baseUrl;if(n===void 0)throw new i(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let r=e.apiKey??t.apiKey;if(r===void 0)throw new i(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...e,baseUrl:n,apiKey:r}}function createStandards(e={}){let{bundles:t=[],transport:n,...a}=e;if(n!==void 0&&Object.values(a).some(e=>e!==void 0))throw new i(`createStandards takes a transport or an HTTP connection (baseUrl, apiKey, tenantId, timeoutMs), not both.`);return buildStandards(n??r(resolveConfig(a)),t.flatMap(e=>e.objectBuilders))}function buildStandards(e,t){let n=o(e),sync=((t,r)=>isBundleBuilder(t)?syncBundle(e,t,r):n.bundles.sync(t,r)),r={...n,bundles:{...n.bundles,sync},from:t=>createRecordsQuery(e,t),contract:n},i=t.map(e=>definitionOf(e).name);assertObjectNames(i),t.forEach((t,n)=>{r[objectKeyOf(i[n])]=createRecordsQuery(e,t)});let a=e.withCaller?.bind(e);return a!==void 0&&(r.as=e=>buildStandards(a(_(e)),t)),r}function isBundleBuilder(e){return typeof e==`object`&&!!e&&`objectBuilders`in e&&typeof e.build==`function`}export{definitionOf as a,createRecordsQuery as i,createStandards as n,readRecord as o,resolveConfig as r,syncBundle as s,buildStandards as t};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
2
|
+
import { C as OperationTransport, T as TransportConfig, r as InProcessTransport, t as AppClient, v as HttpTransport } from "./app-_CiXRLoD.js";
|
|
3
3
|
import { AggregateRecordsOptions, BundleBuilder, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult } from "@standards/schema";
|
|
4
|
+
import { ActorId } from "@standards/schema/api";
|
|
4
5
|
/**
|
|
5
6
|
* What a sync carries besides the bundle itself.
|
|
6
7
|
*
|
|
@@ -289,12 +290,28 @@ type Standards = Omit<AppClient, "bundles"> & {
|
|
|
289
290
|
* reads.
|
|
290
291
|
*/
|
|
291
292
|
type StandardsOf<TObjects extends readonly ObjectBuilderLike[]> = Omit<Standards, keyof ObjectsOf<TObjects>> & ObjectsOf<TObjects>;
|
|
293
|
+
/**
|
|
294
|
+
* A client in a server that embeds Standards: the same client, plus `as` to
|
|
295
|
+
* name who acts. Absent over HTTP, where the identity is the API key's.
|
|
296
|
+
*/
|
|
297
|
+
type ActingStandards<S> = S & {
|
|
298
|
+
/**
|
|
299
|
+
* The same client, every call acting as `actor`: an actor id, or `"system"`
|
|
300
|
+
* for the workspace's system actor. Permissions and visibility are that
|
|
301
|
+
* actor's; the actor the context implies, if any, is recorded as the one
|
|
302
|
+
* who triggered the call. Without `as`, a call acts as the context implies:
|
|
303
|
+
* the request's user, the job's enqueuer, the write's author, else the
|
|
304
|
+
* system.
|
|
305
|
+
*/
|
|
306
|
+
as(actor: ActorId | "system"): ActingStandards<S>;
|
|
307
|
+
};
|
|
292
308
|
/**
|
|
293
309
|
* Every call `createStandards` makes is a contract operation (`call`, and
|
|
294
310
|
* `stream` for an `"events"` one); a records `export()` also
|
|
295
|
-
* needs an HTTP transport's `postRaw
|
|
311
|
+
* needs an HTTP transport's `postRaw`, and `as` the in-process transport's
|
|
312
|
+
* `withCaller`.
|
|
296
313
|
*/
|
|
297
|
-
type StandardsTransport = OperationTransport & Partial<Pick<HttpTransport, "postRaw">>;
|
|
314
|
+
type StandardsTransport = OperationTransport & Partial<Pick<HttpTransport, "postRaw">> & Partial<Pick<InProcessTransport, "withCaller">>;
|
|
298
315
|
/**
|
|
299
316
|
* The options `createStandards` takes: an API key's HTTP connection
|
|
300
317
|
* (`baseUrl`, `apiKey`, read from the environment when absent), or a
|
|
@@ -304,8 +321,15 @@ type StandardsTransport = OperationTransport & Partial<Pick<HttpTransport, "post
|
|
|
304
321
|
type StandardsConfig = Partial<TransportConfig> & {
|
|
305
322
|
transport?: StandardsTransport;
|
|
306
323
|
};
|
|
324
|
+
declare function createStandards<const TBundles extends readonly AnyBundle[]>(config: StandardsConfig & {
|
|
325
|
+
transport: InProcessTransport;
|
|
326
|
+
bundles: TBundles;
|
|
327
|
+
}): ActingStandards<StandardsOf<ObjectsOfBundles<TBundles>>>;
|
|
328
|
+
declare function createStandards(config: StandardsConfig & {
|
|
329
|
+
transport: InProcessTransport;
|
|
330
|
+
}): ActingStandards<Standards>;
|
|
307
331
|
declare function createStandards<const TBundles extends readonly AnyBundle[]>(config: StandardsConfig & {
|
|
308
332
|
bundles: TBundles;
|
|
309
333
|
}): StandardsOf<ObjectsOfBundles<TBundles>>;
|
|
310
334
|
declare function createStandards(config?: StandardsConfig): Standards;
|
|
311
|
-
export {
|
|
335
|
+
export { SyncBundleOptions as A, UntypedBuilder as C, UpdateManyResult as D, UpdateManyError as E, syncBundle as M, createRecordsQuery as O, RecordsQuery as S, UpdateManyEntry as T, RecordInput as _, ObjectsOfBundles as a, RecordsAggregateOptions as b, StandardsOf as c, CreateManyError as d, CreateManyResult as f, RecordCreateOptions as g, FetchResult as h, ObjectsOf as i, SyncTransport as j, CamelCase as k, StandardsTransport as l, DeleteManyResult as m, AnyBundle as n, Standards as o, DeleteManyError as p, BundlesSync as r, StandardsConfig as s, ActingStandards as t, createStandards as u, RecordUpdate as v, UntypedRecordsQuery as w, RecordsExportOptions as x, RecordUpdateOptions as y };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
2
|
+
import { C as OperationTransport, T as TransportConfig, r as InProcessTransport, t as AppClient, v as HttpTransport } from "./app-_CiXRLoD.mjs";
|
|
3
3
|
import { AggregateRecordsOptions, BundleBuilder, ExtractRecord, ExtractRecordInputStrict, ExtractRecordUpdateStrict, FilterRule, ObjectBuilderLike, RecordAccessRole, RecordAggregates, RecordAudience, RuleValue, SchemaSourceResolution, SyncBundleResult } from "@standards/schema";
|
|
4
|
+
import { ActorId } from "@standards/schema/api";
|
|
4
5
|
/**
|
|
5
6
|
* What a sync carries besides the bundle itself.
|
|
6
7
|
*
|
|
@@ -289,12 +290,28 @@ type Standards = Omit<AppClient, "bundles"> & {
|
|
|
289
290
|
* reads.
|
|
290
291
|
*/
|
|
291
292
|
type StandardsOf<TObjects extends readonly ObjectBuilderLike[]> = Omit<Standards, keyof ObjectsOf<TObjects>> & ObjectsOf<TObjects>;
|
|
293
|
+
/**
|
|
294
|
+
* A client in a server that embeds Standards: the same client, plus `as` to
|
|
295
|
+
* name who acts. Absent over HTTP, where the identity is the API key's.
|
|
296
|
+
*/
|
|
297
|
+
type ActingStandards<S> = S & {
|
|
298
|
+
/**
|
|
299
|
+
* The same client, every call acting as `actor`: an actor id, or `"system"`
|
|
300
|
+
* for the workspace's system actor. Permissions and visibility are that
|
|
301
|
+
* actor's; the actor the context implies, if any, is recorded as the one
|
|
302
|
+
* who triggered the call. Without `as`, a call acts as the context implies:
|
|
303
|
+
* the request's user, the job's enqueuer, the write's author, else the
|
|
304
|
+
* system.
|
|
305
|
+
*/
|
|
306
|
+
as(actor: ActorId | "system"): ActingStandards<S>;
|
|
307
|
+
};
|
|
292
308
|
/**
|
|
293
309
|
* Every call `createStandards` makes is a contract operation (`call`, and
|
|
294
310
|
* `stream` for an `"events"` one); a records `export()` also
|
|
295
|
-
* needs an HTTP transport's `postRaw
|
|
311
|
+
* needs an HTTP transport's `postRaw`, and `as` the in-process transport's
|
|
312
|
+
* `withCaller`.
|
|
296
313
|
*/
|
|
297
|
-
type StandardsTransport = OperationTransport & Partial<Pick<HttpTransport, "postRaw">>;
|
|
314
|
+
type StandardsTransport = OperationTransport & Partial<Pick<HttpTransport, "postRaw">> & Partial<Pick<InProcessTransport, "withCaller">>;
|
|
298
315
|
/**
|
|
299
316
|
* The options `createStandards` takes: an API key's HTTP connection
|
|
300
317
|
* (`baseUrl`, `apiKey`, read from the environment when absent), or a
|
|
@@ -304,8 +321,15 @@ type StandardsTransport = OperationTransport & Partial<Pick<HttpTransport, "post
|
|
|
304
321
|
type StandardsConfig = Partial<TransportConfig> & {
|
|
305
322
|
transport?: StandardsTransport;
|
|
306
323
|
};
|
|
324
|
+
declare function createStandards<const TBundles extends readonly AnyBundle[]>(config: StandardsConfig & {
|
|
325
|
+
transport: InProcessTransport;
|
|
326
|
+
bundles: TBundles;
|
|
327
|
+
}): ActingStandards<StandardsOf<ObjectsOfBundles<TBundles>>>;
|
|
328
|
+
declare function createStandards(config: StandardsConfig & {
|
|
329
|
+
transport: InProcessTransport;
|
|
330
|
+
}): ActingStandards<Standards>;
|
|
307
331
|
declare function createStandards<const TBundles extends readonly AnyBundle[]>(config: StandardsConfig & {
|
|
308
332
|
bundles: TBundles;
|
|
309
333
|
}): StandardsOf<ObjectsOfBundles<TBundles>>;
|
|
310
334
|
declare function createStandards(config?: StandardsConfig): Standards;
|
|
311
|
-
export {
|
|
335
|
+
export { SyncBundleOptions as A, UntypedBuilder as C, UpdateManyResult as D, UpdateManyError as E, syncBundle as M, createRecordsQuery as O, RecordsQuery as S, UpdateManyEntry as T, RecordInput as _, ObjectsOfBundles as a, RecordsAggregateOptions as b, StandardsOf as c, CreateManyError as d, CreateManyResult as f, RecordCreateOptions as g, FetchResult as h, ObjectsOf as i, SyncTransport as j, CamelCase as k, StandardsTransport as l, DeleteManyResult as m, AnyBundle as n, Standards as o, DeleteManyError as p, BundlesSync as r, StandardsConfig as s, ActingStandards as t, createStandards as u, RecordUpdate as v, UntypedRecordsQuery as w, RecordsExportOptions as x, RecordUpdateOptions as y };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,12 +1,35 @@
|
|
|
1
1
|
|
|
2
|
-
import { A as
|
|
3
|
-
import {
|
|
2
|
+
import { A as SyncBundleOptions, C as UntypedBuilder, D as UpdateManyResult, E as UpdateManyError, M as syncBundle, O as createRecordsQuery, S as RecordsQuery, T as UpdateManyEntry, _ as RecordInput, a as ObjectsOfBundles, b as RecordsAggregateOptions, c as StandardsOf, d as CreateManyError, f as CreateManyResult, g as RecordCreateOptions, h as FetchResult, i as ObjectsOf, j as SyncTransport, k as CamelCase, l as StandardsTransport, m as DeleteManyResult, n as AnyBundle, o as Standards, p as DeleteManyError, r as BundlesSync, s as StandardsConfig, t as ActingStandards, u as createStandards, v as RecordUpdate, w as UntypedRecordsQuery, x as RecordsExportOptions, y as RecordUpdateOptions } from "./create-standards-lDN6ru8u.mjs";
|
|
3
|
+
import { F as StandardsRequestError, M as BundleValidationError, N as StandardsAuthError, O as createTransport, P as StandardsConfigurationError, T as TransportConfig, b as MultipartRequestOptions, j as BundleConflictError, w as Transport } from "./app-_CiXRLoD.mjs";
|
|
4
4
|
import { ActorType, Attribute, BUNDLE_NAME_PATTERN, BuiltBundle, BundleBuilder, BundlePiece, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, InstalledBundleSummary, NotFoundError, ObjectBuilderLike, ObjectDefinition, RecordAccessRole, RecordAudience, RecordMetadata, SchemaError, SchemaErrorCode, SchemaSourceCurrencyRetype, SchemaSourcePhoneRetype, SchemaSourceRename, SchemaSourceResolution, SchemaSourceRetype, SortDirection, SortRule, SyncBundleResult, UsageBucket, UsageModality, UsageReport, UsageScope, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, currency, currentActor, date, detailView, document, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, text, today, user } from "@standards/schema";
|
|
5
|
-
import { encodePathSegment } from "@standards/schema/api";
|
|
5
|
+
import { ActorId, OperationCaller, encodePathSegment } from "@standards/schema/api";
|
|
6
|
+
/**
|
|
7
|
+
* Declare your bundle once, and the default `standards` instance is typed by
|
|
8
|
+
* it:
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* declare module "@standards/client" {
|
|
12
|
+
* interface Register { bundle: typeof crm }
|
|
13
|
+
* }
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
interface Register {}
|
|
17
|
+
type RegisteredObjects = Register extends {
|
|
18
|
+
bundle: infer B extends AnyBundle;
|
|
19
|
+
} ? B["objectBuilders"] : readonly [];
|
|
20
|
+
/** The default instance's type: the registered bundle's objects, and `as`. */
|
|
21
|
+
type DefaultStandards = ActingStandards<StandardsOf<RegisteredObjects>>;
|
|
22
|
+
/**
|
|
23
|
+
* The ready instance: `import { standards } from "@standards/client"` and
|
|
24
|
+
* call it. Its transport is resolved on first use (see {@link resolved}); its
|
|
25
|
+
* types come from {@link Register}. `createStandards` stays for several
|
|
26
|
+
* instances or another workspace.
|
|
27
|
+
*/
|
|
28
|
+
export declare const standards: DefaultStandards;
|
|
6
29
|
/**
|
|
7
30
|
* Every caller-supplied path segment is percent-encoded: `objectName` and `id`
|
|
8
31
|
* come from the application, and an id such as `../../bundles/x` must
|
|
9
32
|
* never leave `/records/<object>/`.
|
|
10
33
|
*/
|
|
11
34
|
export declare function recordsPath(objectName: string, ...segments: string[]): string;
|
|
12
|
-
export { type ActorType, type AnyBundle, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type BundlesSync, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DeleteManyError, type DeleteManyResult, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type RecordAccessRole, type RecordAudience, type RecordCreateOptions, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordUpdateOptions, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, type StandardsOf, StandardsRequestError, type StandardsTransport, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UsageBucket, type UsageModality, type UsageReport, type UsageScope, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, syncBundle, text, today, user };
|
|
35
|
+
export { type ActingStandards, type ActorId, type ActorType, type AnyBundle, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type BundlesSync, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DefaultStandards, type DeleteManyError, type DeleteManyResult, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type OperationCaller, type RecordAccessRole, type RecordAudience, type RecordCreateOptions, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordUpdateOptions, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, type Register, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, type StandardsOf, StandardsRequestError, type StandardsTransport, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UsageBucket, type UsageModality, type UsageReport, type UsageScope, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, syncBundle, text, today, user };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,35 @@
|
|
|
1
1
|
|
|
2
|
-
import { A as
|
|
3
|
-
import {
|
|
2
|
+
import { A as SyncBundleOptions, C as UntypedBuilder, D as UpdateManyResult, E as UpdateManyError, M as syncBundle, O as createRecordsQuery, S as RecordsQuery, T as UpdateManyEntry, _ as RecordInput, a as ObjectsOfBundles, b as RecordsAggregateOptions, c as StandardsOf, d as CreateManyError, f as CreateManyResult, g as RecordCreateOptions, h as FetchResult, i as ObjectsOf, j as SyncTransport, k as CamelCase, l as StandardsTransport, m as DeleteManyResult, n as AnyBundle, o as Standards, p as DeleteManyError, r as BundlesSync, s as StandardsConfig, t as ActingStandards, u as createStandards, v as RecordUpdate, w as UntypedRecordsQuery, x as RecordsExportOptions, y as RecordUpdateOptions } from "./create-standards-De7-xdtZ.js";
|
|
3
|
+
import { F as StandardsRequestError, M as BundleValidationError, N as StandardsAuthError, O as createTransport, P as StandardsConfigurationError, T as TransportConfig, b as MultipartRequestOptions, j as BundleConflictError, w as Transport } from "./app-_CiXRLoD.js";
|
|
4
4
|
import { ActorType, Attribute, BUNDLE_NAME_PATTERN, BuiltBundle, BundleBuilder, BundlePiece, CollectionPage, CollectionResponse, ContentViewDefinition, DuplicateError, ExtractRecord, ExtractRecordInput, ExtractRecordInputStrict, ExtractRecordStrict, ExtractRecordUpdate, ExtractRecordUpdateStrict, FilterCombinator, FilterOperator, FilterRule, FilterState, ForbiddenError, InstalledBundleSummary, NotFoundError, ObjectBuilderLike, ObjectDefinition, RecordAccessRole, RecordAudience, RecordMetadata, SchemaError, SchemaErrorCode, SchemaSourceCurrencyRetype, SchemaSourcePhoneRetype, SchemaSourceRename, SchemaSourceResolution, SchemaSourceRetype, SortDirection, SortRule, SyncBundleResult, UsageBucket, UsageModality, UsageReport, UsageScope, ValidationError, ViewContentDefinition, ViewDeclaration, ViewerAccess, WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, currency, currentActor, date, detailView, document, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, text, today, user } from "@standards/schema";
|
|
5
|
-
import { encodePathSegment } from "@standards/schema/api";
|
|
5
|
+
import { ActorId, OperationCaller, encodePathSegment } from "@standards/schema/api";
|
|
6
|
+
/**
|
|
7
|
+
* Declare your bundle once, and the default `standards` instance is typed by
|
|
8
|
+
* it:
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* declare module "@standards/client" {
|
|
12
|
+
* interface Register { bundle: typeof crm }
|
|
13
|
+
* }
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
interface Register {}
|
|
17
|
+
type RegisteredObjects = Register extends {
|
|
18
|
+
bundle: infer B extends AnyBundle;
|
|
19
|
+
} ? B["objectBuilders"] : readonly [];
|
|
20
|
+
/** The default instance's type: the registered bundle's objects, and `as`. */
|
|
21
|
+
type DefaultStandards = ActingStandards<StandardsOf<RegisteredObjects>>;
|
|
22
|
+
/**
|
|
23
|
+
* The ready instance: `import { standards } from "@standards/client"` and
|
|
24
|
+
* call it. Its transport is resolved on first use (see {@link resolved}); its
|
|
25
|
+
* types come from {@link Register}. `createStandards` stays for several
|
|
26
|
+
* instances or another workspace.
|
|
27
|
+
*/
|
|
28
|
+
export declare const standards: DefaultStandards;
|
|
6
29
|
/**
|
|
7
30
|
* Every caller-supplied path segment is percent-encoded: `objectName` and `id`
|
|
8
31
|
* come from the application, and an id such as `../../bundles/x` must
|
|
9
32
|
* never leave `/records/<object>/`.
|
|
10
33
|
*/
|
|
11
34
|
export declare function recordsPath(objectName: string, ...segments: string[]): string;
|
|
12
|
-
export { type ActorType, type AnyBundle, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type BundlesSync, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DeleteManyError, type DeleteManyResult, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type RecordAccessRole, type RecordAudience, type RecordCreateOptions, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordUpdateOptions, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, type StandardsOf, StandardsRequestError, type StandardsTransport, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UsageBucket, type UsageModality, type UsageReport, type UsageScope, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, syncBundle, text, today, user };
|
|
35
|
+
export { type ActingStandards, type ActorId, type ActorType, type AnyBundle, type Attribute, BUNDLE_NAME_PATTERN, type BuiltBundle, type BundleBuilder, BundleConflictError, type BundlePiece, BundleValidationError, type BundlesSync, type CamelCase, type CollectionPage, type CollectionResponse, type ContentViewDefinition, type CreateManyError, type CreateManyResult, type DefaultStandards, type DeleteManyError, type DeleteManyResult, DuplicateError, type ExtractRecord, type ExtractRecordInput, type ExtractRecordInputStrict, type ExtractRecordStrict, type ExtractRecordUpdate, type ExtractRecordUpdateStrict, type FetchResult, type FilterCombinator, type FilterOperator, type FilterRule, type FilterState, ForbiddenError, type InstalledBundleSummary, type MultipartRequestOptions, NotFoundError, type ObjectBuilderLike, type ObjectDefinition, type ObjectsOf, type ObjectsOfBundles, type OperationCaller, type RecordAccessRole, type RecordAudience, type RecordCreateOptions, type RecordInput, type RecordMetadata, type RecordUpdate, type RecordUpdateOptions, type RecordsAggregateOptions, type RecordsExportOptions, type RecordsQuery, type Register, SchemaError, SchemaErrorCode, type SchemaSourceCurrencyRetype, type SchemaSourcePhoneRetype, type SchemaSourceRename, type SchemaSourceResolution, type SchemaSourceRetype, type SortDirection, type SortRule, type Standards, StandardsAuthError, type StandardsConfig, StandardsConfigurationError, type StandardsOf, StandardsRequestError, type StandardsTransport, type SyncBundleOptions, type SyncBundleResult, type SyncTransport, type Transport, type TransportConfig, type UntypedBuilder, type UntypedRecordsQuery, type UpdateManyEntry, type UpdateManyError, type UpdateManyResult, type UsageBucket, type UsageModality, type UsageReport, type UsageScope, ValidationError, type ViewContentDefinition, type ViewDeclaration, type ViewerAccess, type WalletState, assertBundleName, bundle, canonicalStringify, checkbox, content, createRecordsQuery, createStandards, createTransport, currency, currentActor, date, detailView, document, encodePathSegment, formula, group, listView, location, multiselect, now, number, object, phone, query, relation, richtext, rollup, select, status, syncBundle, text, today, user };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./create-standards-
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./create-standards-2D3Tmvj1.js"),t=require("./app-BgWz3r5k.js");let n=require("@standards/schema/api"),r=require("@standards/schema");const i=/* @__PURE__ */ new WeakMap;let a;function resolved(){let r=(0,n.registeredOperationHost)();if(r!==void 0){let n=i.get(r);return n===void 0&&(n=e.t(t.n(r.host),r.objects),i.set(r,n)),n}if(a===void 0){let n;try{n=e.r({})}catch(e){throw e instanceof t.m?new t.m(`The default standards instance found no Standards host in this process (a server embedding Standards registers one at boot), so it calls the API over HTTP, and ${e.message}`):e}a=e.t(t.i(n),[])}return a}function asOverHttp(e){throw new t.m(`standards.as() acts in process only, in a server that embeds Standards: over HTTP every call acts as the API key's actor. Use a key of the actor you want instead.`)}const o=new Proxy({},{get(e,t){if(typeof t==`symbol`||t===`then`)return;let n=resolved();return t===`as`&&!(`as`in n)?asOverHttp:Reflect.get(n,t)},has:(e,t)=>Reflect.has(resolved(),t),ownKeys:()=>Reflect.ownKeys(resolved()),getOwnPropertyDescriptor(e,t){let n=Reflect.getOwnPropertyDescriptor(resolved(),t);return n===void 0?void 0:{...n,configurable:!0}}});Object.defineProperty(exports,"BUNDLE_NAME_PATTERN",{enumerable:!0,get:function(){return r.BUNDLE_NAME_PATTERN}}),exports.BundleConflictError=t.d,exports.BundleValidationError=t.f,Object.defineProperty(exports,"DuplicateError",{enumerable:!0,get:function(){return r.DuplicateError}}),Object.defineProperty(exports,"ForbiddenError",{enumerable:!0,get:function(){return r.ForbiddenError}}),Object.defineProperty(exports,"NotFoundError",{enumerable:!0,get:function(){return r.NotFoundError}}),Object.defineProperty(exports,"SchemaError",{enumerable:!0,get:function(){return r.SchemaError}}),Object.defineProperty(exports,"SchemaErrorCode",{enumerable:!0,get:function(){return r.SchemaErrorCode}}),exports.StandardsAuthError=t.p,exports.StandardsConfigurationError=t.m,exports.StandardsRequestError=t.h,Object.defineProperty(exports,"ValidationError",{enumerable:!0,get:function(){return r.ValidationError}}),Object.defineProperty(exports,"assertBundleName",{enumerable:!0,get:function(){return r.assertBundleName}}),Object.defineProperty(exports,"bundle",{enumerable:!0,get:function(){return r.bundle}}),Object.defineProperty(exports,"canonicalStringify",{enumerable:!0,get:function(){return r.canonicalStringify}}),Object.defineProperty(exports,"checkbox",{enumerable:!0,get:function(){return r.checkbox}}),Object.defineProperty(exports,"content",{enumerable:!0,get:function(){return r.content}}),exports.createRecordsQuery=e.i,exports.createStandards=e.n,exports.createTransport=t.i,Object.defineProperty(exports,"currency",{enumerable:!0,get:function(){return r.currency}}),Object.defineProperty(exports,"currentActor",{enumerable:!0,get:function(){return r.currentActor}}),Object.defineProperty(exports,"date",{enumerable:!0,get:function(){return r.date}}),Object.defineProperty(exports,"detailView",{enumerable:!0,get:function(){return r.detailView}}),Object.defineProperty(exports,"document",{enumerable:!0,get:function(){return r.document}}),Object.defineProperty(exports,"encodePathSegment",{enumerable:!0,get:function(){return n.encodePathSegment}}),Object.defineProperty(exports,"formula",{enumerable:!0,get:function(){return r.formula}}),Object.defineProperty(exports,"group",{enumerable:!0,get:function(){return r.group}}),Object.defineProperty(exports,"listView",{enumerable:!0,get:function(){return r.listView}}),Object.defineProperty(exports,"location",{enumerable:!0,get:function(){return r.location}}),Object.defineProperty(exports,"multiselect",{enumerable:!0,get:function(){return r.multiselect}}),Object.defineProperty(exports,"now",{enumerable:!0,get:function(){return r.now}}),Object.defineProperty(exports,"number",{enumerable:!0,get:function(){return r.number}}),Object.defineProperty(exports,"object",{enumerable:!0,get:function(){return r.object}}),Object.defineProperty(exports,"phone",{enumerable:!0,get:function(){return r.phone}}),Object.defineProperty(exports,"query",{enumerable:!0,get:function(){return r.query}}),exports.recordsPath=t.s,Object.defineProperty(exports,"relation",{enumerable:!0,get:function(){return r.relation}}),Object.defineProperty(exports,"richtext",{enumerable:!0,get:function(){return r.richtext}}),Object.defineProperty(exports,"rollup",{enumerable:!0,get:function(){return r.rollup}}),Object.defineProperty(exports,"select",{enumerable:!0,get:function(){return r.select}}),exports.standards=o,Object.defineProperty(exports,"status",{enumerable:!0,get:function(){return r.status}}),exports.syncBundle=e.s,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{i as e,n as t,r as n,s as r,t as i}from"./create-standards-CZ_ZYNz8.mjs";import{d as a,f as o,h as s,i as c,m as l,n as u,p as d,s as f}from"./app-TJt8rk9y.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,registeredOperationHost as Y}from"@standards/schema/api";const X=/* @__PURE__ */ new WeakMap;let Z;function resolved(){let e=Y();if(e!==void 0){let t=X.get(e);return t===void 0&&(t=i(u(e.host),e.objects),X.set(e,t)),t}if(Z===void 0){let e;try{e=n({})}catch(e){throw e instanceof l?new l(`The default standards instance found no Standards host in this process (a server embedding Standards registers one at boot), so it calls the API over HTTP, and ${e.message}`):e}Z=i(c(e),[])}return Z}function asOverHttp(e){throw new l(`standards.as() acts in process only, in a server that embeds Standards: over HTTP every call acts as the API key's actor. Use a key of the actor you want instead.`)}const Q=new Proxy({},{get(e,t){if(typeof t==`symbol`||t===`then`)return;let n=resolved();return t===`as`&&!(`as`in n)?asOverHttp:Reflect.get(n,t)},has:(e,t)=>Reflect.has(resolved(),t),ownKeys:()=>Reflect.ownKeys(resolved()),getOwnPropertyDescriptor(e,t){let n=Reflect.getOwnPropertyDescriptor(resolved(),t);return n===void 0?void 0:{...n,configurable:!0}}});export{p as BUNDLE_NAME_PATTERN,a as BundleConflictError,o as BundleValidationError,m as DuplicateError,h as ForbiddenError,g as NotFoundError,_ as SchemaError,v as SchemaErrorCode,d as StandardsAuthError,l as StandardsConfigurationError,s as StandardsRequestError,y as ValidationError,b as assertBundleName,x as bundle,S as canonicalStringify,C as checkbox,w as content,e as createRecordsQuery,t as createStandards,c 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,f as recordsPath,B as relation,V as richtext,H as rollup,U as select,Q as standards,W as status,r as syncBundle,G as text,K as today,q as user};
|
package/dist/testing.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
import "./app-
|
|
2
|
+
import { a as ObjectsOfBundles, c as StandardsOf, n as AnyBundle } from "./create-standards-lDN6ru8u.mjs";
|
|
3
|
+
import "./app-_CiXRLoD.mjs";
|
|
4
4
|
import { ExtractRecord, ExtractRecordInputStrict, ObjectBuilderLike } from "@standards/schema";
|
|
5
5
|
/**
|
|
6
6
|
* A filter rule the in-memory workspace does not serve. The server answers
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
import {
|
|
3
|
-
import "./app-
|
|
2
|
+
import { a as ObjectsOfBundles, c as StandardsOf, n as AnyBundle } from "./create-standards-De7-xdtZ.js";
|
|
3
|
+
import "./app-_CiXRLoD.js";
|
|
4
4
|
import { ExtractRecord, ExtractRecordInputStrict, ObjectBuilderLike } from "@standards/schema";
|
|
5
5
|
/**
|
|
6
6
|
* A filter rule the in-memory workspace does not serve. The server answers
|
package/dist/testing.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./create-standards-CqOOm8eg.js"),t=require("./app-d25WfBqA.js");let n=require("@standards/schema"),r=require("@standards/schema/api");var UnsupportedFilterOperatorError=class extends Error{constructor(e,t){super(`The in-memory test workspace does not serve the "${e}" operator (on "${t}"). Test it against a real workspace.`),this.name=`UnsupportedFilterOperatorError`,this.operator=e}};const i=/* @__PURE__ */ new Set([`id`,`createdAt`,`updatedAt`]),a=/* @__PURE__ */ new Set([`createdAt`,`updatedAt`]),o=/* @__PURE__ */ new Set([`number`,`currency`]),s=/* @__PURE__ */ new Set([`select`,`status`]),c=/^\d{4}-\d{2}-\d{2}/,l=/^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:[T ]((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,6})?)?)(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;function attributeValue(e,t){if(i.has(t))return e[t];let n=e.values[t];return typeof n==`object`&&n&&`value`in n&&!Array.isArray(n)?n.value:n}function isEmptyValue(e){return e==null||e===``||Array.isArray(e)&&e.length===0}function textOf(e){return e==null?null:e instanceof Date?e.toISOString():typeof e==`string`?e:JSON.stringify(e)}function members(e){return Array.isArray(e)?e.map(String):null}function dayOf(e){let t=textOf(e);if(t===null||!c.test(t))return null;let n=t.slice(0,10);return Number.isNaN(Date.parse(`${n}T00:00:00.000Z`))?null:n}const u=Date.parse(`0001-01-01T00:00:00Z`);function instantOf(e){let t=typeof e==`object`&&e&&`start`in e?e.start:e,n=typeof t==`string`?l.exec(t):null;if(!n)return null;let[,r=``,i=`00:00`,a=`Z`]=n;if(r.startsWith(`0000`))return null;let o=a===`Z`?`Z`:`${a.slice(0,3)}:${a.slice(3).replace(`:`,``)||`00`}`,s=Date.parse(`${r}T${i}${o}`);return Number.isNaN(s)||(/* @__PURE__ */ new Date(`${r}T00:00:00Z`)).toISOString().slice(0,10)!==r||s<u?null:s}function nextDay(e){let t=/* @__PURE__ */ new Date(`${e}T00:00:00.000Z`);return t.setUTCDate(t.getUTCDate()+1),t.toISOString().slice(0,10)}function isUnmodelledDate(e){if(e?.type!==`date`)return!1;let t=e;return t.endDate===!0||t.includeTime===!0}function isTimedDate(e){return e?.type===`date`&&e.includeTime===!0}function matchesDay(e,t,n,r){let i=dayOf(n);if(i===null)return!1;let a=textOf(t),o=nextDay(i),s=r?textOf(n)??i:i;switch(e){case`is`:return a!==null&&a>=s&&a<o;case`is_not`:return a===null||a<s||a>=o;case`greater_than`:return a!==null&&a>=o;case`greater_or_equal`:return a!==null&&a>=s;case`less_than`:return a!==null&&a<s;default:return a!==null&&a<o}}function compare(e,t,n){let r=textOf(e),i=textOf(t);if(r===null||i===null)return null;if(n){let e=Number(r),t=Number(i);return r===``||Number.isNaN(e)||Number.isNaN(t)?null:e-t}return r<i?-1:+(r>i)}function matchesRule(e,t,r){let i=r.attributes.find(e=>e.name===t.attribute)?.type,s=attributeValue(e,t.attribute),c=i!==void 0&&o.has(i),l=textOf(t.value),u=l===null?void 0:(0,n.foldText)(l),d=textOf(s),f=d===null?null:(0,n.foldText)(d);if((i===`date`||a.has(t.attribute))&&[`is`,`is_not`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`].includes(t.operator))return matchesDay(t.operator,s,t.value,a.has(t.attribute));switch(t.operator){case`is`:return i===`checkbox`||i===void 0&&typeof t.value==`boolean`?t.value===!0?s===!0:s!==!0:textOf(s)!==null&&textOf(s)===textOf(t.value);case`is_not`:return textOf(s)===null||textOf(s)!==textOf(t.value);case`contains`:return Array.isArray(s)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>s.map(String).includes(e)):f!==null&&u!==void 0&&f.includes(u);case`not_contains`:return s==null||!matchesRule(e,{...t,operator:`contains`},r);case`starts_with`:return f!==null&&u!==void 0&&f.startsWith(u);case`ends_with`:return f!==null&&u!==void 0&&f.endsWith(u);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(s,t.value,c);return e===null?!1:t.operator===`greater_than`?e>0:t.operator===`greater_or_equal`?e>=0:t.operator===`less_than`?e<0:e<=0}case`is_empty`:return isEmptyValue(s);case`is_not_empty`:return!isEmptyValue(s);case`any_of`:{let e=members(t.value);return e===null||e.length===0||s==null?!1:Array.isArray(s)?s.some(t=>e.includes(String(t))):e.includes(textOf(s)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||s==null?!0:Array.isArray(s)?!s.some(t=>e.includes(String(t))):!e.includes(textOf(s)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const d=/* @__PURE__ */ new Set([`is`,`is_not`,`contains`,`not_contains`,`starts_with`,`ends_with`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`,`is_empty`,`is_not_empty`,`any_of`,`none_of`]);function assertServedOperators(e,t){for(let n of e?.rules??[])if(!d.has(n.operator)||n.attribute.startsWith(`metadata.`)||isUnmodelledDate(t.attributes.find(e=>e.name===n.attribute))&&n.operator!==`is_empty`&&n.operator!==`is_not_empty`)throw new UnsupportedFilterOperatorError(n.operator,n.attribute)}function matchesFilters(e,t,n){let r=t?.rules??[];if(r.length===0)return!0;let i=r.map(t=>matchesRule(e,t,n));return t?.combinator===`or`?i.some(Boolean):i.every(Boolean)}function matchesSearch(e,t){let n=t.trim().toLowerCase();return n===``||Object.values(e.values).some(e=>(Array.isArray(e)?e:[e]).some(e=>typeof e==`string`&&e.toLowerCase().includes(n)))}function sortKey(e,t,n){let r=attributeValue(e,t),i=n.attributes.find(e=>e.name===t);if(i&&s.has(i.type)){let e=(i.options??[]).findIndex(e=>e.value===r);return{position:e===-1?null:e,value:r}}return r}function isOptionKey(e){return typeof e==`object`&&!!e&&`position`in e}function compareOptionKeys(e,t,n){let r=n===`desc`?-1:1;return e.position!==null&&t.position!==null?r*(e.position-t.position):e.position!==null||t.position!==null?e.position===null?1:-1:r*(compare(e.value,t.value,!1)??0)}function compareInstants(e,t,n){let r=instantOf(e.values[n.attribute]),i=instantOf(t.values[n.attribute]);return r===i?0:r===null||i===null?r===null?1:-1:n.direction===`desc`?i-r:r-i}function compareRecords(e,t){let n=e&&e.length>0?[...e]:[{attribute:`createdAt`,direction:`desc`}];return n.some(e=>e.attribute===`id`)||n.push({attribute:`id`,direction:`asc`}),(e,r)=>{for(let i of n){let n=t.attributes.find(e=>e.name===i.attribute),a=n?.type;if(isTimedDate(n)){let t=compareInstants(e,r,i);if(t!==0)return t;continue}let s=sortKey(e,i.attribute,t),c=sortKey(r,i.attribute,t),l=isOptionKey(s)?s.value:s,u=isOptionKey(c)?c.value:c,d=textOf(l)===null,f=textOf(u)===null;if(d||f){if(d&&f)continue;return d?1:-1}if(isOptionKey(s)&&isOptionKey(c)){let e=compareOptionKeys(s,c,i.direction);if(e!==0)return e;continue}let p=compare(s,c,a!==void 0&&o.has(a))??0;if(p!==0)return i.direction===`desc`?-p:p}return 0}}const f=`SCHEMA_RECORD_NOT_FOUND`,p=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,m=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...(0,n.getObjectSystemAttributes)(e)]}}function withoutSystemKeys(e){let t={...e};for(let e of m)delete t[e];return t}function boundOf(e,n,r){if(e==null)return r;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new t.h(400,`${n} must be a non-negative integer`);return e}function errorFor(e,n,r){return e===401||e===403?new t.p(e,n,r):new t.h(e,n,r)}function asTheServerValidates(e){try{e()}catch(e){throw e instanceof n.ValidationError?new t.h(400,e.message,e.code):e}}function notServed(e,n){return new t.h(501,`The in-memory test workspace does not serve ${e} ${n}: only the records API is in memory.`)}function isoOf(e,t){return e===void 0?t:e instanceof Date?e.toISOString():new Date(e).toISOString()}function wire(e){return JSON.parse(JSON.stringify(e))}function createInMemoryApi(i){let a=/* @__PURE__ */ new Map;for(let t of i.builders){let n=e.i(t);a.set(n.name,n)}let o=new Map([...a.keys()].map(e=>[e,[]])),s=/* @__PURE__ */ new Set,c=null,l=0,u=1;function now(){return l=Math.max(Date.now(),l+1),new Date(l).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(u++).toString(16).padStart(12,`0`)}`;while(s.has(e));return e}function objectOf(e){let n=a.get(e),r=o.get(e);if(!(n&&r))throw new t.h(404,`Object "${e}" not found. Make sure the object exists and you have access to it.`);return{definition:n,records:r}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:i,updatedAt:a,...o}=t,c=now(),l={id:r??newId(),values:wire(o),createdAt:isoOf(i,c),updatedAt:isoOf(a,isoOf(i,c)),visibility:`workspace`,ownedBy:null,metadata:{},objectId:objectOf(e).definition.id??e,label:``,parentId:null,ancestorIds:[],trashedWithRecordId:null,schemaVersion:1};return n.push(l),s.add(l.id),l}function find(e,n){let r=objectOf(e).records.find(e=>e.id===n);if(!r)throw new t.h(404,readNotFound(n),f);return r}function requireWritable(e,n){if(!objectOf(e).records.some(e=>e.id===n))throw new t.h(404,writeNotFound(n),f)}function update(e,n,r){let i=objectOf(e).records.find(e=>e.id===n);if(!i)throw new t.h(404,writeNotFound(n),f);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(e,n){let{records:r}=objectOf(e),i=r.findIndex(e=>e.id===n);if(i===-1)throw new t.h(404,writeNotFound(n),f);r.splice(i,1)}function list(e,t,r){let{definition:i,records:a}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>(0,n.validateQualifiedRule)(structuredClone(e),{attributes:i.attributes}));assertServedOperators(t.filters,i);let o=Math.min(boundOf(t.limit,`limit`,20),1e3),s=boundOf(t.offset,`offset`,0);if(o===0)return{data:[],page:{hasMore:!1,total:null,countMode:`none`}};let c=r?t.q:void 0,l=a.filter(e=>matchesFilters(e,t.filters,i)).filter(e=>c===void 0||matchesSearch(e,c)).sort(compareRecords(t.sorts,i)),u=l.slice(s,s+o);return{data:u,page:{hasMore:s+u.length<l.length,total:null,countMode:`none`}}}function bulk(e,r,i){let a=i.records??i.updates??i.ids;if(!Array.isArray(a)||a.length>100)throw new t.h(400,`A bulk request carries at most 100 items.`);let o=withSystemAttributes(objectOf(e).definition);if(r===`bulk-create`){let r=[],i=[];for(let[s,c]of a.entries())if(!(0,n.isPlainRecord)(c))i.push({index:s,error:`Record data must be an object`});else try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(insert(e,withoutSystemKeys(c)))}catch(e){if(!(e instanceof t.h))throw e;i.push({index:s,error:e.message})}return{created:r,errors:i}}if(r===`bulk-update`){let r=[],i=[];for(let{id:s,data:c}of a)try{if(!(0,n.isPlainRecord)(c))throw new t.h(400,`Update data must be an object`,p);requireWritable(e,s),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(update(e,s,c))}catch(e){if(!(e instanceof t.h))throw e;i.push({id:s,error:e.message,code:e.code??p})}return{updated:r,errors:i}}let s=[],c=[];for(let t of a)try{remove(e,t),s.push(t)}catch{c.push({id:t,error:writeNotFound(t),code:f})}return{deleted:s,errors:c}}function operation(e,r,i){let o=Array.isArray(i.steps)?i.steps:[],[s]=o;if(o.length!==1||!(0,n.isPlainRecord)(s)||s.kind!==`record.set`)throw notServed(e,r);let c=String(s.recordId),l=(0,n.isPlainRecord)(s.values)?s.values:{},u=[...a].find(([e,t])=>(t.id??e)===s.objectId)?.[0],answer=e=>({opId:i.opId,steps:[e],inverse:null});if(u===void 0||!objectOf(u).records.some(e=>e.id===c))return answer({status:`error`,recordId:c,code:f});try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(u).definition),l))}catch(e){if(!(e instanceof t.h))throw e;let n=e.code??p;return answer({status:`error`,recordId:c,code:n,...n===p&&{message:e.message}})}return answer({status:`applied`,record:update(u,c,l)})}function route(e,r,i){let[a,o,s,...c]=r.replace(/^\/+/,``).split(`/`);if(e===`POST`&&a===`operations`&&o===void 0)return operation(e,r,(0,n.isPlainRecord)(i)?i:{});if(a!==`records`||o===void 0||c.length>0)throw notServed(e,r);let l=decodeURIComponent(o),u=s===void 0?void 0:decodeURIComponent(s),d=(0,n.isPlainRecord)(i)?i:{};if(e===`POST`&&u===void 0){let e=(0,n.isPlainRecord)(d.data)?d.data:{};return asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(e===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(e===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(e,r);if(e===`GET`)return find(l,u);if(e===`PUT`||e===`PATCH`){if(Object.keys(d).length===0)throw new t.h(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(e===`DELETE`)return remove(l,u),null;throw notServed(e,r)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(c){let{status:e,failure:t}=c;throw c=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let d={call:(e,t)=>Promise.resolve().then(()=>{let{path:n,body:i}=(0,r.splitOperationInput)(e,t??{});return request(e.method,n,i).then(t=>(0,r.decodeOperationOutput)(e,t??null))}),stream:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=(0,r.splitOperationInput)(e,t??{});throw notServed(e.method,n)}),get:e=>request(`GET`,e),post:(e,t)=>request(`POST`,e,t),patch:(e,t)=>request(`PATCH`,e,t),put:(e,t)=>request(`PUT`,e,t),delete:e=>request(`DELETE`,e),getText:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`GET`,e)}),postRaw:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`POST`,e)}),postMultipart:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`POST`,e)})};return{transport:d,get:d.get,post:d.post,definitionOf:e=>objectOf(e).definition,seed:(e,t)=>t.map(t=>insert(e,t)),records:e=>objectOf(e).records,failNextRequestWith(e,t={}){c={status:e,failure:t}}}}function createTestStandards(t){let n=t.bundles.flatMap(e=>e.objectBuilders),i=createInMemoryApi({builders:n}),flatten=(t,n)=>e.a(i.definitionOf(t),(0,r.decodeOperationOutput)(r.recordsOperations.get,JSON.parse(JSON.stringify(n))));return{db:e.t(i.transport,n),seed:(e,t)=>i.seed(e,t).map(t=>flatten(e,t)),records:e=>i.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>i.failNextRequestWith(e,t)}}exports.UnsupportedFilterOperatorError=UnsupportedFilterOperatorError,exports.createTestStandards=createTestStandards;
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./create-standards-2D3Tmvj1.js"),t=require("./app-BgWz3r5k.js");let n=require("@standards/schema"),r=require("@standards/schema/api");var UnsupportedFilterOperatorError=class extends Error{constructor(e,t){super(`The in-memory test workspace does not serve the "${e}" operator (on "${t}"). Test it against a real workspace.`),this.name=`UnsupportedFilterOperatorError`,this.operator=e}};const i=/* @__PURE__ */ new Set([`id`,`createdAt`,`updatedAt`]),a=/* @__PURE__ */ new Set([`createdAt`,`updatedAt`]),o=/* @__PURE__ */ new Set([`number`,`currency`]),s=/* @__PURE__ */ new Set([`select`,`status`]),c=/^\d{4}-\d{2}-\d{2}/,l=/^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:[T ]((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,6})?)?)(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;function attributeValue(e,t){if(i.has(t))return e[t];let n=e.values[t];return typeof n==`object`&&n&&`value`in n&&!Array.isArray(n)?n.value:n}function isEmptyValue(e){return e==null||e===``||Array.isArray(e)&&e.length===0}function textOf(e){return e==null?null:e instanceof Date?e.toISOString():typeof e==`string`?e:JSON.stringify(e)}function members(e){return Array.isArray(e)?e.map(String):null}function dayOf(e){let t=textOf(e);if(t===null||!c.test(t))return null;let n=t.slice(0,10);return Number.isNaN(Date.parse(`${n}T00:00:00.000Z`))?null:n}const u=Date.parse(`0001-01-01T00:00:00Z`);function instantOf(e){let t=typeof e==`object`&&e&&`start`in e?e.start:e,n=typeof t==`string`?l.exec(t):null;if(!n)return null;let[,r=``,i=`00:00`,a=`Z`]=n;if(r.startsWith(`0000`))return null;let o=a===`Z`?`Z`:`${a.slice(0,3)}:${a.slice(3).replace(`:`,``)||`00`}`,s=Date.parse(`${r}T${i}${o}`);return Number.isNaN(s)||(/* @__PURE__ */ new Date(`${r}T00:00:00Z`)).toISOString().slice(0,10)!==r||s<u?null:s}function nextDay(e){let t=/* @__PURE__ */ new Date(`${e}T00:00:00.000Z`);return t.setUTCDate(t.getUTCDate()+1),t.toISOString().slice(0,10)}function isUnmodelledDate(e){if(e?.type!==`date`)return!1;let t=e;return t.endDate===!0||t.includeTime===!0}function isTimedDate(e){return e?.type===`date`&&e.includeTime===!0}function matchesDay(e,t,n,r){let i=dayOf(n);if(i===null)return!1;let a=textOf(t),o=nextDay(i),s=r?textOf(n)??i:i;switch(e){case`is`:return a!==null&&a>=s&&a<o;case`is_not`:return a===null||a<s||a>=o;case`greater_than`:return a!==null&&a>=o;case`greater_or_equal`:return a!==null&&a>=s;case`less_than`:return a!==null&&a<s;default:return a!==null&&a<o}}function compare(e,t,n){let r=textOf(e),i=textOf(t);if(r===null||i===null)return null;if(n){let e=Number(r),t=Number(i);return r===``||Number.isNaN(e)||Number.isNaN(t)?null:e-t}return r<i?-1:+(r>i)}function matchesRule(e,t,r){let i=r.attributes.find(e=>e.name===t.attribute)?.type,s=attributeValue(e,t.attribute),c=i!==void 0&&o.has(i),l=textOf(t.value),u=l===null?void 0:(0,n.foldText)(l),d=textOf(s),f=d===null?null:(0,n.foldText)(d);if((i===`date`||a.has(t.attribute))&&[`is`,`is_not`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`].includes(t.operator))return matchesDay(t.operator,s,t.value,a.has(t.attribute));switch(t.operator){case`is`:return i===`checkbox`||i===void 0&&typeof t.value==`boolean`?t.value===!0?s===!0:s!==!0:textOf(s)!==null&&textOf(s)===textOf(t.value);case`is_not`:return textOf(s)===null||textOf(s)!==textOf(t.value);case`contains`:return Array.isArray(s)?(Array.isArray(t.value)?t.value.map(String):[String(t.value)]).every(e=>s.map(String).includes(e)):f!==null&&u!==void 0&&f.includes(u);case`not_contains`:return s==null||!matchesRule(e,{...t,operator:`contains`},r);case`starts_with`:return f!==null&&u!==void 0&&f.startsWith(u);case`ends_with`:return f!==null&&u!==void 0&&f.endsWith(u);case`greater_than`:case`greater_or_equal`:case`less_than`:case`less_or_equal`:{let e=compare(s,t.value,c);return e===null?!1:t.operator===`greater_than`?e>0:t.operator===`greater_or_equal`?e>=0:t.operator===`less_than`?e<0:e<=0}case`is_empty`:return isEmptyValue(s);case`is_not_empty`:return!isEmptyValue(s);case`any_of`:{let e=members(t.value);return e===null||e.length===0||s==null?!1:Array.isArray(s)?s.some(t=>e.includes(String(t))):e.includes(textOf(s)??``)}case`none_of`:{let e=members(t.value);return e===null?!1:e.length===0||s==null?!0:Array.isArray(s)?!s.some(t=>e.includes(String(t))):!e.includes(textOf(s)??``)}default:throw new UnsupportedFilterOperatorError(t.operator,t.attribute)}}const d=/* @__PURE__ */ new Set([`is`,`is_not`,`contains`,`not_contains`,`starts_with`,`ends_with`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`,`is_empty`,`is_not_empty`,`any_of`,`none_of`]);function assertServedOperators(e,t){for(let n of e?.rules??[])if(!d.has(n.operator)||n.attribute.startsWith(`metadata.`)||isUnmodelledDate(t.attributes.find(e=>e.name===n.attribute))&&n.operator!==`is_empty`&&n.operator!==`is_not_empty`)throw new UnsupportedFilterOperatorError(n.operator,n.attribute)}function matchesFilters(e,t,n){let r=t?.rules??[];if(r.length===0)return!0;let i=r.map(t=>matchesRule(e,t,n));return t?.combinator===`or`?i.some(Boolean):i.every(Boolean)}function matchesSearch(e,t){let n=t.trim().toLowerCase();return n===``||Object.values(e.values).some(e=>(Array.isArray(e)?e:[e]).some(e=>typeof e==`string`&&e.toLowerCase().includes(n)))}function sortKey(e,t,n){let r=attributeValue(e,t),i=n.attributes.find(e=>e.name===t);if(i&&s.has(i.type)){let e=(i.options??[]).findIndex(e=>e.value===r);return{position:e===-1?null:e,value:r}}return r}function isOptionKey(e){return typeof e==`object`&&!!e&&`position`in e}function compareOptionKeys(e,t,n){let r=n===`desc`?-1:1;return e.position!==null&&t.position!==null?r*(e.position-t.position):e.position!==null||t.position!==null?e.position===null?1:-1:r*(compare(e.value,t.value,!1)??0)}function compareInstants(e,t,n){let r=instantOf(e.values[n.attribute]),i=instantOf(t.values[n.attribute]);return r===i?0:r===null||i===null?r===null?1:-1:n.direction===`desc`?i-r:r-i}function compareRecords(e,t){let n=e&&e.length>0?[...e]:[{attribute:`createdAt`,direction:`desc`}];return n.some(e=>e.attribute===`id`)||n.push({attribute:`id`,direction:`asc`}),(e,r)=>{for(let i of n){let n=t.attributes.find(e=>e.name===i.attribute),a=n?.type;if(isTimedDate(n)){let t=compareInstants(e,r,i);if(t!==0)return t;continue}let s=sortKey(e,i.attribute,t),c=sortKey(r,i.attribute,t),l=isOptionKey(s)?s.value:s,u=isOptionKey(c)?c.value:c,d=textOf(l)===null,f=textOf(u)===null;if(d||f){if(d&&f)continue;return d?1:-1}if(isOptionKey(s)&&isOptionKey(c)){let e=compareOptionKeys(s,c,i.direction);if(e!==0)return e;continue}let p=compare(s,c,a!==void 0&&o.has(a))??0;if(p!==0)return i.direction===`desc`?-p:p}return 0}}const f=`SCHEMA_RECORD_NOT_FOUND`,p=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,m=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...(0,n.getObjectSystemAttributes)(e)]}}function withoutSystemKeys(e){let t={...e};for(let e of m)delete t[e];return t}function boundOf(e,n,r){if(e==null)return r;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new t.h(400,`${n} must be a non-negative integer`);return e}function errorFor(e,n,r){return e===401||e===403?new t.p(e,n,r):new t.h(e,n,r)}function asTheServerValidates(e){try{e()}catch(e){throw e instanceof n.ValidationError?new t.h(400,e.message,e.code):e}}function notServed(e,n){return new t.h(501,`The in-memory test workspace does not serve ${e} ${n}: only the records API is in memory.`)}function isoOf(e,t){return e===void 0?t:e instanceof Date?e.toISOString():new Date(e).toISOString()}function wire(e){return JSON.parse(JSON.stringify(e))}function createInMemoryApi(i){let a=/* @__PURE__ */ new Map;for(let t of i.builders){let n=e.a(t);a.set(n.name,n)}let o=new Map([...a.keys()].map(e=>[e,[]])),s=/* @__PURE__ */ new Set,c=null,l=0,u=1;function now(){return l=Math.max(Date.now(),l+1),new Date(l).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(u++).toString(16).padStart(12,`0`)}`;while(s.has(e));return e}function objectOf(e){let n=a.get(e),r=o.get(e);if(!(n&&r))throw new t.h(404,`Object "${e}" not found. Make sure the object exists and you have access to it.`);return{definition:n,records:r}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:i,updatedAt:a,...o}=t,c=now(),l={id:r??newId(),values:wire(o),createdAt:isoOf(i,c),updatedAt:isoOf(a,isoOf(i,c)),visibility:`workspace`,ownedBy:null,metadata:{},objectId:objectOf(e).definition.id??e,label:``,parentId:null,ancestorIds:[],trashedWithRecordId:null,schemaVersion:1};return n.push(l),s.add(l.id),l}function find(e,n){let r=objectOf(e).records.find(e=>e.id===n);if(!r)throw new t.h(404,readNotFound(n),f);return r}function requireWritable(e,n){if(!objectOf(e).records.some(e=>e.id===n))throw new t.h(404,writeNotFound(n),f)}function update(e,n,r){let i=objectOf(e).records.find(e=>e.id===n);if(!i)throw new t.h(404,writeNotFound(n),f);return Object.assign(i.values,withoutSystemKeys(r)),i.updatedAt=now(),i}function remove(e,n){let{records:r}=objectOf(e),i=r.findIndex(e=>e.id===n);if(i===-1)throw new t.h(404,writeNotFound(n),f);r.splice(i,1)}function list(e,t,r){let{definition:i,records:a}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>(0,n.validateQualifiedRule)(structuredClone(e),{attributes:i.attributes}));assertServedOperators(t.filters,i);let o=Math.min(boundOf(t.limit,`limit`,20),1e3),s=boundOf(t.offset,`offset`,0);if(o===0)return{data:[],page:{hasMore:!1,total:null,countMode:`none`}};let c=r?t.q:void 0,l=a.filter(e=>matchesFilters(e,t.filters,i)).filter(e=>c===void 0||matchesSearch(e,c)).sort(compareRecords(t.sorts,i)),u=l.slice(s,s+o);return{data:u,page:{hasMore:s+u.length<l.length,total:null,countMode:`none`}}}function bulk(e,r,i){let a=i.records??i.updates??i.ids;if(!Array.isArray(a)||a.length>100)throw new t.h(400,`A bulk request carries at most 100 items.`);let o=withSystemAttributes(objectOf(e).definition);if(r===`bulk-create`){let r=[],i=[];for(let[s,c]of a.entries())if(!(0,n.isPlainRecord)(c))i.push({index:s,error:`Record data must be an object`});else try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(insert(e,withoutSystemKeys(c)))}catch(e){if(!(e instanceof t.h))throw e;i.push({index:s,error:e.message})}return{created:r,errors:i}}if(r===`bulk-update`){let r=[],i=[];for(let{id:s,data:c}of a)try{if(!(0,n.isPlainRecord)(c))throw new t.h(400,`Update data must be an object`,p);requireWritable(e,s),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(o,c)),r.push(update(e,s,c))}catch(e){if(!(e instanceof t.h))throw e;i.push({id:s,error:e.message,code:e.code??p})}return{updated:r,errors:i}}let s=[],c=[];for(let t of a)try{remove(e,t),s.push(t)}catch{c.push({id:t,error:writeNotFound(t),code:f})}return{deleted:s,errors:c}}function operation(e,r,i){let o=Array.isArray(i.steps)?i.steps:[],[s]=o;if(o.length!==1||!(0,n.isPlainRecord)(s)||s.kind!==`record.set`)throw notServed(e,r);let c=String(s.recordId),l=(0,n.isPlainRecord)(s.values)?s.values:{},u=[...a].find(([e,t])=>(t.id??e)===s.objectId)?.[0],answer=e=>({opId:i.opId,steps:[e],inverse:null});if(u===void 0||!objectOf(u).records.some(e=>e.id===c))return answer({status:`error`,recordId:c,code:f});try{asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(u).definition),l))}catch(e){if(!(e instanceof t.h))throw e;let n=e.code??p;return answer({status:`error`,recordId:c,code:n,...n===p&&{message:e.message}})}return answer({status:`applied`,record:update(u,c,l)})}function route(e,r,i){let[a,o,s,...c]=r.replace(/^\/+/,``).split(`/`);if(e===`POST`&&a===`operations`&&o===void 0)return operation(e,r,(0,n.isPlainRecord)(i)?i:{});if(a!==`records`||o===void 0||c.length>0)throw notServed(e,r);let l=decodeURIComponent(o),u=s===void 0?void 0:decodeURIComponent(s),d=(0,n.isPlainRecord)(i)?i:{};if(e===`POST`&&u===void 0){let e=(0,n.isPlainRecord)(d.data)?d.data:{};return asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),e)),insert(l,withoutSystemKeys(e))}if(e===`POST`&&(u===`list`||u===`search`))return list(l,d,u===`search`);if(e===`POST`&&u?.startsWith(`bulk-`))return bulk(l,u,d);if(u===void 0)throw notServed(e,r);if(e===`GET`)return find(l,u);if(e===`PUT`||e===`PATCH`){if(Object.keys(d).length===0)throw new t.h(400,`Request body cannot be empty`);return requireWritable(l,u),asTheServerValidates(()=>(0,n.rejectUnknownAttributesOrThrow)(withSystemAttributes(objectOf(l).definition),d)),update(l,u,d)}if(e===`DELETE`)return remove(l,u),null;throw notServed(e,r)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(c){let{status:e,failure:t}=c;throw c=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let d={call:(e,t)=>Promise.resolve().then(()=>{let{path:n,body:i}=(0,r.splitOperationInput)(e,t??{});return request(e.method,n,i).then(t=>(0,r.decodeOperationOutput)(e,t??null))}),stream:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=(0,r.splitOperationInput)(e,t??{});throw notServed(e.method,n)}),get:e=>request(`GET`,e),post:(e,t)=>request(`POST`,e,t),patch:(e,t)=>request(`PATCH`,e,t),put:(e,t)=>request(`PUT`,e,t),delete:e=>request(`DELETE`,e),getText:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`GET`,e)}),postRaw:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`POST`,e)}),postMultipart:e=>Promise.resolve().then(()=>{throw takeFailure(),notServed(`POST`,e)})};return{transport:d,get:d.get,post:d.post,definitionOf:e=>objectOf(e).definition,seed:(e,t)=>t.map(t=>insert(e,t)),records:e=>objectOf(e).records,failNextRequestWith(e,t={}){c={status:e,failure:t}}}}function createTestStandards(t){let n=t.bundles.flatMap(e=>e.objectBuilders),i=createInMemoryApi({builders:n}),flatten=(t,n)=>e.o(i.definitionOf(t),(0,r.decodeOperationOutput)(r.recordsOperations.get,JSON.parse(JSON.stringify(n))));return{db:e.t(i.transport,n),seed:(e,t)=>i.seed(e,t).map(t=>flatten(e,t)),records:e=>i.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>i.failNextRequestWith(e,t)}}exports.UnsupportedFilterOperatorError=UnsupportedFilterOperatorError,exports.createTestStandards=createTestStandards;
|
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{a as e,i as t,t as n}from"./create-standards-orKjtGR6.mjs";import{h as r,p as i}from"./app-CjHQKAwu.mjs";import{ValidationError as a,foldText as o,getObjectSystemAttributes as s,isPlainRecord as c,rejectUnknownAttributesOrThrow as l,validateQualifiedRule as u}from"@standards/schema";import{decodeOperationOutput as d,recordsOperations as f,splitOperationInput as p}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 m=/* @__PURE__ */ new Set([`id`,`createdAt`,`updatedAt`]),h=/* @__PURE__ */ new Set([`createdAt`,`updatedAt`]),g=/* @__PURE__ */ new Set([`number`,`currency`]),_=/* @__PURE__ */ new Set([`select`,`status`]),v=/^\d{4}-\d{2}-\d{2}/,y=/^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:[T ]((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,6})?)?)(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;function attributeValue(e,t){if(m.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||!v.test(t))return null;let n=t.slice(0,10);return Number.isNaN(Date.parse(`${n}T00:00:00.000Z`))?null:n}const b=Date.parse(`0001-01-01T00:00:00Z`);function instantOf(e){let t=typeof e==`object`&&e&&`start`in e?e.start:e,n=typeof t==`string`?y.exec(t):null;if(!n)return null;let[,r=``,i=`00:00`,a=`Z`]=n;if(r.startsWith(`0000`))return null;let o=a===`Z`?`Z`:`${a.slice(0,3)}:${a.slice(3).replace(`:`,``)||`00`}`,s=Date.parse(`${r}T${i}${o}`);return Number.isNaN(s)||(/* @__PURE__ */ new Date(`${r}T00:00:00Z`)).toISOString().slice(0,10)!==r||s<b?null:s}function nextDay(e){let t=/* @__PURE__ */ new Date(`${e}T00:00:00.000Z`);return t.setUTCDate(t.getUTCDate()+1),t.toISOString().slice(0,10)}function isUnmodelledDate(e){if(e?.type!==`date`)return!1;let t=e;return t.endDate===!0||t.includeTime===!0}function isTimedDate(e){return e?.type===`date`&&e.includeTime===!0}function matchesDay(e,t,n,r){let i=dayOf(n);if(i===null)return!1;let a=textOf(t),o=nextDay(i),s=r?textOf(n)??i:i;switch(e){case`is`:return a!==null&&a>=s&&a<o;case`is_not`:return a===null||a<s||a>=o;case`greater_than`:return a!==null&&a>=o;case`greater_or_equal`:return a!==null&&a>=s;case`less_than`:return a!==null&&a<s;default:return a!==null&&a<o}}function compare(e,t,n){let r=textOf(e),i=textOf(t);if(r===null||i===null)return null;if(n){let e=Number(r),t=Number(i);return r===``||Number.isNaN(e)||Number.isNaN(t)?null:e-t}return r<i?-1:+(r>i)}function matchesRule(e,t,n){let r=n.attributes.find(e=>e.name===t.attribute)?.type,i=attributeValue(e,t.attribute),a=r!==void 0&&g.has(r),s=textOf(t.value),c=s===null?void 0:o(s),l=textOf(i),u=l===null?null:o(l);if((r===`date`||h.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,h.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)):u!==null&&c!==void 0&&u.includes(c);case`not_contains`:return i==null||!matchesRule(e,{...t,operator:`contains`},n);case`starts_with`:return u!==null&&c!==void 0&&u.startsWith(c);case`ends_with`:return u!==null&&c!==void 0&&u.endsWith(c);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 x=/* @__PURE__ */ new Set([`is`,`is_not`,`contains`,`not_contains`,`starts_with`,`ends_with`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`,`is_empty`,`is_not_empty`,`any_of`,`none_of`]);function assertServedOperators(e,t){for(let n of e?.rules??[])if(!x.has(n.operator)||n.attribute.startsWith(`metadata.`)||isUnmodelledDate(t.attributes.find(e=>e.name===n.attribute))&&n.operator!==`is_empty`&&n.operator!==`is_not_empty`)throw new UnsupportedFilterOperatorError(n.operator,n.attribute)}function matchesFilters(e,t,n){let r=t?.rules??[];if(r.length===0)return!0;let i=r.map(t=>matchesRule(e,t,n));return t?.combinator===`or`?i.some(Boolean):i.every(Boolean)}function matchesSearch(e,t){let n=t.trim().toLowerCase();return n===``||Object.values(e.values).some(e=>(Array.isArray(e)?e:[e]).some(e=>typeof e==`string`&&e.toLowerCase().includes(n)))}function sortKey(e,t,n){let r=attributeValue(e,t),i=n.attributes.find(e=>e.name===t);if(i&&_.has(i.type)){let e=(i.options??[]).findIndex(e=>e.value===r);return{position:e===-1?null:e,value:r}}return r}function isOptionKey(e){return typeof e==`object`&&!!e&&`position`in e}function compareOptionKeys(e,t,n){let r=n===`desc`?-1:1;return e.position!==null&&t.position!==null?r*(e.position-t.position):e.position!==null||t.position!==null?e.position===null?1:-1:r*(compare(e.value,t.value,!1)??0)}function compareInstants(e,t,n){let r=instantOf(e.values[n.attribute]),i=instantOf(t.values[n.attribute]);return r===i?0:r===null||i===null?r===null?1:-1:n.direction===`desc`?i-r:r-i}function compareRecords(e,t){let n=e&&e.length>0?[...e]:[{attribute:`createdAt`,direction:`desc`}];return n.some(e=>e.attribute===`id`)||n.push({attribute:`id`,direction:`asc`}),(e,r)=>{for(let i of n){let n=t.attributes.find(e=>e.name===i.attribute),a=n?.type;if(isTimedDate(n)){let t=compareInstants(e,r,i);if(t!==0)return t;continue}let o=sortKey(e,i.attribute,t),s=sortKey(r,i.attribute,t),c=isOptionKey(o)?o.value:o,l=isOptionKey(s)?s.value:s,u=textOf(c)===null,d=textOf(l)===null;if(u||d){if(u&&d)continue;return u?1:-1}if(isOptionKey(o)&&isOptionKey(s)){let e=compareOptionKeys(o,s,i.direction);if(e!==0)return e;continue}let f=compare(o,s,a!==void 0&&g.has(a))??0;if(f!==0)return i.direction===`desc`?-f:f}return 0}}const S=`SCHEMA_RECORD_NOT_FOUND`,C=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,w=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...s(e)]}}function withoutSystemKeys(e){let t={...e};for(let e of w)delete t[e];return t}function boundOf(e,t,n){if(e==null)return n;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new r(400,`${t} must be a non-negative integer`);return e}function errorFor(e,t,n){return e===401||e===403?new i(e,t,n):new r(e,t,n)}function asTheServerValidates(e){try{e()}catch(e){throw e instanceof a?new r(400,e.message,e.code):e}}function notServed(e,t){return new r(501,`The in-memory test workspace does not serve ${e} ${t}: 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(e){let n=/* @__PURE__ */ new Map;for(let r of e.builders){let e=t(r);n.set(e.name,e)}let i=new Map([...n.keys()].map(e=>[e,[]])),a=/* @__PURE__ */ new Set,o=null,s=0,f=1;function now(){return s=Math.max(Date.now(),s+1),new Date(s).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(f++).toString(16).padStart(12,`0`)}`;while(a.has(e));return e}function objectOf(e){let t=n.get(e),a=i.get(e);if(!(t&&a))throw new r(404,`Object "${e}" not found. Make sure the object exists and you have access to it.`);return{definition:t,records:a}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:i,updatedAt:o,...s}=t,c=now(),l={id:r??newId(),values:wire(s),createdAt:isoOf(i,c),updatedAt:isoOf(o,isoOf(i,c)),visibility:`workspace`,ownedBy:null,metadata:{},objectId:objectOf(e).definition.id??e,label:``,parentId:null,ancestorIds:[],trashedWithRecordId:null,schemaVersion:1};return n.push(l),a.add(l.id),l}function find(e,t){let n=objectOf(e).records.find(e=>e.id===t);if(!n)throw new r(404,readNotFound(t),S);return n}function requireWritable(e,t){if(!objectOf(e).records.some(e=>e.id===t))throw new r(404,writeNotFound(t),S)}function update(e,t,n){let i=objectOf(e).records.find(e=>e.id===t);if(!i)throw new r(404,writeNotFound(t),S);return Object.assign(i.values,withoutSystemKeys(n)),i.updatedAt=now(),i}function remove(e,t){let{records:n}=objectOf(e),i=n.findIndex(e=>e.id===t);if(i===-1)throw new r(404,writeNotFound(t),S);n.splice(i,1)}function list(e,t,n){let{definition:r,records:i}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>u(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)),l=c.slice(o,o+a);return{data:l,page:{hasMore:o+l.length<c.length,total:null,countMode:`none`}}}function bulk(e,t,n){let i=n.records??n.updates??n.ids;if(!Array.isArray(i)||i.length>100)throw new r(400,`A bulk request carries at most 100 items.`);let a=withSystemAttributes(objectOf(e).definition);if(t===`bulk-create`){let t=[],n=[];for(let[o,s]of i.entries())if(!c(s))n.push({index:o,error:`Record data must be an object`});else try{asTheServerValidates(()=>l(a,s)),t.push(insert(e,withoutSystemKeys(s)))}catch(e){if(!(e instanceof r))throw e;n.push({index:o,error:e.message})}return{created:t,errors:n}}if(t===`bulk-update`){let t=[],n=[];for(let{id:o,data:s}of i)try{if(!c(s))throw new r(400,`Update data must be an object`,C);requireWritable(e,o),asTheServerValidates(()=>l(a,s)),t.push(update(e,o,s))}catch(e){if(!(e instanceof r))throw e;n.push({id:o,error:e.message,code:e.code??C})}return{updated:t,errors:n}}let o=[],s=[];for(let t of i)try{remove(e,t),o.push(t)}catch{s.push({id:t,error:writeNotFound(t),code:S})}return{deleted:o,errors:s}}function operation(e,t,i){let a=Array.isArray(i.steps)?i.steps:[],[o]=a;if(a.length!==1||!c(o)||o.kind!==`record.set`)throw notServed(e,t);let s=String(o.recordId),u=c(o.values)?o.values:{},d=[...n].find(([e,t])=>(t.id??e)===o.objectId)?.[0],answer=e=>({opId:i.opId,steps:[e],inverse:null});if(d===void 0||!objectOf(d).records.some(e=>e.id===s))return answer({status:`error`,recordId:s,code:S});try{asTheServerValidates(()=>l(withSystemAttributes(objectOf(d).definition),u))}catch(e){if(!(e instanceof r))throw e;let t=e.code??C;return answer({status:`error`,recordId:s,code:t,...t===C&&{message:e.message}})}return answer({status:`applied`,record:update(d,s,u)})}function route(e,t,n){let[i,a,o,...s]=t.replace(/^\/+/,``).split(`/`);if(e===`POST`&&i===`operations`&&a===void 0)return operation(e,t,c(n)?n:{});if(i!==`records`||a===void 0||s.length>0)throw notServed(e,t);let u=decodeURIComponent(a),d=o===void 0?void 0:decodeURIComponent(o),f=c(n)?n:{};if(e===`POST`&&d===void 0){let e=c(f.data)?f.data:{};return asTheServerValidates(()=>l(withSystemAttributes(objectOf(u).definition),e)),insert(u,withoutSystemKeys(e))}if(e===`POST`&&(d===`list`||d===`search`))return list(u,f,d===`search`);if(e===`POST`&&d?.startsWith(`bulk-`))return bulk(u,d,f);if(d===void 0)throw notServed(e,t);if(e===`GET`)return find(u,d);if(e===`PUT`||e===`PATCH`){if(Object.keys(f).length===0)throw new r(400,`Request body cannot be empty`);return requireWritable(u,d),asTheServerValidates(()=>l(withSystemAttributes(objectOf(u).definition),f)),update(u,d,f)}if(e===`DELETE`)return remove(u,d),null;throw notServed(e,t)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(o){let{status:e,failure:t}=o;throw o=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let m={call:(e,t)=>Promise.resolve().then(()=>{let{path:n,body:r}=p(e,t??{});return request(e.method,n,r).then(t=>d(e,t??null))}),stream:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=p(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:m,get:m.get,post:m.post,definitionOf:e=>objectOf(e).definition,seed:(e,t)=>t.map(t=>insert(e,t)),records:e=>objectOf(e).records,failNextRequestWith(e,t={}){o={status:e,failure:t}}}}function createTestStandards(t){let r=t.bundles.flatMap(e=>e.objectBuilders),i=createInMemoryApi({builders:r}),flatten=(t,n)=>e(i.definitionOf(t),d(f.get,JSON.parse(JSON.stringify(n))));return{db:n(i.transport,r),seed:(e,t)=>i.seed(e,t).map(t=>flatten(e,t)),records:e=>i.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>i.failNextRequestWith(e,t)}}export{UnsupportedFilterOperatorError,createTestStandards};
|
|
2
|
+
import{a as e,o as t,t as n}from"./create-standards-CZ_ZYNz8.mjs";import{h as r,p as i}from"./app-TJt8rk9y.mjs";import{ValidationError as a,foldText as o,getObjectSystemAttributes as s,isPlainRecord as c,rejectUnknownAttributesOrThrow as l,validateQualifiedRule as u}from"@standards/schema";import{decodeOperationOutput as d,recordsOperations as f,splitOperationInput as p}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 m=/* @__PURE__ */ new Set([`id`,`createdAt`,`updatedAt`]),h=/* @__PURE__ */ new Set([`createdAt`,`updatedAt`]),g=/* @__PURE__ */ new Set([`number`,`currency`]),_=/* @__PURE__ */ new Set([`select`,`status`]),v=/^\d{4}-\d{2}-\d{2}/,y=/^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:[T ]((?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,6})?)?)(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;function attributeValue(e,t){if(m.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||!v.test(t))return null;let n=t.slice(0,10);return Number.isNaN(Date.parse(`${n}T00:00:00.000Z`))?null:n}const b=Date.parse(`0001-01-01T00:00:00Z`);function instantOf(e){let t=typeof e==`object`&&e&&`start`in e?e.start:e,n=typeof t==`string`?y.exec(t):null;if(!n)return null;let[,r=``,i=`00:00`,a=`Z`]=n;if(r.startsWith(`0000`))return null;let o=a===`Z`?`Z`:`${a.slice(0,3)}:${a.slice(3).replace(`:`,``)||`00`}`,s=Date.parse(`${r}T${i}${o}`);return Number.isNaN(s)||(/* @__PURE__ */ new Date(`${r}T00:00:00Z`)).toISOString().slice(0,10)!==r||s<b?null:s}function nextDay(e){let t=/* @__PURE__ */ new Date(`${e}T00:00:00.000Z`);return t.setUTCDate(t.getUTCDate()+1),t.toISOString().slice(0,10)}function isUnmodelledDate(e){if(e?.type!==`date`)return!1;let t=e;return t.endDate===!0||t.includeTime===!0}function isTimedDate(e){return e?.type===`date`&&e.includeTime===!0}function matchesDay(e,t,n,r){let i=dayOf(n);if(i===null)return!1;let a=textOf(t),o=nextDay(i),s=r?textOf(n)??i:i;switch(e){case`is`:return a!==null&&a>=s&&a<o;case`is_not`:return a===null||a<s||a>=o;case`greater_than`:return a!==null&&a>=o;case`greater_or_equal`:return a!==null&&a>=s;case`less_than`:return a!==null&&a<s;default:return a!==null&&a<o}}function compare(e,t,n){let r=textOf(e),i=textOf(t);if(r===null||i===null)return null;if(n){let e=Number(r),t=Number(i);return r===``||Number.isNaN(e)||Number.isNaN(t)?null:e-t}return r<i?-1:+(r>i)}function matchesRule(e,t,n){let r=n.attributes.find(e=>e.name===t.attribute)?.type,i=attributeValue(e,t.attribute),a=r!==void 0&&g.has(r),s=textOf(t.value),c=s===null?void 0:o(s),l=textOf(i),u=l===null?null:o(l);if((r===`date`||h.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,h.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)):u!==null&&c!==void 0&&u.includes(c);case`not_contains`:return i==null||!matchesRule(e,{...t,operator:`contains`},n);case`starts_with`:return u!==null&&c!==void 0&&u.startsWith(c);case`ends_with`:return u!==null&&c!==void 0&&u.endsWith(c);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 x=/* @__PURE__ */ new Set([`is`,`is_not`,`contains`,`not_contains`,`starts_with`,`ends_with`,`greater_than`,`greater_or_equal`,`less_than`,`less_or_equal`,`is_empty`,`is_not_empty`,`any_of`,`none_of`]);function assertServedOperators(e,t){for(let n of e?.rules??[])if(!x.has(n.operator)||n.attribute.startsWith(`metadata.`)||isUnmodelledDate(t.attributes.find(e=>e.name===n.attribute))&&n.operator!==`is_empty`&&n.operator!==`is_not_empty`)throw new UnsupportedFilterOperatorError(n.operator,n.attribute)}function matchesFilters(e,t,n){let r=t?.rules??[];if(r.length===0)return!0;let i=r.map(t=>matchesRule(e,t,n));return t?.combinator===`or`?i.some(Boolean):i.every(Boolean)}function matchesSearch(e,t){let n=t.trim().toLowerCase();return n===``||Object.values(e.values).some(e=>(Array.isArray(e)?e:[e]).some(e=>typeof e==`string`&&e.toLowerCase().includes(n)))}function sortKey(e,t,n){let r=attributeValue(e,t),i=n.attributes.find(e=>e.name===t);if(i&&_.has(i.type)){let e=(i.options??[]).findIndex(e=>e.value===r);return{position:e===-1?null:e,value:r}}return r}function isOptionKey(e){return typeof e==`object`&&!!e&&`position`in e}function compareOptionKeys(e,t,n){let r=n===`desc`?-1:1;return e.position!==null&&t.position!==null?r*(e.position-t.position):e.position!==null||t.position!==null?e.position===null?1:-1:r*(compare(e.value,t.value,!1)??0)}function compareInstants(e,t,n){let r=instantOf(e.values[n.attribute]),i=instantOf(t.values[n.attribute]);return r===i?0:r===null||i===null?r===null?1:-1:n.direction===`desc`?i-r:r-i}function compareRecords(e,t){let n=e&&e.length>0?[...e]:[{attribute:`createdAt`,direction:`desc`}];return n.some(e=>e.attribute===`id`)||n.push({attribute:`id`,direction:`asc`}),(e,r)=>{for(let i of n){let n=t.attributes.find(e=>e.name===i.attribute),a=n?.type;if(isTimedDate(n)){let t=compareInstants(e,r,i);if(t!==0)return t;continue}let o=sortKey(e,i.attribute,t),s=sortKey(r,i.attribute,t),c=isOptionKey(o)?o.value:o,l=isOptionKey(s)?s.value:s,u=textOf(c)===null,d=textOf(l)===null;if(u||d){if(u&&d)continue;return u?1:-1}if(isOptionKey(o)&&isOptionKey(s)){let e=compareOptionKeys(o,s,i.direction);if(e!==0)return e;continue}let f=compare(o,s,a!==void 0&&g.has(a))??0;if(f!==0)return i.direction===`desc`?-f:f}return 0}}const S=`SCHEMA_RECORD_NOT_FOUND`,C=`SCHEMA_VALIDATION_FAILED`,readNotFound=e=>`Record "${e}" not found.`,writeNotFound=e=>`Record with id "${e}" not found`,w=[`id`,`createdAt`,`updatedAt`];function withSystemAttributes(e){return{...e,attributes:[...e.attributes,...s(e)]}}function withoutSystemKeys(e){let t={...e};for(let e of w)delete t[e];return t}function boundOf(e,t,n){if(e==null)return n;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw new r(400,`${t} must be a non-negative integer`);return e}function errorFor(e,t,n){return e===401||e===403?new i(e,t,n):new r(e,t,n)}function asTheServerValidates(e){try{e()}catch(e){throw e instanceof a?new r(400,e.message,e.code):e}}function notServed(e,t){return new r(501,`The in-memory test workspace does not serve ${e} ${t}: 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=/* @__PURE__ */ new Map;for(let r of t.builders){let t=e(r);n.set(t.name,t)}let i=new Map([...n.keys()].map(e=>[e,[]])),a=/* @__PURE__ */ new Set,o=null,s=0,f=1;function now(){return s=Math.max(Date.now(),s+1),new Date(s).toISOString()}function newId(){let e;do e=`00000000-0000-4000-8000-${(f++).toString(16).padStart(12,`0`)}`;while(a.has(e));return e}function objectOf(e){let t=n.get(e),a=i.get(e);if(!(t&&a))throw new r(404,`Object "${e}" not found. Make sure the object exists and you have access to it.`);return{definition:t,records:a}}function insert(e,t){let{records:n}=objectOf(e),{id:r,createdAt:i,updatedAt:o,...s}=t,c=now(),l={id:r??newId(),values:wire(s),createdAt:isoOf(i,c),updatedAt:isoOf(o,isoOf(i,c)),visibility:`workspace`,ownedBy:null,metadata:{},objectId:objectOf(e).definition.id??e,label:``,parentId:null,ancestorIds:[],trashedWithRecordId:null,schemaVersion:1};return n.push(l),a.add(l.id),l}function find(e,t){let n=objectOf(e).records.find(e=>e.id===t);if(!n)throw new r(404,readNotFound(t),S);return n}function requireWritable(e,t){if(!objectOf(e).records.some(e=>e.id===t))throw new r(404,writeNotFound(t),S)}function update(e,t,n){let i=objectOf(e).records.find(e=>e.id===t);if(!i)throw new r(404,writeNotFound(t),S);return Object.assign(i.values,withoutSystemKeys(n)),i.updatedAt=now(),i}function remove(e,t){let{records:n}=objectOf(e),i=n.findIndex(e=>e.id===t);if(i===-1)throw new r(404,writeNotFound(t),S);n.splice(i,1)}function list(e,t,n){let{definition:r,records:i}=objectOf(e);for(let e of t.filters?.rules??[])asTheServerValidates(()=>u(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)),l=c.slice(o,o+a);return{data:l,page:{hasMore:o+l.length<c.length,total:null,countMode:`none`}}}function bulk(e,t,n){let i=n.records??n.updates??n.ids;if(!Array.isArray(i)||i.length>100)throw new r(400,`A bulk request carries at most 100 items.`);let a=withSystemAttributes(objectOf(e).definition);if(t===`bulk-create`){let t=[],n=[];for(let[o,s]of i.entries())if(!c(s))n.push({index:o,error:`Record data must be an object`});else try{asTheServerValidates(()=>l(a,s)),t.push(insert(e,withoutSystemKeys(s)))}catch(e){if(!(e instanceof r))throw e;n.push({index:o,error:e.message})}return{created:t,errors:n}}if(t===`bulk-update`){let t=[],n=[];for(let{id:o,data:s}of i)try{if(!c(s))throw new r(400,`Update data must be an object`,C);requireWritable(e,o),asTheServerValidates(()=>l(a,s)),t.push(update(e,o,s))}catch(e){if(!(e instanceof r))throw e;n.push({id:o,error:e.message,code:e.code??C})}return{updated:t,errors:n}}let o=[],s=[];for(let t of i)try{remove(e,t),o.push(t)}catch{s.push({id:t,error:writeNotFound(t),code:S})}return{deleted:o,errors:s}}function operation(e,t,i){let a=Array.isArray(i.steps)?i.steps:[],[o]=a;if(a.length!==1||!c(o)||o.kind!==`record.set`)throw notServed(e,t);let s=String(o.recordId),u=c(o.values)?o.values:{},d=[...n].find(([e,t])=>(t.id??e)===o.objectId)?.[0],answer=e=>({opId:i.opId,steps:[e],inverse:null});if(d===void 0||!objectOf(d).records.some(e=>e.id===s))return answer({status:`error`,recordId:s,code:S});try{asTheServerValidates(()=>l(withSystemAttributes(objectOf(d).definition),u))}catch(e){if(!(e instanceof r))throw e;let t=e.code??C;return answer({status:`error`,recordId:s,code:t,...t===C&&{message:e.message}})}return answer({status:`applied`,record:update(d,s,u)})}function route(e,t,n){let[i,a,o,...s]=t.replace(/^\/+/,``).split(`/`);if(e===`POST`&&i===`operations`&&a===void 0)return operation(e,t,c(n)?n:{});if(i!==`records`||a===void 0||s.length>0)throw notServed(e,t);let u=decodeURIComponent(a),d=o===void 0?void 0:decodeURIComponent(o),f=c(n)?n:{};if(e===`POST`&&d===void 0){let e=c(f.data)?f.data:{};return asTheServerValidates(()=>l(withSystemAttributes(objectOf(u).definition),e)),insert(u,withoutSystemKeys(e))}if(e===`POST`&&(d===`list`||d===`search`))return list(u,f,d===`search`);if(e===`POST`&&d?.startsWith(`bulk-`))return bulk(u,d,f);if(d===void 0)throw notServed(e,t);if(e===`GET`)return find(u,d);if(e===`PUT`||e===`PATCH`){if(Object.keys(f).length===0)throw new r(400,`Request body cannot be empty`);return requireWritable(u,d),asTheServerValidates(()=>l(withSystemAttributes(objectOf(u).definition),f)),update(u,d,f)}if(e===`DELETE`)return remove(u,d),null;throw notServed(e,t)}function request(e,t,n){return Promise.resolve().then(()=>(takeFailure(),wire(route(e,t,n===void 0?void 0:wire(n)))))}function takeFailure(){if(o){let{status:e,failure:t}=o;throw o=null,errorFor(e,t.message??`Request failed with status ${e}`,t.code)}}let m={call:(e,t)=>Promise.resolve().then(()=>{let{path:n,body:r}=p(e,t??{});return request(e.method,n,r).then(t=>d(e,t??null))}),stream:(e,t)=>Promise.resolve().then(()=>{takeFailure();let{path:n}=p(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:m,get:m.get,post:m.post,definitionOf:e=>objectOf(e).definition,seed:(e,t)=>t.map(t=>insert(e,t)),records:e=>objectOf(e).records,failNextRequestWith(e,t={}){o={status:e,failure:t}}}}function createTestStandards(e){let r=e.bundles.flatMap(e=>e.objectBuilders),i=createInMemoryApi({builders:r}),flatten=(e,n)=>t(i.definitionOf(e),d(f.get,JSON.parse(JSON.stringify(n))));return{db:n(i.transport,r),seed:(e,t)=>i.seed(e,t).map(t=>flatten(e,t)),records:e=>i.records(e).map(t=>flatten(e,t)),failNextRequestWith:(e,t)=>i.failNextRequestWith(e,t)}}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.426",
|
|
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.426"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@types/node": "^25.6.0",
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
const e=require("./app-d25WfBqA.js");let t=require("@standards/schema"),n=require("@standards/schema/api");async function readInstalled(t,r){try{return await t.call(n.bundlesOperations.get,{name:r})}catch(t){if(t instanceof e.h&&t.status===404)return null;throw t}}async function syncBundle(t,r,i={}){let a=await r.build(),o=await readInstalled(t,a.name);if(o?.hash===a.hash&&o.label===a.label&&o.description===a.description&&o.uses.join(`
|
|
3
|
-
`)===a.uses.join(`
|
|
4
|
-
`))return{applied:!1,hash:a.hash};let s=i.resolutions&&i.resolutions.length>0?{...a,resolutions:i.resolutions}:a;try{return await t.call(n.bundlesOperations.sync,{name:a.name,bundle:s})}catch(t){throw t instanceof e.h&&t.status===409?new e.d(t.status,t.message,t.code):t instanceof e.h&&t.status===400?new e.f(t.status,t.message,t.code):t}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const r=/* @__PURE__ */ new Set([`from`,`bundles`,`contract`]);function assertObjectKeys(t){let n=/* @__PURE__ */ new Map;for(let i of t){if(i.includes(`--`)||i.endsWith(`-`))throw new e.m(`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.m(`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.m(`Objects "${a}" and "${i}" both map to the client key "${t}". Rename one of them.`);n.set(t,i)}}function assertObjectNames(e){let n=/* @__PURE__ */ new Set;for(let r of e){if(n.has(r))throw new t.DuplicateError(`object`,r);n.add(r)}assertObjectKeys(e)}function readRecord(e,n){let{values:r,...i}=n;return(0,t.isPlainRecord)(r)?{...i,...(0,t.decodeRecordValues)(e,r)}:n}var i=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 readRecord(this.definition,e)}async export(t,r={}){if(!this.transport.postRaw)throw new e.m(`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.call(n.recordsOperations.aggregate,{objectName:this.objectName,...r})}async fetchPage(){let e={objectName:this.objectName,...this.body()},t=this.state.search===void 0?await this.transport.call(n.recordsOperations.list,e):await this.transport.call(n.recordsOperations.search,e);return{records:t.data.map(e=>this.revive(e)),page:t.page}}async fetch(){let{records:e,page:t}=await this.fetchPage();return{records:e,total:t.total}}async all(){if(this.state.limit!==void 0&&this.state.limit<0)return(await this.fetch()).records;let e=this.state.limit??1/0,t=[],n=this.state.offset??0;for(;;){let r=Math.min(1e3,e-t.length);if(r<=0)return t;let{records:i,page:a}=await this.with({limit:r,offset:n}).fetchPage();if(t.push(...i),!a.hasMore)return t;let o=a.nextOffset??n+i.length;if(o<=n)return t;n=o}}async single(){let{records:e}=await this.limit(1).fetch();return e[0]??null}async get(e){let t=await this.transport.call(n.recordsOperations.get,{objectName:this.objectName,id:e});return this.revive(t)}async create(e,{allowDraft:r,metadata:i}={}){let a={...r!==void 0&&{allowDraft:r},...i!==void 0&&{metadata:i}},o=await this.transport.call(n.recordsOperations.create,{objectName:this.objectName,data:(0,t.encodeRecordValues)(this.definition,e),...Object.keys(a).length>0&&{options:a}});return this.revive(o)}async update(r,i,{metadata:a}={}){let o=(0,t.encodeRecordValues)(this.definition,i);if(a===void 0){let e=await this.transport.call(n.recordsOperations.update,{objectName:this.objectName,id:r,values:o});return this.revive(e)}let{objectId:s}=await this.transport.call(n.recordsOperations.get,{objectName:this.objectName,id:r}),{steps:c}=await this.transport.call(n.recordOperationsOperations.execute,{opId:crypto.randomUUID(),steps:[{kind:`record.set`,objectId:s,recordId:r,values:o,metadata:a}]}),[l]=c;if(l===void 0||l.status===`error`){let n=l?.code,r=n===void 0?500:t.SCHEMA_ERROR_HTTP_STATUS[n];throw e.o(r,JSON.stringify({message:l?.message,code:n}))}let u=(0,n.decodeOperationOutput)(n.recordsOperations.get,l.record);return this.revive(u)}async delete(e){await this.transport.call(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 r={created:[],errors:[]};return await this.inChunks(e,async(e,i)=>{let a=await this.transport.call(n.recordsOperations.bulkCreate,{objectName:this.objectName,records:e.map(e=>(0,t.encodeRecordValues)(this.definition,e))});r.created.push(...a.created.map(e=>this.revive(e))),r.errors.push(...a.errors.map(e=>({...e,index:e.index+i})))}),r}async updateMany(e){let r={updated:[],errors:[]};return await this.inChunks(e,async e=>{let i=await this.transport.call(n.recordsOperations.bulkUpdate,{objectName:this.objectName,updates:e.map(({id:e,data:n})=>({id:e,data:(0,t.encodeRecordValues)(this.definition,n)}))});r.updated.push(...i.updated.map(e=>this.revive(e))),r.errors.push(...i.errors)}),r}async deleteMany(e){let t={deleted:[],errors:[]};return await this.inChunks(e,async e=>{let r=await this.transport.call(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.call(n.recordAccessOperations.list,{objectName:this.objectName,recordId:e})}async grantAccess(e,t,r){return await this.transport.call(n.recordAccessOperations.grant,{objectName:this.objectName,recordId:e,actorId:t,role:r})}async revokeAccess(e,t){return await this.transport.call(n.recordAccessOperations.revoke,{objectName:this.objectName,recordId:e,actorId:t})}async clearAccess(e){return await this.transport.call(n.recordAccessOperations.clear,{objectName:this.objectName,recordId:e})}};const a=/* @__PURE__ */ new WeakMap;function definitionOf(e){let t=a.get(e);if(t)return t;let n=e.build();return a.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new i(e,t,null);let n=definitionOf(t);return new i(e,n.name,n)}function readEnvironment(){return typeof process>`u`||!process.env?{}:{baseUrl:process.env.STANDARDS_API_URL||void 0,apiKey:process.env.STANDARDS_API_KEY||void 0}}function resolveConfig(t){if(globalThis.window!==void 0){if(t.apiKey)throw new e.m(`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.m(`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.m(`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.m(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...t,baseUrl:r,apiKey:i}}function createStandards(t={}){let{bundles:n=[],transport:r,...i}=t;if(r!==void 0&&Object.values(i).some(e=>e!==void 0))throw new e.m(`createStandards takes a transport or an HTTP connection (baseUrl, apiKey, tenantId, timeoutMs), not both.`);return buildStandards(r??e.i(resolveConfig(i)),n.flatMap(e=>e.objectBuilders))}function buildStandards(t,n){let r=e.t(t),sync=((e,n)=>isBundleBuilder(e)?syncBundle(t,e,n):r.bundles.sync(e,n)),i={...r,bundles:{...r.bundles,sync},from:e=>createRecordsQuery(t,e),contract:r},a=n.map(e=>definitionOf(e).name);return assertObjectNames(a),n.forEach((e,n)=>{i[objectKeyOf(a[n])]=createRecordsQuery(t,e)}),i}function isBundleBuilder(e){return typeof e==`object`&&!!e&&`objectBuilders`in e&&typeof e.build==`function`}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return readRecord}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return definitionOf}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return createStandards}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return syncBundle}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return createRecordsQuery}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return buildStandards}});
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
import{d as e,f as t,h as n,i as r,m as i,o as a,t as o}from"./app-CjHQKAwu.mjs";import{AggregateValidationError as s,DuplicateError as c,RecordQuery as l,SCHEMA_ERROR_HTTP_STATUS as u,SchemaErrorCode as d,decodeRecordValues as f,encodeRecordValues as p,isPlainRecord as m}from"@standards/schema";import{buildOperationPath as h,bundlesOperations as g,decodeOperationOutput as _,recordAccessOperations as v,recordOperationsOperations as y,recordsOperations as b}from"@standards/schema/api";async function readInstalled(e,t){try{return await e.call(g.get,{name:t})}catch(e){if(e instanceof n&&e.status===404)return null;throw e}}async function syncBundle(r,i,a={}){let o=await i.build(),s=await readInstalled(r,o.name);if(s?.hash===o.hash&&s.label===o.label&&s.description===o.description&&s.uses.join(`
|
|
3
|
-
`)===o.uses.join(`
|
|
4
|
-
`))return{applied:!1,hash:o.hash};let c=a.resolutions&&a.resolutions.length>0?{...o,resolutions:a.resolutions}:o;try{return await r.call(g.sync,{name:o.name,bundle:c})}catch(r){throw r instanceof n&&r.status===409?new e(r.status,r.message,r.code):r instanceof n&&r.status===400?new t(r.status,r.message,r.code):r}}function objectKeyOf(e){return e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase())}const x=/* @__PURE__ */ new Set([`from`,`bundles`,`contract`]);function assertObjectKeys(e){let t=/* @__PURE__ */ new Map;for(let n of e){if(n.includes(`--`)||n.endsWith(`-`))throw new i(`Object "${n}" has a doubled or trailing hyphen, which has no client key. Rename the object.`);let e=objectKeyOf(n);if(x.has(e))throw new i(`Object "${n}" maps to the client key "${e}", which is reserved. Rename the object.`);let r=t.get(e);if(r!==void 0&&r!==n)throw new i(`Objects "${r}" and "${n}" both map to the client key "${e}". Rename one of them.`);t.set(e,n)}}function assertObjectNames(e){let t=/* @__PURE__ */ new Set;for(let n of e){if(t.has(n))throw new c(`object`,n);t.add(n)}assertObjectKeys(e)}function readRecord(e,t){let{values:n,...r}=t;return m(n)?{...r,...f(e,n)}:t}var S=class RecordsQueryImpl extends l{constructor(e,t,n,r={object:t,combinator:`and`,rules:[],sorts:[]}){super(r),this.transport=e,this.objectName=t,this.definition=n}with(e){return new RecordsQueryImpl(this.transport,this.objectName,this.definition,{...this.state,...e})}body(){let e={};return this.state.search!==void 0&&(e.q=this.state.search),this.state.rules.length>0&&(e.filters={combinator:this.state.combinator,rules:this.state.rules}),this.state.sorts.length>0&&(e.sorts=this.state.sorts),this.state.limit!==void 0&&(e.limit=this.state.limit),this.state.offset!==void 0&&(e.offset=this.state.offset),e}revive(e){return readRecord(this.definition,e)}async export(e,t={}){if(!this.transport.postRaw)throw new i(`export() needs a transport with postRaw(path, body): Promise<Response>`);let{filters:n,sorts:r}=this.body(),{ids:a,locale:o,filename:s}=t;return await this.transport.postRaw(h(b.export,{objectName:this.objectName}),{q:this.state.search??``,...n?{filters:n}:{},...r?{sorts:r}:{},columns:e,...a?{ids:a}:{},...o?{locale:o}:{},timezone:t.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone,...s?{filename:s}:{}})}async aggregate(e){if(this.state.search!==void 0)throw new s(d.AGGREGATE_SEARCH_UNSUPPORTED,`An aggregate cannot be narrowed by a search; use filters instead`);let t={...e,query:this.toDefinition(),timezone:e.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone};return await this.transport.call(b.aggregate,{objectName:this.objectName,...t})}async fetchPage(){let e={objectName:this.objectName,...this.body()},t=this.state.search===void 0?await this.transport.call(b.list,e):await this.transport.call(b.search,e);return{records:t.data.map(e=>this.revive(e)),page:t.page}}async fetch(){let{records:e,page:t}=await this.fetchPage();return{records:e,total:t.total}}async all(){if(this.state.limit!==void 0&&this.state.limit<0)return(await this.fetch()).records;let e=this.state.limit??1/0,t=[],n=this.state.offset??0;for(;;){let r=Math.min(1e3,e-t.length);if(r<=0)return t;let{records:i,page:a}=await this.with({limit:r,offset:n}).fetchPage();if(t.push(...i),!a.hasMore)return t;let o=a.nextOffset??n+i.length;if(o<=n)return t;n=o}}async single(){let{records:e}=await this.limit(1).fetch();return e[0]??null}async get(e){let t=await this.transport.call(b.get,{objectName:this.objectName,id:e});return this.revive(t)}async create(e,{allowDraft:t,metadata:n}={}){let r={...t!==void 0&&{allowDraft:t},...n!==void 0&&{metadata:n}},i=await this.transport.call(b.create,{objectName:this.objectName,data:p(this.definition,e),...Object.keys(r).length>0&&{options:r}});return this.revive(i)}async update(e,t,{metadata:n}={}){let r=p(this.definition,t);if(n===void 0){let t=await this.transport.call(b.update,{objectName:this.objectName,id:e,values:r});return this.revive(t)}let{objectId:i}=await this.transport.call(b.get,{objectName:this.objectName,id:e}),{steps:o}=await this.transport.call(y.execute,{opId:crypto.randomUUID(),steps:[{kind:`record.set`,objectId:i,recordId:e,values:r,metadata:n}]}),[s]=o;if(s===void 0||s.status===`error`){let e=s?.code,t=e===void 0?500:u[e];throw a(t,JSON.stringify({message:s?.message,code:e}))}let c=_(b.get,s.record);return this.revive(c)}async delete(e){await this.transport.call(b.delete,{objectName:this.objectName,id:e})}async inChunks(e,t){for(let n=0;n<e.length;n+=100)await t(e.slice(n,n+100),n)}async createMany(e){let t={created:[],errors:[]};return await this.inChunks(e,async(e,n)=>{let r=await this.transport.call(b.bulkCreate,{objectName:this.objectName,records:e.map(e=>p(this.definition,e))});t.created.push(...r.created.map(e=>this.revive(e))),t.errors.push(...r.errors.map(e=>({...e,index:e.index+n})))}),t}async updateMany(e){let t={updated:[],errors:[]};return await this.inChunks(e,async e=>{let n=await this.transport.call(b.bulkUpdate,{objectName:this.objectName,updates:e.map(({id:e,data:t})=>({id:e,data:p(this.definition,t)}))});t.updated.push(...n.updated.map(e=>this.revive(e))),t.errors.push(...n.errors)}),t}async deleteMany(e){let t={deleted:[],errors:[]};return await this.inChunks(e,async e=>{let n=await this.transport.call(b.bulkDelete,{objectName:this.objectName,ids:e});t.deleted.push(...n.deleted),t.errors.push(...n.errors)}),t}async listAccess(e){return await this.transport.call(v.list,{objectName:this.objectName,recordId:e})}async grantAccess(e,t,n){return await this.transport.call(v.grant,{objectName:this.objectName,recordId:e,actorId:t,role:n})}async revokeAccess(e,t){return await this.transport.call(v.revoke,{objectName:this.objectName,recordId:e,actorId:t})}async clearAccess(e){return await this.transport.call(v.clear,{objectName:this.objectName,recordId:e})}};const C=/* @__PURE__ */ new WeakMap;function definitionOf(e){let t=C.get(e);if(t)return t;let n=e.build();return C.set(e,n),n}function createRecordsQuery(e,t){if(typeof t==`string`)return new S(e,t,null);let n=definitionOf(t);return new S(e,n.name,n)}function readEnvironment(){return typeof process>`u`||!process.env?{}:{baseUrl:process.env.STANDARDS_API_URL||void 0,apiKey:process.env.STANDARDS_API_KEY||void 0}}function resolveConfig(e){if(globalThis.window!==void 0){if(e.apiKey)throw new i(`createStandards received an apiKey in a browser context. API keys belong to server code only (Route Handlers, Server Components, scripts).`);if(e.baseUrl===void 0)throw new i(`createStandards needs an explicit baseUrl in a browser context: STANDARDS_API_URL and STANDARDS_API_KEY are never read from the environment there.`);return{...e,baseUrl:e.baseUrl,apiKey:``}}let t=readEnvironment(),n=e.baseUrl??t.baseUrl;if(n===void 0)throw new i(`createStandards needs a base URL: pass baseUrl or set the STANDARDS_API_URL environment variable.`);let r=e.apiKey??t.apiKey;if(r===void 0)throw new i(`createStandards needs an API key: pass apiKey or set the STANDARDS_API_KEY environment variable.`);return{...e,baseUrl:n,apiKey:r}}function createStandards(e={}){let{bundles:t=[],transport:n,...a}=e;if(n!==void 0&&Object.values(a).some(e=>e!==void 0))throw new i(`createStandards takes a transport or an HTTP connection (baseUrl, apiKey, tenantId, timeoutMs), not both.`);return buildStandards(n??r(resolveConfig(a)),t.flatMap(e=>e.objectBuilders))}function buildStandards(e,t){let n=o(e),sync=((t,r)=>isBundleBuilder(t)?syncBundle(e,t,r):n.bundles.sync(t,r)),r={...n,bundles:{...n.bundles,sync},from:t=>createRecordsQuery(e,t),contract:n},i=t.map(e=>definitionOf(e).name);return assertObjectNames(i),t.forEach((t,n)=>{r[objectKeyOf(i[n])]=createRecordsQuery(e,t)}),r}function isBundleBuilder(e){return typeof e==`object`&&!!e&&`objectBuilders`in e&&typeof e.build==`function`}export{readRecord as a,definitionOf as i,createStandards as n,syncBundle as o,createRecordsQuery as r,buildStandards as t};
|