payload-live-preview 2.3.0 → 2.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -16
- package/dist/adapters/astro/index.js +1 -1
- package/dist/adapters/astro/index.js.map +1 -1
- package/dist/adapters/astro/middleware-entry.js +1 -1
- package/dist/adapters/astro/middleware-entry.js.map +1 -1
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nuxt/index.js +1 -1
- package/dist/adapters/nuxt/index.js.map +1 -1
- package/dist/adapters/react/index.js +1 -1
- package/dist/adapters/react/index.js.map +1 -1
- package/dist/adapters/sveltekit/index.js +1 -1
- package/dist/adapters/sveltekit/index.js.map +1 -1
- package/dist/adapters/vue/index.js +1 -1
- package/dist/adapters/vue/index.js.map +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +16 -14
- package/dist/core.d.ts +16 -14
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lean.cjs +1 -1
- package/dist/lean.cjs.map +1 -1
- package/dist/lean.js +1 -1
- package/dist/lean.js.map +1 -1
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.cjs.map +1 -1
- package/dist/plugins.js +1 -1
- package/dist/plugins.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getCurrentScope as e,shallowRef as t,onScopeDispose as i,computed as n}from"vue";function s(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then&&(Promise.resolve(e).catch(()=>{}),!0)}function r(){}function o(e){if(++e.nodes>1e4)throw new Error("invalid or oversized field schema")}function a(e,t,i){if(o(t),i>64||t.active.has(e))throw new Error("invalid or oversized field schema");t.active.add(e)}function l(e){try{return c(e,{nodes:0,active:/* @__PURE__ */new WeakSet},0)}catch{return[]}}function c(e,t,i){if(!Array.isArray(e))return[];a(e,t,i);const n=[];for(const s of e){const e=d(s,t,i);e&&n.push(e)}return t.active.delete(e),n}function d(e,t,i){if(o(t),"object"!=typeof e||null===e)return;const n=e,s=n.name,r=n.type;if("string"!=typeof s||0===s.length)return;if("string"!=typeof r||0===r.length)return;const l=c(n.fields,t,i+1),d=function(e,t,i){if("object"==typeof e&&null!==e&&!Array.isArray(e)){a(e,t,i);const n=[];for(const s in e){if(!Object.hasOwn(e,s))continue;o(t);const r=Reflect.get(e,s);"object"!=typeof r||null===r||["__proto__","constructor","prototype"].includes(s)||n.push({...r,slug:s,fields:c(r.fields,t,i+1)})}return t.active.delete(e),n}if(!Array.isArray(e))return[];a(e,t,i);const n=[];for(const s of e){if(o(t),"object"!=typeof s||null===s)continue;const e=s,r=e.slug;if("string"!=typeof r||0===r.length)continue;const a=c(e.fields,t,i+1);n.push({...e,slug:r,fields:a})}return t.active.delete(e),n}(n.blocks,t,i+1),u={...n,name:s,type:r},h=n.relationTo;if(Array.isArray(h)){const e=[];for(const i of h)o(t),e.push(i);u.relationTo=e}return l.length>0?u.fields=l:delete u.fields,d.length>0?u.blocks=d:delete u.blocks,u}function u(e,t){return void 0===e||t(e)}function h(e,t){return null==e||t(e)}function f(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}var p=["data","fieldSchemaJSON","globalSlug","collectionSlug","locale","ready","previewToken","protocolVersion"],v=1e4,g=1048576,y=/* @__PURE__ */new Set(["__proto__","constructor","prototype"]);function m(){throw new Error("invalid or oversized legacy population")}function b(e){for(let t=0;t<e.length;t+=1){const i=e.charCodeAt(t);if(i<=31||127===i)return!0}return!1}function w(e,t){if("string"!=typeof e||0===e.length||e.length>t||"."===e||".."===e)return!1;if(e.includes("/")||e.includes("\\")||b(e))return!1;try{return encodeURIComponent(e),!0}catch{return!1}}function S(e){return w(e,128)&&!/[?#%]/u.test(e)&&!y.has(e)}function A(e){return Number.isFinite(e)?String(e):w(e,512)?e:m()}function O(e,t){return Object.hasOwn(e,t)?Reflect.get(e,t):void 0}function L(e,t,i){Object.defineProperty(e,t,{value:i,writable:!0,configurable:!0,enumerable:!0})}function T(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return e.slice(0,t)}function R(e){const t=/* @__PURE__ */new WeakSet;let i=0,n=0;return function e(s,r){if(++i>v||r>64)return m();if("string"==typeof s)return n+=s.length,n>g&&m(),s;if(null==s||"boolean"==typeof s)return s;if("number"==typeof s)return Number.isFinite(s)?s:m();if(!Array.isArray(s)&&!f(s))return m();if(Array.isArray(s)){s.length>v&&m();for(let e=0;e<s.length;e+=1)Object.hasOwn(s,e)||m()}if(t.has(s))return m();t.add(s);const o=Array.isArray(s)?[]:{};for(const t of Object.keys(s))L(o,t,e(Reflect.get(s,t),r+1));return t.delete(s),o}(e,0)}function k(e,t,i,n,s,r){if(!Number.isSafeInteger(s)||s<0||s>64)return m();void 0!==r&&("string"!=typeof r||r.length>128||b(r))&&m();const o=R(e);if(!f(o))return m();const a=/* @__PURE__ */new Map,l=/* @__PURE__ */new Set;let c=0;const d=/* @__PURE__ */new WeakSet,u=e=>{(++c>v||e>64)&&m()};function h(e,t,i,n){if(null==n||""===n)return;const r=f(n)?O(n,"id"):n,o=A(r);if(0===s)return void L(e,t,r);const c=JSON.stringify([i,o]);l.add(c),l.size>1e3&&m();const d=a.get(i)??[];d.push({owner:e,key:t,id:o}),a.set(i,d)}function p(e,t,i){void 0!==i.hasMany&&"boolean"!=typeof i.hasMany&&m();const n=i.relationTo,s=O(e,t);if(Array.isArray(n)){0===n.length&&m();const e=f(s)?O(s,"relationTo"):void 0;let t;for(const i of n)u(0),S(i)||m(),i===e&&(t=i);if(null==s||""===s)return;f(s)&&void 0!==t||m(),h(s,"value",t,O(s,"value"))}else S(n)||m(),h(e,t,n,s)}function g(e,t){if(u(t),Array.isArray(e)||f(e)){if(f(e)&&Object.hasOwn(e,"relationTo")&&Object.hasOwn(e,"value")){const t=O(e,"relationTo");return S(t)||m(),void h(e,"value",t,O(e,"value"))}for(const i of Object.keys(e))g(Reflect.get(e,i),t+1)}}!function e(t,i,n){u(n),d.has(t)&&m(),d.add(t);for(const s of t){u(n),f(s)&&w(s.name,512)&&!y.has(s.name)||m();const t=O(i,s.name);if("relationship"===s.type||"upload"===s.type)if(s.hasMany)if(null==t||Array.isArray(t)||m(),Array.isArray(t))for(let e=0;e<t.length;e+=1)p(t,e,s);else p(i,s.name,s);else p(i,s.name,s);else if("group"===s.type||"tabs"===s.type)null==t||f(t)||m(),f(t)&&s.fields&&e(s.fields,t,n+1);else if("row"===s.type||"collapsible"===s.type)s.fields&&e(s.fields,i,n+1);else if("array"===s.type||"blocks"===s.type){if(0===t?L(i,s.name,[]):null==t||Array.isArray(t)||m(),Array.isArray(t))for(const i of t)if(f(i)||m(),"array"===s.type&&s.fields)e(s.fields,i,n+1);else if("blocks"===s.type){const t=O(i,"blockType"),r=s.blocks?.find(e=>(u(n),e.slug===t));void 0===r&&m(),e(r.fields,i,n+1)}}else"richText"===s.type&&g(t,n+1)}d.delete(t)}(t,o,0),a.size>25&&m();const k=[];if(0===a.size)return{doc:o,requests:k};const P=new URL(i);(!["http:","https:"].includes(P.protocol)||P.username||P.password||P.search||P.hash)&&m(),(!n.startsWith("/")||n.includes("\\")||/[%?#]/u.test(n)||b(n))&&m(),n.split("/").some(e=>"."===e||".."===e)&&m();const U=`${T(i)}${T(n)}/`;for(const[e,t]of a){const i=[...new Set(t.map(e=>e.id))];let n=0;for(;n<i.length;){const o=i[n];void 0===o&&m();const a=o.includes(","),l=[];let c="";for(;n<i.length&&l.length<20;){const t=i[n];if(void 0===t||l.length>0&&(a||t.includes(",")))break;const o=[...l,t],d=new URLSearchParams({depth:String(s),limit:String(o.length)});void 0!==r&&d.set("locale",r),d.set(a?"where[id][equals]":"where[id][in]",a?t:o.join(","));const u=`${U}${encodeURIComponent(e)}?${d}`;if(u.length>8192){0===l.length&&m();break}new URL(u).origin!==P.origin&&m(),l.push(t),n+=1,c=u}(0===l.length||k.length>=64)&&m();const d=new Set(l);k.push({url:c,ids:d,slots:t.filter(e=>d.has(e.id))})}}return{doc:o,requests:k}}async function P(e,t,i){let n,s=!1,r=!1;const o=/* @__PURE__ */Symbol();let a;const l=new Promise(e=>{a=()=>{e(o)}}),c=()=>{i()&&!t.aborted||m()},d=()=>{if(void 0!==n&&!s){s=!0;try{Promise.resolve(n.cancel()).catch(()=>{})}catch{}}},u=()=>{a?.(),d()};t.addEventListener("abort",u,{once:!0});try{c();const t=e.body??null;if(c(),null===t){const t=e.json.bind(e);c();const i=await Promise.race([Promise.resolve().then(()=>(c(),t())),l]);return c(),i===o&&m(),i}const i=t.getReader.bind(t);c();const s=i();n=s,c();const a=[];let d=0,u=0;for(;;){const e=Promise.resolve().then(()=>{c();const e=s.read.bind(s);return c(),e()}),t=await Promise.race([e,l]);if(c(),t===o&&m(),t.done)break;d+=t.value.byteLength,(++u>1e4||d>g)&&m(),a.push(t.value)}r=!0;const h=new Uint8Array(d);let f=0;for(const e of a)h.set(e,f),f+=e.byteLength;try{return JSON.parse((new TextDecoder).decode(h))}catch{return m()}}finally{t.removeEventListener("abort",u),r||d();try{n?.releaseLock()}catch{}}}function U(e,t){const i=R(t);f(i)||m();const n=O(i,"docs");(!Array.isArray(n)||n.length>20)&&m();const s=/* @__PURE__ */new Map;for(const t of n){f(t)||m();const i=A(O(t,"id"));e.ids.has(i)&&!s.has(i)||m(),s.set(i,t)}s.size!==e.ids.size&&m();for(const t of e.slots)L(t.owner,t.key,s.get(t.id))}function q(e,t){return e.length>0&&e.length<=t&&"."!==e&&".."!==e&&!e.includes("/")&&!e.includes("\\")&&!function(e){for(const t of e){const e=t.codePointAt(0)??0;if(e<=31||127===e)return!0}return!1}(e)}function I(e){return q(e,128)&&!e.includes("?")&&!e.includes("#")}function j(e){return"number"==typeof e?Number.isFinite(e):"string"==typeof e&&q(e,512)}var M=new Error,N=class{serverURL;apiRoute;depth;fetchFn;log;timeoutMs;inflight=null;attempt=0;destroyDepth=0;constructor(e){this.serverURL=function(e){let t=e.length;for(;e.endsWith("/",t);)t-=1;return e.slice(0,t)}(e.serverURL);const t=e.apiRoute??"/api";var i;this.apiRoute=t.startsWith("/")?t:`/${t}`,this.depth=e.depth??1,this.fetchFn=e.fetchFn,this.log=(i=e.log??r,(...e)=>{try{s(i(...e))}catch{}});const n=e.timeoutMs??0;this.timeoutMs=n>0&&n<Number.POSITIVE_INFINITY?n:void 0}canMerge(e){try{const t=e.schema;return void 0!==t?(k(e.data,t,this.serverURL,this.apiRoute,this.depth,e.locale),!0):null!==this.endpointOf(e)}catch{return!1}}endpointOf(e){try{const t=e.globalSlug;if(t)return I(t)?{path:`globals/${encodeURIComponent(t)}`,field:"globalType",value:t}:null;const i=e.collectionSlug??"",n=e.data.id;return I(i)&&j(n)?{path:`${encodeURIComponent(i)}/${encodeURIComponent(String(n))}`,field:"id",value:String(n)}:null}catch{return null}}async merge(e){if(this.destroyDepth>0)return{status:"superseded"};const t=this.attempt+=1,i=this.inflight;this.inflight=null;let n=null,s=!1;const r=()=>this.attempt!==t,o=this.timeoutMs;let a,l;const c=(e,t)=>void 0===o?e:(void 0===l&&(l=new Promise((e,i)=>{a=setTimeout(()=>{t.abort(),i(M)},o)}),l.catch(()=>{})),Promise.race([e,l]));try{if(i?.abort(),r())return{status:"superseded"};const t=e.schema;if(s=void 0!==t,void 0!==t){const i=k(e.data,t,this.serverURL,this.apiRoute,this.depth,e.locale);if(r())return{status:"superseded"};if(0===i.requests.length)return{status:"merged",doc:i.doc};const s=this.fetchFn??("function"==typeof fetch?fetch:void 0);if(r())return{status:"superseded"};if(void 0===s)return{status:"unavailable"};n=new AbortController,this.inflight=n;for(const e of i.requests){const t=await c(s(e.url,{method:"GET",credentials:"include",redirect:"error",signal:n.signal}),n);if(r())return{status:"superseded"};const i=t.ok;if(r())return{status:"superseded"};if(!i){const e=t.status;return r()?{status:"superseded"}:(n.abort(),r()?{status:"superseded"}:(this.log("merge HTTP",e),r()?{status:"superseded"}:{status:"unavailable"}))}const o=await c(P(t,n.signal,()=>!r()),n);if(r())return{status:"superseded"};if(U(e,o),r())return{status:"superseded"}}return{status:"merged",doc:i.doc}}const o=this.endpointOf(e);if(r())return{status:"superseded"};if(null===o)return{status:"unavailable"};const a=this.fetchFn??("function"==typeof fetch?fetch:void 0);if(r())return{status:"superseded"};if(void 0===a)return{status:"unavailable"};const l=JSON.stringify({data:e.data,depth:this.depth,flattenLocales:!1,locale:e.locale});if(r())return{status:"superseded"};n=new AbortController,this.inflight=n;const d=`${this.serverURL}${this.apiRoute}/${o.path}`,u=await c(a(d,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json","X-Payload-HTTP-Method-Override":"GET"},body:l,signal:n.signal}),n);if(r())return{status:"superseded"};const h=u.ok;if(r())return{status:"superseded"};if(!h){const e=u.status;return r()?{status:"superseded"}:(this.log("merge HTTP",e,d),r()?{status:"superseded"}:{status:"unavailable"})}const f=u.json.bind(u);if(r())return{status:"superseded"};const p=await c(f(),n);if(r())return{status:"superseded"};if(null===p||"object"!=typeof p||Array.isArray(p))return this.log("merge invalid",d),r()?{status:"superseded"}:{status:"unavailable"};const v=p,g=v[o.field],y=Object.hasOwn(v,o.field)&&("id"===o.field?!j(g)||String(g)!==o.value:g!==o.value);return r()?{status:"superseded"}:y?(this.log("merge invalid",d),r()?{status:"superseded"}:{status:"unavailable"}):{status:"merged",doc:v}}catch(e){return r()?{status:"superseded"}:e===M?(this.log("merge timeout",o),{status:"unavailable"}):s&&(n?.abort(),r())?{status:"superseded"}:(this.log("merge exception",s?new Error("legacy population could not be resolved"):e),r()?{status:"superseded"}:{status:"unavailable"})}finally{clearTimeout(a),this.inflight===n&&(this.inflight=null)}}destroy(){this.attempt+=1;const e=this.inflight;this.inflight=null,this.destroyDepth+=1;try{e?.abort()}finally{this.destroyDepth-=1}}},$=class{matcher;handlers;boundListener=void 0;attachedTarget=void 0;generation=0;revision=0;queueHead=void 0;queueTail=void 0;lastAccepted=void 0;replayedGeneration=0;latestAcceptedAttempt=void 0;constructor(e,t){this.matcher=e,this.handlers=t}attach(e=window){if(void 0!==this.attachedTarget)return;let t=!1;const i=n=>{if(!t||this.boundListener!==i)return;const s=this.generation;try{this.receive(n,s,e)}catch{let e;try{e=n.origin}catch{e=""}this.reportInvalid("shape",e,s)}};this.generation+=1,this.resetQueue(),this.attachedTarget=e,this.boundListener=i;try{e.addEventListener("message",i)}catch(t){this.boundListener===i&&(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue());try{e.removeEventListener("message",i)}catch{}throw t}if(this.boundListener===i)t=!0;else try{e.removeEventListener("message",i)}catch{}}detach(){const e=this.attachedTarget,t=this.boundListener;void 0!==e&&void 0!==t&&(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue(),e.removeEventListener("message",t))}advanceGeneration(){return void 0!==this.attachedTarget&&(this.generation+=1,this.resetQueue(),!0)}replayLastAccepted(){const e=this.lastAccepted,t=this.generation,i=this.handlers.onReplay;if(void 0===i||void 0===e||e.generation>=t||this.replayedGeneration===t)return!1;if(!this.matchesOrigin(e.origin,t)||this.lastAccepted!==e)return!1;this.replayedGeneration=t;const n={generation:t,revision:this.revision+=1};return this.invokeHandler(t,i,structuredClone(e.message),e.origin,n),!0}forgetLastAccepted(){this.lastAccepted=void 0,this.replayedGeneration=0,this.latestAcceptedAttempt=void 0}static sendReady(e,t){const i={type:"payload-live-preview",ready:!0,protocolVersion:4};for(const n of e)for(const e of t)try{n.postMessage(i,e)}catch{}}receive(e,t,i){const n=e.origin;if(!this.matchesOrigin(n,t))return void this.reportInvalid("origin",n,t);if(!this.matchesSource(e,i))return void this.reportInvalid("source",n,t);const s=e.data;var r;if("object"==typeof(r=s)&&null!==r&&"type"in r&&"string"==typeof r.type)switch(s.type){case"payload-live-preview":return function(e){const t=e;return!(void 0!==t.data&&null!==t.data&&!f(t.data))&&h(t.fieldSchemaJSON,e=>Array.isArray(e))&&h(t.globalSlug,e=>"string"==typeof e)&&h(t.collectionSlug,e=>"string"==typeof e)&&h(t.locale,e=>"string"==typeof e)&&h(t.ready,e=>"boolean"==typeof e)&&h(t.previewToken,e=>"string"==typeof e)&&h(t.protocolVersion,e=>"number"==typeof e)}(s)?void this.dispatchUpdate(function(e){const t={...e};for(const e of p)null===Reflect.get(t,e)&&Reflect.deleteProperty(t,e);return Array.isArray(t.fieldSchemaJSON)?{...t,fieldSchemaJSON:l(t.fieldSchemaJSON)}:t}(s),n,t):void this.reportInvalid("shape",n,t);case"payload-document-event":return function(e){const t=e;return u(t.action,e=>"updated"===e||"created"===e||"deleted"===e)&&u(t.slug,e=>"string"==typeof e)&&u(t.id,e=>"string"==typeof e||Number.isFinite(e))}(s)?void this.invokeHandler(t,this.handlers.onDocumentEvent,s,n):void this.reportInvalid("shape",n,t);case"payload-live-preview-focus":{const e=function(e){const t=e.field;return"string"==typeof t&&t.length>0?t:void 0}(s);return void 0===e?void this.reportInvalid("shape",n,t):void this.invokeHandler(t,this.handlers.onFocusField,e,n)}default:this.reportInvalid("type",n,t)}else this.reportInvalid("shape",n,t)}dispatchUpdate(e,t,i){const n=f(e.data);if(!this.isCurrentGeneration(i))return;const s=n?{generation:i,revision:this.revision+=1}:void 0,r=this.handlers.validateToken;if(!this.isCurrentGeneration(i))return;if(void 0===r)return void this.commitUpdate(e,t,i,s);if(!0===e.ready&&void 0===e.data)return void this.commitUpdate(e,t,i,void 0);const o={generation:i,message:e,origin:t,messageRevision:s,verdict:void 0,next:void 0};let a;this.enqueue(o);try{a=r(e.previewToken,t)}catch{return void this.settleValidation(o,!1)}"boolean"!=typeof a?Promise.resolve(a).then(e=>{this.settleValidation(o,!0===e)},()=>{this.settleValidation(o,!1)}):this.settleValidation(o,a)}settleValidation(e,t){e.verdict=t,this.drainQueue(e.generation)}drainQueue(e){for(;this.isCurrentGeneration(e);){const t=this.queueHead;if(void 0===t)return;if(this.matchesOrigin(t.origin,e)){if(void 0===t.verdict)return;this.dequeue(t)&&(t.verdict?this.commitUpdate(t.message,t.origin,t.generation,t.messageRevision):this.reportInvalid("token",t.origin,t.generation))}else{if(!this.dequeue(t))continue;this.reportInvalid("origin",t.origin,t.generation)}}}commitUpdate(e,t,i,n){if(void 0===n)this.invokeHandler(i,this.handlers.onUpdate,e,t);else{const s={};this.latestAcceptedAttempt=s;const r=function(e){const t={...e};delete t.previewToken;try{return structuredClone(t)}catch{return null}}(e);if(this.latestAcceptedAttempt!==s||!this.isCurrentGeneration(i))return;this.lastAccepted=null===r?void 0:{generation:i,message:r,origin:t},this.invokeHandler(i,this.handlers.onUpdate,e,t,n)}}reportInvalid(e,t,i){this.invokeHandler(i,this.handlers.onInvalid,e,t)}matchesSource(e,t){if("parent-or-opener"!==this.handlers.sourcePolicy)return!0;try{const i=e.source;if("object"!=typeof i||null===i)return!1;const n=t.parent;return n!==t&&i===n||i===t.opener}catch{return!1}}matchesOrigin(e,t){try{return!0===(this.isCurrentGeneration(t)&&this.matcher(e))&&this.isCurrentGeneration(t)}catch{return!1}}invokeHandler(e,t,...i){if(void 0!==t&&this.isCurrentGeneration(e))try{s(t(...i))}catch{}}isCurrentGeneration(e){return void 0!==this.attachedTarget&&this.generation===e}enqueue(e){void 0===this.queueTail?this.queueHead=e:this.queueTail.next=e,this.queueTail=e}dequeue(e){return this.queueHead===e&&(this.queueHead=e.next,void 0===this.queueHead&&(this.queueTail=void 0),!0)}resetQueue(){this.queueHead=void 0,this.queueTail=void 0}};function isDevMode(){const e=function(){if("undefined"==typeof process)return;const e=process.env.NODE_ENV;return"string"==typeof e?e:void 0}();if(void 0!==e)return"production"!==e;if("undefined"!=typeof window){const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e}return!1}var E=/^https?:\/\/(localhost|127\.0\.0\.1)(?::\d+)?$/i,C=/^https?:\/\/[^/?#\s]+$/i,D=[3e3,3001,3333,4e3,4321,5e3,5173,5174,8e3,8080,8888,9e3];function H(){if("undefined"==typeof location)return;const e=location.ancestorOrigins;return e?.[0]}var OriginDetector=class{#e;constructor(e={}){const t=/* @__PURE__ */new Set;for(const i of e.additionalOrigins??[]){const e=F(i);void 0!==e&&t.add(e)}let i;if(e.enableReferrerDetection??1){const t=e.referrer??("undefined"!=typeof document?document.referrer:"");if(t.length>0)try{const e=new URL(t).origin;e&&"null"!==e&&(i=e)}catch{}}const n=(e.enableLocalhostMatching??!0)&&(e.forceDevMode??isDevMode());this.#e=[t,i,n,void 0!==i,void 0,H()]}matches(e){return 0!==e.length&&"null"!==e&&(void 0!==this.#e[4]?e===this.#e[4]:!!this.#e[0].has(e)||0===this.#e[0].size&&void 0!==this.#e[1]&&e===this.#e[1]||!(!this.#e[2]||!E.test(e)))}lockOrigin(e){return!!this.matches(e)&&(this.#e[4]=e,!0)}unlockOrigin(){const e=this.#e[4];return this.#e[4]=void 0,e}get lockedOrigin(){return this.#e[4]}enumerate(){if(void 0!==this.#e[4])return[this.#e[4]];const e=new Set(this.#e[0]);0===this.#e[0].size&&void 0!==this.#e[1]&&e.add(this.#e[1]);const t=this.#e[5];if(this.#e[2]&&void 0!==t)E.test(t)&&e.add(t);else if(this.#e[2])for(const t of D)e.add(`http://localhost:${String(t)}`),e.add(`http://127.0.0.1:${String(t)}`);return[...e]}get referrerWasAvailable(){return this.#e[3]}get isProductionUnconfigured(){return!(!function isInIframe(){if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch{return!0}}()||this.#e[0].size>0||this.#e[2]||void 0!==this.#e[1])}get isReferrerOnlyTrust(){return!(this.#e[0].size>0||this.#e[2]||void 0===this.#e[1])}};function F(e){const t=e.trim();if(0!==t.length)try{const e=new URL(t);if("http:"!==e.protocol&&"https:"!==e.protocol)return;if(!C.test(e.origin))return;return e.origin}catch{return}}function G(e){const[t,i]=e;return"merge HTTP"===t?`the server answered ${String(i)}`:"merge timeout"===t?`the server did not answer within ${String(i)} ms`:"merge invalid"===t?"the server answered with something other than a document":"merge exception"===t?i instanceof Error?i.message:"the request failed":"the update could not be merged"}var z=class{#t;#i;#n;#s;#r=/* @__PURE__ */new Set;#o;#a;#l=0;#c=[];#d=!1;#u;#h;#f;#p=!1;#v=!1;constructor(e,t){this.#n=new OriginDetector({...void 0!==t.allowedOrigins?{additionalOrigins:t.allowedOrigins}:{},enableReferrerDetection:t.enableReferrerDetection??!1,...void 0!==t.enableLocalhostMatching?{enableLocalhostMatching:t.enableLocalhostMatching}:{}}),this.#t=new N({serverURL:t.serverURL,...void 0!==t.apiRoute?{apiRoute:t.apiRoute}:{},...void 0!==t.depth?{depth:t.depth}:{},...void 0!==t.timeoutMs?{timeoutMs:t.timeoutMs}:{},...void 0!==t.fetchFn?{fetchFn:t.fetchFn}:{},log:(...e)=>{this.#c=e}}),this.#i=new $(e=>this.#n.matches(e),{onUpdate:e=>{this.#g(e)},onDocumentEvent:()=>{},sourcePolicy:t.eventSourcePolicy??"parent-or-opener"}),this.#s=t.target,this.#f=t.document,this.#o={data:e,isLoading:!0,status:"idle",error:void 0,revision:0},this.#a=this.#o}subscribe=e=>(this.#r.add(e),this.#d||this.#y(),()=>{this.#r.delete(e),0===this.#r.size&&this.#m()});getSnapshot=()=>this.#a;getServerSnapshot=()=>this.#o;#y(){"undefined"==typeof window&&void 0===this.#s||(this.#d=!0,this.#i.attach(this.#s??window),$.sendReady(this.#b(),this.#n.enumerate()))}#m(){this.#d&&(this.#d=!1,this.#l+=1,this.#i.detach(),this.#t.destroy())}#b(){const e=this.#s??("undefined"==typeof window?void 0:window);if(void 0===e)return[];const t=[];e.parent!==e&&t.push(e.parent);const i=e.opener;return null!=i&&i!==e&&t.push(i),t}#w(e){return this.#d&&e===this.#l}#S(e,t){const i=this.#f;if(void 0===i)return!0;const{locale:n,globalSlug:s,collectionSlug:r}=e;if(void 0!==i.locale&&void 0!==n&&n!==i.locale)return!1;if("global"in i){if(void 0!==s)return s===i.global;if(void 0!==r)return!1}else{if(void 0!==s)return!1;if(void 0!==r&&r!==i.collection)return!1;const e=void 0===r?void 0:function(e){const t=e.id;return"string"==typeof t&&t.length>0?t:"number"==typeof t&&Number.isFinite(t)?String(t):void 0}(t);if(void 0!==e)return e===String(i.id)}return this.#A(i),!1}#A(e){if(this.#p||!isDevMode())return;this.#p=!0;const t="global"in e?`global "${e.global}"`:`collection "${e.collection}", id "${String(e.id)}"`;console.warn(`[payload-live-preview] This hook previews ${t} and ignored an update that does not say which document it is for: Payload 2 sends no collection or global slug, and a create screen has no id yet.`)}async#g(e){const t=e.data;if(void 0===t)return;if(void 0!==e.fieldSchemaJSON&&!this.#v&&isDevMode()&&(this.#v=!0,console.warn("[payload-live-preview] This admin sends fieldSchemaJSON, which only Payload 2 does. Every 2.x release of this package supports Payload 2; 3.0 supports Payload 3 and 4.")),!this.#S(e,t))return;const i=this.#l+=1;void 0!==e.fieldSchemaJSON&&(this.#u=e.fieldSchemaJSON);const n=this.#u;void 0!==e.locale&&(this.#h=e.locale);const s=void 0===n?e.locale:this.#h;if(this.#O({...this.#a,isLoading:!0}),!this.#w(i))return;this.#c=[];const r=await this.#t.merge({data:t,...void 0===n?{}:{schema:n},...void 0!==e.collectionSlug?{collectionSlug:e.collectionSlug}:{},...void 0!==e.globalSlug?{globalSlug:e.globalSlug}:{},...void 0!==s?{locale:s}:{}});this.#w(i)&&"superseded"!==r.status&&("unavailable"!==r.status?this.#O({data:r.doc,isLoading:!1,status:"live",error:void 0,revision:i}):this.#O({...this.#a,isLoading:!1,status:"unavailable",error:new Error(`live preview: ${G(this.#c)}`)}))}#O(e){const t=this.#a;if(t.data!==e.data||t.isLoading!==e.isLoading||t.status!==e.status||t.error!==e.error||t.revision!==e.revision){this.#a=e;for(const e of[...this.#r])e()}}};function J(s){if(void 0===e())throw new Error("payload-live-preview: useLivePreviewDocument() needs an effect scope — call it from setup() or inside effectScope(), so its window listener and any request in flight are released with the component.");const{initialData:r,...o}=s,a=new z(r,o),l=t(a.getSnapshot());return i(a.subscribe(()=>{l.value=a.getSnapshot()})),{data:n(()=>l.value.data),isLoading:n(()=>l.value.isLoading),status:n(()=>l.value.status),error:n(()=>l.value.error),revision:n(()=>l.value.revision)}}export{J as useLivePreviewDocument};
|
|
1
|
+
import{getCurrentScope as e,shallowRef as t,onScopeDispose as i,computed as n}from"vue";function s(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&"function"==typeof e.then&&(Promise.resolve(e).catch(()=>{}),!0)}function r(){}function o(e){if(++e.nodes>1e4)throw new Error("invalid or oversized field schema")}function a(e,t,i){if(o(t),i>64||t.active.has(e))throw new Error("invalid or oversized field schema");t.active.add(e)}function l(e){try{return c(e,{nodes:0,active:/* @__PURE__ */new WeakSet},0)}catch{return[]}}function c(e,t,i){if(!Array.isArray(e))return[];a(e,t,i);const n=[];for(const s of e){const e=d(s,t,i);e&&n.push(e)}return t.active.delete(e),n}function d(e,t,i){if(o(t),"object"!=typeof e||null===e)return;const n=e,s=n.name,r=n.type;if("string"!=typeof s||0===s.length)return;if("string"!=typeof r||0===r.length)return;const l=c(n.fields,t,i+1),d=function(e,t,i){if("object"==typeof e&&null!==e&&!Array.isArray(e)){a(e,t,i);const n=[];for(const s in e){if(!Object.hasOwn(e,s))continue;o(t);const r=Reflect.get(e,s);"object"!=typeof r||null===r||["__proto__","constructor","prototype"].includes(s)||n.push({...r,slug:s,fields:c(r.fields,t,i+1)})}return t.active.delete(e),n}if(!Array.isArray(e))return[];a(e,t,i);const n=[];for(const s of e){if(o(t),"object"!=typeof s||null===s)continue;const e=s,r=e.slug;if("string"!=typeof r||0===r.length)continue;const a=c(e.fields,t,i+1);n.push({...e,slug:r,fields:a})}return t.active.delete(e),n}(n.blocks,t,i+1),u={...n,name:s,type:r},h=n.relationTo;if(Array.isArray(h)){const e=[];for(const i of h)o(t),e.push(i);u.relationTo=e}return l.length>0?u.fields=l:delete u.fields,d.length>0?u.blocks=d:delete u.blocks,u}function u(e,t){return void 0===e||t(e)}function h(e,t){return null==e||t(e)}function f(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}var p=["data","fieldSchemaJSON","globalSlug","collectionSlug","locale","ready","previewToken","protocolVersion"],v=1e4,g=1048576,y=/* @__PURE__ */new Set(["__proto__","constructor","prototype"]);function m(){throw new Error("invalid or oversized legacy population")}function b(e){for(let t=0;t<e.length;t+=1){const i=e.charCodeAt(t);if(i<=31||127===i)return!0}return!1}function w(e,t){if("string"!=typeof e||0===e.length||e.length>t||"."===e||".."===e)return!1;if(e.includes("/")||e.includes("\\")||b(e))return!1;try{return encodeURIComponent(e),!0}catch{return!1}}function S(e){return w(e,128)&&!/[?#%]/u.test(e)&&!y.has(e)}function A(e){return Number.isFinite(e)?String(e):w(e,512)?e:m()}function O(e,t){return Object.hasOwn(e,t)?Reflect.get(e,t):void 0}function L(e,t,i){Object.defineProperty(e,t,{value:i,writable:!0,configurable:!0,enumerable:!0})}function T(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return e.slice(0,t)}function R(e){const t=/* @__PURE__ */new WeakSet;let i=0,n=0;return function e(s,r){if(++i>v||r>64)return m();if("string"==typeof s)return n+=s.length,n>g&&m(),s;if(null==s||"boolean"==typeof s)return s;if("number"==typeof s)return Number.isFinite(s)?s:m();if(!Array.isArray(s)&&!f(s))return m();if(Array.isArray(s)){s.length>v&&m();for(let e=0;e<s.length;e+=1)Object.hasOwn(s,e)||m()}if(t.has(s))return m();t.add(s);const o=Array.isArray(s)?[]:{};for(const t of Object.keys(s))L(o,t,e(Reflect.get(s,t),r+1));return t.delete(s),o}(e,0)}function k(e,t,i,n,s,r){if(!Number.isSafeInteger(s)||s<0||s>64)return m();void 0!==r&&("string"!=typeof r||r.length>128||b(r))&&m();const o=R(e);if(!f(o))return m();const a=/* @__PURE__ */new Map,l=/* @__PURE__ */new Set;let c=0;const d=/* @__PURE__ */new WeakSet,u=e=>{(++c>v||e>64)&&m()};function h(e,t,i,n){if(null==n||""===n)return;const r=f(n)?O(n,"id"):n,o=A(r);if(0===s)return void L(e,t,r);const c=JSON.stringify([i,o]);l.add(c),l.size>1e3&&m();const d=a.get(i)??[];d.push({owner:e,key:t,id:o}),a.set(i,d)}function p(e,t,i){void 0!==i.hasMany&&"boolean"!=typeof i.hasMany&&m();const n=i.relationTo,s=O(e,t);if(Array.isArray(n)){0===n.length&&m();const e=f(s)?O(s,"relationTo"):void 0;let t;for(const i of n)u(0),S(i)||m(),i===e&&(t=i);if(null==s||""===s)return;f(s)&&void 0!==t||m(),h(s,"value",t,O(s,"value"))}else S(n)||m(),h(e,t,n,s)}function g(e,t){if(u(t),Array.isArray(e)||f(e)){if(f(e)&&Object.hasOwn(e,"relationTo")&&Object.hasOwn(e,"value")){const t=O(e,"relationTo");return S(t)||m(),void h(e,"value",t,O(e,"value"))}for(const i of Object.keys(e))g(Reflect.get(e,i),t+1)}}!function e(t,i,n){u(n),d.has(t)&&m(),d.add(t);for(const s of t){u(n),f(s)&&w(s.name,512)&&!y.has(s.name)||m();const t=O(i,s.name);if("relationship"===s.type||"upload"===s.type)if(s.hasMany)if(null==t||Array.isArray(t)||m(),Array.isArray(t))for(let e=0;e<t.length;e+=1)p(t,e,s);else p(i,s.name,s);else p(i,s.name,s);else if("group"===s.type||"tabs"===s.type)null==t||f(t)||m(),f(t)&&s.fields&&e(s.fields,t,n+1);else if("row"===s.type||"collapsible"===s.type)s.fields&&e(s.fields,i,n+1);else if("array"===s.type||"blocks"===s.type){if(0===t?L(i,s.name,[]):null==t||Array.isArray(t)||m(),Array.isArray(t))for(const i of t)if(f(i)||m(),"array"===s.type&&s.fields)e(s.fields,i,n+1);else if("blocks"===s.type){const t=O(i,"blockType"),r=s.blocks?.find(e=>(u(n),e.slug===t));void 0===r&&m(),e(r.fields,i,n+1)}}else"richText"===s.type&&g(t,n+1)}d.delete(t)}(t,o,0),a.size>25&&m();const k=[];if(0===a.size)return{doc:o,requests:k};const P=new URL(i);(!["http:","https:"].includes(P.protocol)||P.username||P.password||P.search||P.hash)&&m(),(!n.startsWith("/")||n.includes("\\")||/[%?#]/u.test(n)||b(n))&&m(),n.split("/").some(e=>"."===e||".."===e)&&m();const U=`${T(i)}${T(n)}/`;for(const[e,t]of a){const i=[...new Set(t.map(e=>e.id))];let n=0;for(;n<i.length;){const o=i[n];void 0===o&&m();const a=o.includes(","),l=[];let c="";for(;n<i.length&&l.length<20;){const t=i[n];if(void 0===t||l.length>0&&(a||t.includes(",")))break;const o=[...l,t],d=new URLSearchParams({depth:String(s),limit:String(o.length)});void 0!==r&&d.set("locale",r),d.set(a?"where[id][equals]":"where[id][in]",a?t:o.join(","));const u=`${U}${encodeURIComponent(e)}?${d}`;if(u.length>8192){0===l.length&&m();break}new URL(u).origin!==P.origin&&m(),l.push(t),n+=1,c=u}(0===l.length||k.length>=64)&&m();const d=new Set(l);k.push({url:c,ids:d,slots:t.filter(e=>d.has(e.id))})}}return{doc:o,requests:k}}async function P(e,t,i){let n,s=!1,r=!1;const o=/* @__PURE__ */Symbol();let a;const l=new Promise(e=>{a=()=>{e(o)}}),c=()=>{i()&&!t.aborted||m()},d=()=>{if(void 0!==n&&!s){s=!0;try{Promise.resolve(n.cancel()).catch(()=>{})}catch{}}},u=()=>{a?.(),d()};t.addEventListener("abort",u,{once:!0});try{c();const t=e.body??null;if(c(),null===t){const t=e.json.bind(e);c();const i=await Promise.race([Promise.resolve().then(()=>(c(),t())),l]);return c(),i===o&&m(),i}const i=t.getReader.bind(t);c();const s=i();n=s,c();const a=[];let d=0,u=0;for(;;){const e=Promise.resolve().then(()=>{c();const e=s.read.bind(s);return c(),e()}),t=await Promise.race([e,l]);if(c(),t===o&&m(),t.done)break;d+=t.value.byteLength,(++u>1e4||d>g)&&m(),a.push(t.value)}r=!0;const h=new Uint8Array(d);let f=0;for(const e of a)h.set(e,f),f+=e.byteLength;try{return JSON.parse((new TextDecoder).decode(h))}catch{return m()}}finally{t.removeEventListener("abort",u),r||d();try{n?.releaseLock()}catch{}}}function U(e,t){const i=R(t);f(i)||m();const n=O(i,"docs");(!Array.isArray(n)||n.length>20)&&m();const s=/* @__PURE__ */new Map;for(const t of n){f(t)||m();const i=A(O(t,"id"));e.ids.has(i)&&!s.has(i)||m(),s.set(i,t)}s.size!==e.ids.size&&m();for(const t of e.slots)L(t.owner,t.key,s.get(t.id))}function q(e,t){return e.length>0&&e.length<=t&&"."!==e&&".."!==e&&!e.includes("/")&&!e.includes("\\")&&!function(e){for(const t of e){const e=t.codePointAt(0)??0;if(e<=31||127===e)return!0}return!1}(e)}function I(e){return q(e,128)&&!e.includes("?")&&!e.includes("#")}function j(e){return"number"==typeof e?Number.isFinite(e):"string"==typeof e&&q(e,512)}var M=new Error,N=class{serverURL;apiRoute;depth;fetchFn;log;timeoutMs;inflight=null;attempt=0;destroyDepth=0;constructor(e){this.serverURL=function(e){let t=e.length;for(;e.endsWith("/",t);)t-=1;return e.slice(0,t)}(e.serverURL);const t=e.apiRoute??"/api";var i;this.apiRoute=t.startsWith("/")?t:`/${t}`,this.depth=e.depth??1,this.fetchFn=e.fetchFn,this.log=(i=e.log??r,(...e)=>{try{s(i(...e))}catch{}});const n=e.timeoutMs??0;this.timeoutMs=n>0&&n<Number.POSITIVE_INFINITY?n:void 0}canMerge(e){try{const t=e.schema;return void 0!==t?(k(e.data,t,this.serverURL,this.apiRoute,this.depth,e.locale),!0):null!==this.endpointOf(e)}catch{return!1}}endpointOf(e){try{const t=e.globalSlug;if(t)return I(t)?{path:`globals/${encodeURIComponent(t)}`,field:"globalType",value:t}:null;const i=e.collectionSlug??"",n=e.data.id;return I(i)&&j(n)?{path:`${encodeURIComponent(i)}/${encodeURIComponent(String(n))}`,field:"id",value:String(n)}:null}catch{return null}}async merge(e){if(this.destroyDepth>0)return{status:"superseded"};const t=this.attempt+=1,i=this.inflight;this.inflight=null;let n=null,s=!1;const r=()=>this.attempt!==t,o=this.timeoutMs;let a,l,c=!1;const d=(e,t)=>void 0===o?e:(void 0===l&&(l=new Promise((e,i)=>{a=setTimeout(()=>{c=!0,t.abort(),i(M)},o)}),l.catch(()=>{})),Promise.race([e,l]));try{if(i?.abort(),r())return{status:"superseded"};const t=e.schema;if(s=void 0!==t,void 0!==t){const i=k(e.data,t,this.serverURL,this.apiRoute,this.depth,e.locale);if(r())return{status:"superseded"};if(0===i.requests.length)return{status:"merged",doc:i.doc};const s=this.fetchFn??("function"==typeof fetch?fetch:void 0);if(r())return{status:"superseded"};if(void 0===s)return{status:"unavailable"};n=new AbortController,this.inflight=n;for(const e of i.requests){const t=await d(s(e.url,{method:"GET",credentials:"include",redirect:"error",signal:n.signal}),n);if(r())return{status:"superseded"};const i=t.ok;if(r())return{status:"superseded"};if(!i){const e=t.status;return r()?{status:"superseded"}:(n.abort(),r()?{status:"superseded"}:(this.log("merge HTTP",e),r()?{status:"superseded"}:{status:"unavailable"}))}const o=await d(P(t,n.signal,()=>!r()),n);if(r())return{status:"superseded"};if(U(e,o),r())return{status:"superseded"}}return{status:"merged",doc:i.doc}}const o=this.endpointOf(e);if(r())return{status:"superseded"};if(null===o)return{status:"unavailable"};const a=this.fetchFn??("function"==typeof fetch?fetch:void 0);if(r())return{status:"superseded"};if(void 0===a)return{status:"unavailable"};const l=JSON.stringify({data:e.data,depth:this.depth,flattenLocales:!1,locale:e.locale});if(r())return{status:"superseded"};n=new AbortController,this.inflight=n;const c=`${this.serverURL}${this.apiRoute}/${o.path}`,u=await d(a(c,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json","X-Payload-HTTP-Method-Override":"GET"},body:l,signal:n.signal}),n);if(r())return{status:"superseded"};const h=u.ok;if(r())return{status:"superseded"};if(!h){const e=u.status;return r()?{status:"superseded"}:(this.log("merge HTTP",e,c),r()?{status:"superseded"}:{status:"unavailable"})}const f=u.json.bind(u);if(r())return{status:"superseded"};const p=await d(f(),n);if(r())return{status:"superseded"};if(null===p||"object"!=typeof p||Array.isArray(p))return this.log("merge invalid",c),r()?{status:"superseded"}:{status:"unavailable"};const v=p,g=v[o.field],y=Object.hasOwn(v,o.field)&&("id"===o.field?!j(g)||String(g)!==o.value:g!==o.value);return r()?{status:"superseded"}:y?(this.log("merge invalid",c),r()?{status:"superseded"}:{status:"unavailable"}):{status:"merged",doc:v}}catch(e){return r()?{status:"superseded"}:c?(this.log("merge timeout",o),{status:"unavailable"}):s&&(n?.abort(),r())?{status:"superseded"}:(this.log("merge exception",s?new Error("legacy population could not be resolved"):e),r()?{status:"superseded"}:{status:"unavailable"})}finally{clearTimeout(a),this.inflight===n&&(this.inflight=null)}}destroy(){this.attempt+=1;const e=this.inflight;this.inflight=null,this.destroyDepth+=1;try{e?.abort()}finally{this.destroyDepth-=1}}},$=class{matcher;handlers;boundListener=void 0;attachedTarget=void 0;generation=0;revision=0;queueHead=void 0;queueTail=void 0;lastAccepted=void 0;replayedGeneration=0;latestAcceptedAttempt=void 0;constructor(e,t){this.matcher=e,this.handlers=t}attach(e=window){if(void 0!==this.attachedTarget)return;let t=!1;const i=n=>{if(!t||this.boundListener!==i)return;const s=this.generation;try{this.receive(n,s,e)}catch{let e;try{e=n.origin}catch{e=""}this.reportInvalid("shape",e,s)}};this.generation+=1,this.resetQueue(),this.attachedTarget=e,this.boundListener=i;try{e.addEventListener("message",i)}catch(t){this.boundListener===i&&(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue());try{e.removeEventListener("message",i)}catch{}throw t}if(this.boundListener===i)t=!0;else try{e.removeEventListener("message",i)}catch{}}detach(){const e=this.attachedTarget,t=this.boundListener;void 0!==e&&void 0!==t&&(this.attachedTarget=void 0,this.boundListener=void 0,this.resetQueue(),e.removeEventListener("message",t))}advanceGeneration(){return void 0!==this.attachedTarget&&(this.generation+=1,this.resetQueue(),!0)}replayLastAccepted(){const e=this.lastAccepted,t=this.generation,i=this.handlers.onReplay;if(void 0===i||void 0===e||e.generation>=t||this.replayedGeneration===t)return!1;if(!this.matchesOrigin(e.origin,t)||this.lastAccepted!==e)return!1;this.replayedGeneration=t;const n={generation:t,revision:this.revision+=1};return this.invokeHandler(t,i,structuredClone(e.message),e.origin,n),!0}forgetLastAccepted(){this.lastAccepted=void 0,this.replayedGeneration=0,this.latestAcceptedAttempt=void 0}static sendReady(e,t){const i={type:"payload-live-preview",ready:!0,protocolVersion:4};for(const n of e)for(const e of t)try{n.postMessage(i,e)}catch{}}receive(e,t,i){const n=e.origin;if(!this.matchesOrigin(n,t))return void this.reportInvalid("origin",n,t);if(!this.matchesSource(e,i))return void this.reportInvalid("source",n,t);const s=e.data;var r;if("object"==typeof(r=s)&&null!==r&&"type"in r&&"string"==typeof r.type)switch(s.type){case"payload-live-preview":return function(e){const t=e;return!(void 0!==t.data&&null!==t.data&&!f(t.data))&&h(t.fieldSchemaJSON,e=>Array.isArray(e))&&h(t.globalSlug,e=>"string"==typeof e)&&h(t.collectionSlug,e=>"string"==typeof e)&&h(t.locale,e=>"string"==typeof e)&&h(t.ready,e=>"boolean"==typeof e)&&h(t.previewToken,e=>"string"==typeof e)&&h(t.protocolVersion,e=>"number"==typeof e)}(s)?void this.dispatchUpdate(function(e){const t={...e};for(const e of p)null===Reflect.get(t,e)&&Reflect.deleteProperty(t,e);return Array.isArray(t.fieldSchemaJSON)?{...t,fieldSchemaJSON:l(t.fieldSchemaJSON)}:t}(s),n,t):void this.reportInvalid("shape",n,t);case"payload-document-event":return function(e){const t=e;return u(t.action,e=>"updated"===e||"created"===e||"deleted"===e)&&u(t.slug,e=>"string"==typeof e)&&u(t.id,e=>"string"==typeof e||Number.isFinite(e))}(s)?void this.invokeHandler(t,this.handlers.onDocumentEvent,s,n):void this.reportInvalid("shape",n,t);case"payload-live-preview-focus":{const e=function(e){const t=e.field;return"string"==typeof t&&t.length>0?t:void 0}(s);return void 0===e?void this.reportInvalid("shape",n,t):void this.invokeHandler(t,this.handlers.onFocusField,e,n)}default:this.reportInvalid("type",n,t)}else this.reportInvalid("shape",n,t)}dispatchUpdate(e,t,i){const n=f(e.data);if(!this.isCurrentGeneration(i))return;const s=n?{generation:i,revision:this.revision+=1}:void 0,r=this.handlers.validateToken;if(!this.isCurrentGeneration(i))return;if(void 0===r)return void this.commitUpdate(e,t,i,s);if(!0===e.ready&&void 0===e.data)return void this.commitUpdate(e,t,i,void 0);const o={generation:i,message:e,origin:t,messageRevision:s,verdict:void 0,next:void 0};let a;this.enqueue(o);try{a=r(e.previewToken,t)}catch{return void this.settleValidation(o,!1)}"boolean"!=typeof a?Promise.resolve(a).then(e=>{this.settleValidation(o,!0===e)},()=>{this.settleValidation(o,!1)}):this.settleValidation(o,a)}settleValidation(e,t){e.verdict=t,this.drainQueue(e.generation)}drainQueue(e){for(;this.isCurrentGeneration(e);){const t=this.queueHead;if(void 0===t)return;if(this.matchesOrigin(t.origin,e)){if(void 0===t.verdict)return;this.dequeue(t)&&(t.verdict?this.commitUpdate(t.message,t.origin,t.generation,t.messageRevision):this.reportInvalid("token",t.origin,t.generation))}else{if(!this.dequeue(t))continue;this.reportInvalid("origin",t.origin,t.generation)}}}commitUpdate(e,t,i,n){if(void 0===n)this.invokeHandler(i,this.handlers.onUpdate,e,t);else{const s={};this.latestAcceptedAttempt=s;const r=function(e){const t={...e};delete t.previewToken;try{return structuredClone(t)}catch{return null}}(e);if(this.latestAcceptedAttempt!==s||!this.isCurrentGeneration(i))return;this.lastAccepted=null===r?void 0:{generation:i,message:r,origin:t},this.invokeHandler(i,this.handlers.onUpdate,e,t,n)}}reportInvalid(e,t,i){this.invokeHandler(i,this.handlers.onInvalid,e,t)}matchesSource(e,t){if("parent-or-opener"!==this.handlers.sourcePolicy)return!0;try{const i=e.source;if("object"!=typeof i||null===i)return!1;const n=t.parent;return n!==t&&i===n||i===t.opener}catch{return!1}}matchesOrigin(e,t){try{return!0===(this.isCurrentGeneration(t)&&this.matcher(e))&&this.isCurrentGeneration(t)}catch{return!1}}invokeHandler(e,t,...i){if(void 0!==t&&this.isCurrentGeneration(e))try{s(t(...i))}catch{}}isCurrentGeneration(e){return void 0!==this.attachedTarget&&this.generation===e}enqueue(e){void 0===this.queueTail?this.queueHead=e:this.queueTail.next=e,this.queueTail=e}dequeue(e){return this.queueHead===e&&(this.queueHead=e.next,void 0===this.queueHead&&(this.queueTail=void 0),!0)}resetQueue(){this.queueHead=void 0,this.queueTail=void 0}};function isDevMode(){const e=function(){if("undefined"==typeof process)return;const e=process.env.NODE_ENV;return"string"==typeof e?e:void 0}();if(void 0!==e)return"production"!==e;if("undefined"!=typeof window){const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e}return!1}var E=/^https?:\/\/(localhost|127\.0\.0\.1)(?::\d+)?$/i,C=/^https?:\/\/[^/?#\s]+$/i,D=[3e3,3001,3333,4e3,4321,5e3,5173,5174,8e3,8080,8888,9e3];function H(){if("undefined"==typeof location)return;const e=location.ancestorOrigins;return e?.[0]}var OriginDetector=class{#e;constructor(e={}){const t=/* @__PURE__ */new Set;for(const i of e.additionalOrigins??[]){const e=F(i);void 0!==e&&t.add(e)}let i;if(e.enableReferrerDetection??1){const t=e.referrer??("undefined"!=typeof document?document.referrer:"");if(t.length>0)try{const e=new URL(t).origin;e&&"null"!==e&&(i=e)}catch{}}const n=(e.enableLocalhostMatching??!0)&&(e.forceDevMode??isDevMode());this.#e=[t,i,n,void 0!==i,void 0,H()]}matches(e){return 0!==e.length&&"null"!==e&&(void 0!==this.#e[4]?e===this.#e[4]:!!this.#e[0].has(e)||0===this.#e[0].size&&void 0!==this.#e[1]&&e===this.#e[1]||!(!this.#e[2]||!E.test(e)))}lockOrigin(e){return!!this.matches(e)&&(this.#e[4]=e,!0)}unlockOrigin(){const e=this.#e[4];return this.#e[4]=void 0,e}get lockedOrigin(){return this.#e[4]}enumerate(){if(void 0!==this.#e[4])return[this.#e[4]];const e=new Set(this.#e[0]);0===this.#e[0].size&&void 0!==this.#e[1]&&e.add(this.#e[1]);const t=this.#e[5];if(this.#e[2]&&void 0!==t)E.test(t)&&e.add(t);else if(this.#e[2])for(const t of D)e.add(`http://localhost:${String(t)}`),e.add(`http://127.0.0.1:${String(t)}`);return[...e]}get referrerWasAvailable(){return this.#e[3]}get isProductionUnconfigured(){return!(!function isInIframe(){if("undefined"==typeof window)return!1;try{return window.self!==window.top}catch{return!0}}()||this.#e[0].size>0||this.#e[2]||void 0!==this.#e[1])}get isReferrerOnlyTrust(){return!(this.#e[0].size>0||this.#e[2]||void 0===this.#e[1])}};function F(e){const t=e.trim();if(0!==t.length)try{const e=new URL(t);if("http:"!==e.protocol&&"https:"!==e.protocol)return;if(!C.test(e.origin))return;return e.origin}catch{return}}function G(e){const[t,i]=e;return"merge HTTP"===t?`the server answered ${String(i)}`:"merge timeout"===t?`the server did not answer within ${String(i)} ms`:"merge invalid"===t?"the server answered with something other than a document":"merge exception"===t?i instanceof Error?i.message:"the request failed":"the update could not be merged"}var z=class{#t;#i;#n;#s;#r=/* @__PURE__ */new Set;#o;#a;#l=0;#c=[];#d=!1;#u;#h;#f;#p=!1;#v=!1;constructor(e,t){this.#n=new OriginDetector({...void 0!==t.allowedOrigins?{additionalOrigins:t.allowedOrigins}:{},enableReferrerDetection:t.enableReferrerDetection??!1,...void 0!==t.enableLocalhostMatching?{enableLocalhostMatching:t.enableLocalhostMatching}:{}}),this.#t=new N({serverURL:t.serverURL,...void 0!==t.apiRoute?{apiRoute:t.apiRoute}:{},...void 0!==t.depth?{depth:t.depth}:{},...void 0!==t.timeoutMs?{timeoutMs:t.timeoutMs}:{},...void 0!==t.fetchFn?{fetchFn:t.fetchFn}:{},log:(...e)=>{this.#c=e}}),this.#i=new $(e=>this.#n.matches(e),{onUpdate:e=>{this.#g(e)},onDocumentEvent:()=>{},sourcePolicy:t.eventSourcePolicy??"parent-or-opener"}),this.#s=t.target,this.#f=t.document,this.#o={data:e,isLoading:!0,status:"idle",error:void 0,revision:0},this.#a=this.#o}subscribe=e=>(this.#r.add(e),this.#d||this.#y(),()=>{this.#r.delete(e),0===this.#r.size&&this.#m()});getSnapshot=()=>this.#a;getServerSnapshot=()=>this.#o;#y(){"undefined"==typeof window&&void 0===this.#s||(this.#d=!0,this.#i.attach(this.#s??window),$.sendReady(this.#b(),this.#n.enumerate()))}#m(){this.#d&&(this.#d=!1,this.#l+=1,this.#i.detach(),this.#t.destroy())}#b(){const e=this.#s??("undefined"==typeof window?void 0:window);if(void 0===e)return[];const t=[];e.parent!==e&&t.push(e.parent);const i=e.opener;return null!=i&&i!==e&&t.push(i),t}#w(e){return this.#d&&e===this.#l}#S(e,t){const i=this.#f;if(void 0===i)return!0;const{locale:n,globalSlug:s,collectionSlug:r}=e;if(void 0!==i.locale&&void 0!==n&&n!==i.locale)return!1;if("global"in i){if(void 0!==s)return s===i.global;if(void 0!==r)return!1}else{if(void 0!==s)return!1;if(void 0!==r&&r!==i.collection)return!1;const e=void 0===r?void 0:function(e){const t=e.id;return"string"==typeof t&&t.length>0?t:"number"==typeof t&&Number.isFinite(t)?String(t):void 0}(t);if(void 0!==e)return e===String(i.id)}return this.#A(i),!1}#A(e){if(this.#p||!isDevMode())return;this.#p=!0;const t="global"in e?`global "${e.global}"`:`collection "${e.collection}", id "${String(e.id)}"`;console.warn(`[payload-live-preview] This hook previews ${t} and ignored an update that does not say which document it is for: Payload 2 sends no collection or global slug, and a create screen has no id yet.`)}async#g(e){const t=e.data;if(void 0===t)return;if(void 0!==e.fieldSchemaJSON&&!this.#v&&isDevMode()&&(this.#v=!0,console.warn("[payload-live-preview] This admin sends fieldSchemaJSON, which only Payload 2 does. Every 2.x release of this package supports Payload 2; 3.0 supports Payload 3 and 4.")),!this.#S(e,t))return;const i=this.#l+=1;void 0!==e.fieldSchemaJSON&&(this.#u=e.fieldSchemaJSON);const n=this.#u;void 0!==e.locale&&(this.#h=e.locale);const s=void 0===n?e.locale:this.#h;if(this.#O({...this.#a,isLoading:!0}),!this.#w(i))return;this.#c=[];const r=await this.#t.merge({data:t,...void 0===n?{}:{schema:n},...void 0!==e.collectionSlug?{collectionSlug:e.collectionSlug}:{},...void 0!==e.globalSlug?{globalSlug:e.globalSlug}:{},...void 0!==s?{locale:s}:{}});this.#w(i)&&"superseded"!==r.status&&("unavailable"!==r.status?this.#O({data:r.doc,isLoading:!1,status:"live",error:void 0,revision:i}):this.#O({...this.#a,isLoading:!1,status:"unavailable",error:new Error(`live preview: ${G(this.#c)}`)}))}#O(e){const t=this.#a;if(t.data!==e.data||t.isLoading!==e.isLoading||t.status!==e.status||t.error!==e.error||t.revision!==e.revision){this.#a=e;for(const e of[...this.#r])e()}}};function J(s){if(void 0===e())throw new Error("payload-live-preview: useLivePreviewDocument() needs an effect scope — call it from setup() or inside effectScope(), so its window listener and any request in flight are released with the component.");const{initialData:r,...o}=s,a=new z(r,o),l=t(a.getSnapshot());return i(a.subscribe(()=>{l.value=a.getSnapshot()})),{data:n(()=>l.value.data),isLoading:n(()=>l.value.isLoading),status:n(()=>l.value.status),error:n(()=>l.value.error),revision:n(()=>l.value.revision)}}export{J as useLivePreviewDocument};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|