@format.dev/studio 0.4.0 → 0.4.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.
@@ -1,265 +0,0 @@
1
- import*as e from"node:path";import t,{basename as n,dirname as r,isAbsolute as i,join as a,relative as o,resolve as s,sep as c}from"node:path";import l,{existsSync as u,readFileSync as d,readdirSync as f,renameSync as p,rmSync as m,writeFileSync as ee}from"node:fs";import{atlas as h}from"gradient-string";import{createServer as te,mergeConfig as ne,searchForWorkspaceRoot as re}from"vite";import ie from"open";import{RemoteAssetFetchError as ae,fetchRemote as oe,fetchRemoteIfChanged as se,readRemoteAssets as ce,scanAssetRefs as le,scanRemoteRefs as ue}from"@format.dev/zip";import{SUPPORTED_FRAMEWORKS as de}from"@format.dev/compile/shared/types/public/index";import{checkDir as fe,formatForLog as pe,getLogLevel as me,loadConfig as g,logger as _,parseLogLevelFromEnv as he,readFile as ge,setLogLevel as _e}from"@format.dev/compile/server/utils/index";import{getSchemaPath as ve,validate as ye}from"@format.dev/compile/server/utils/schema";import be,{parseEnv as xe,stripVTControlCharacters as Se}from"node:util";import v,{chmod as Ce,mkdir as y,open as we,readFile as b,readdir as Te,rename as Ee,rm as De,stat as Oe,writeFile as x}from"node:fs/promises";import{CliError as ke,buildDocumentPlan as Ae,maybeInstallDependencies as je,maybeSetupProject as Me,readProjectDependencies as Ne,resolveStyling as Pe,writeDocument as Fe}from"@format.dev/cli/scaffold";import{PROJECT_EXTENSIONS_ALL as Ie,SERVER_WATCH_IGNORE as Le}from"@format.dev/compile/server/constants";import Re from"node:os";import{fileURLToPath as ze}from"node:url";import{DOT_FORMAT_DIR_NAME as Be,DOT_TMP_DIR_NAME as Ve}from"@format.dev/compile/server/project/paths";import{DEFAULT_VARIANT as He,DEV_API_PORT as Ue,DEV_DASHBOARD_API_PORT as We,DEV_DASHBOARD_PORT as Ge,DEV_WEB_PORT as Ke,NO_DOCUMENTS_MESSAGE as qe,VARIANT_PARAM as Je}from"@format.dev/compile/shared/constants";import{readFile as Ye}from"@format.dev/compile/server/utils/read-file";import{CompileError as Xe}from"@format.dev/compile/server/errors";import{DEFAULT_STYLING as Ze,PAGE_LENGTH_HINT as Qe,SCHEMA_DEPENDENCIES as $e,STYLING_DEPENDENCIES as et,isSchemaKind as tt,parsePageLength as nt}from"@format.dev/cli/scaffold/shared";import{findFormatConfigPath as rt,loadConfig as it}from"@format.dev/compile/server/utils/load-config";import{getUserProjectDir as S}from"@format.dev/compile/server/project/user-project-dir";import{SHARED_ASSETS_OUT_DIR_NAME as at}from"@format.dev/compile/server/compile/constants";import{compileState as C}from"@format.dev/compile/server/runtime-state";import{getDataVariants as ot,getDocumentDataDir as st,getDocumentDataFile as ct,getDocumentDataVariantPath as lt,getDocumentDataVariantPath as ut,getDocuments as dt,getDocuments as ft,getUserDocumentIndex as pt}from"@format.dev/compile/server/project/documents";import{SANDBOX_ERROR_CODE as mt}from"@format.dev/compile/server/render-worker/sandbox";import{LogLevel as ht}from"@format.dev/compile/shared/types/index";import{STUDIO_FORBID_TAGS as gt,UNSUPPORTED_TAGS as _t,getPermittedContentType as vt}from"@format.dev/utils";import{unified as yt}from"unified";import bt,{defaultSchema as xt}from"rehype-sanitize";import{buildObservedSchema as St,parseHtmlFragment as Ct,removeTags as wt,stringifyHtmlFragment as Tt,stripDangerousUrls as Et}from"@format.dev/compile/server/compile/sanitize/shared";import{compileForStudio as Dt,getBundleOutDir as Ot,getDocumentAssetsPath as kt,getDocumentEntryPath as At,renderCompiledDocument as jt}from"@format.dev/compile/server/compile/compile";import{DOCUMENT_ASSETS_DIR_NAME as Mt,resolveDocumentAssetSources as Nt}from"@format.dev/compile/server/compile/document-assets";import*as Pt from"@format.dev/compile/server/compile/producer-release";import{createHash as w,randomBytes as Ft,randomUUID as It}from"node:crypto";import{documentFontCss as Lt,fontsDir as Rt}from"@format.dev/fonts";import{isDev as zt}from"@format.dev/compile/shared/env";import{restampDocumentEngine as Bt}from"@format.dev/compile/server/compile/finalize-document-html";import{http as Vt}from"@format.dev/compile/shared/http";import{setTimeout as Ht}from"node:timers/promises";import{createServer as Ut}from"node:http";import{FormatClient as Wt}from"@format.dev/client";import{logger as Gt}from"@format.dev/compile/server/utils/log";import T from"os";import Kt from"adm-zip";import qt from"prettier";import{stylesPreProcessor as Jt}from"@format.dev/compile/server/vite/plugins/styles-pre-processor";import{createConfig as Yt}from"@format.dev/compile/server/vite/create-config";import{shouldDecodeStyleEntities as Xt}from"@format.dev/compile/server/utils/dependencies";import{getLockstepStatus as Zt}from"@format.dev/cli/lockstep";import{assertProducersAgree as Qt}from"@format.dev/compile/server/compile/producer-agreement";import{RenderWorker as $t}from"@format.dev/compile/server/render-worker/index";var en=Object.defineProperty,tn=Object.getOwnPropertyDescriptor,nn=Object.getOwnPropertyNames,rn=Object.prototype.hasOwnProperty,an=(e,t)=>{let n={};for(var r in e)en(n,r,{get:e[r],enumerable:!0});return t&&en(n,Symbol.toStringTag,{value:`Module`}),n},on=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=nn(t),a=0,o=i.length,s;a<o;a++)s=i[a],!rn.call(e,s)&&s!==n&&en(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=tn(t,s))||r.enumerable});return e},sn=(e,t,n)=>(on(e,t,`default`),n&&on(n,t,`default`)),E=class e extends Error{constructor(t){super(t),this.name=`StudioError`,Error.captureStackTrace?.(this,e)}},D=class extends E{constructor(e){super(e),this.name=`ServerUnreachableError`}},cn=class extends E{constructor(e){super(e),this.name=`SessionExpiredError`}};function O({res:e,status:t,data:n}){let r=JSON.stringify(n);e.statusCode=t,e.setHeader(`Content-Type`,`application/json; charset=utf-8`),e.setHeader(`Content-Length`,Buffer.byteLength(r)),e.end(r)}async function k(e){let t=``;for await(let n of e)t+=n.toString();if(!t)throw Error(`Request body is empty`);try{return JSON.parse(t)}catch{throw Error(`Invalid JSON body`)}}var A=class extends Error{constructor(e,t){super(t),this.status=e,this.name=`HttpError`}};function j(e,t){return t instanceof A?O({res:e,status:t.status,data:{error:t.message}}):O({res:e,status:500,data:{error:t instanceof Error?t.message:`Internal server error`}})}function ln(e){return typeof e==`string`?Se(e):Array.isArray(e)?e.map(ln):typeof e==`object`&&e&&Object.getPrototypeOf(e)===Object.prototype?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,ln(t)])):e}function M(e,t){e?.ws.send({type:`custom`,event:`studio-server-error`,data:ln(t)})}const N=`Your Studio session has expired. Reconnect to continue.`,un=`http://localhost`,dn=`Can't connect to Format servers. Check your connection and try again.`,fn=e=>`Port ${e} is already in use. Another Studio may still be running. Stop it, or pass --port <number>.`;function pn(e){return e.backgroundPdfBuild??!0}function mn(){try{return JSON.parse(d(z,`utf-8`))}catch{return{}}}async function hn(){await Ye(z)||(await y(En,{recursive:!0}),await x(z,JSON.stringify({},null,2)))}async function P(){return await hn(),await Ye(z)}async function gn(e){await hn(),await x(z,JSON.stringify(e,null,2))}const _n={production:{name:`production`,dashboardUrl:`https://dash.format.dev`,dashboardApiUrl:`https://backend.dash.format.dev`,apiUrl:`https://api.format.dev`,webUrl:`https://format.dev`},local:{name:`local`,dashboardUrl:`http://localhost:${Ge}`,dashboardApiUrl:`http://localhost:${We}`,apiUrl:`http://localhost:${Ue}`,webUrl:`http://localhost:${Ke}`,stampEngineVersion:`999.0.0`}};let F=null;function vn(e){let t=process.env.FMT_ENV?.trim();if(t)return{name:t,source:`FMT_ENV`};let n=typeof e.env==`string`?e.env:void 0;return n?{name:n,source:`settings`}:{name:`production`,source:`default`}}function yn(e){let{name:t,source:n}=vn(e),r=process.env.FMT_DASHBOARD_URL?.trim(),i=process.env.FMT_DASHBOARD_API_URL?.trim(),a=process.env.FMT_API_URL?.trim(),o=process.env.FMT_WEB_URL?.trim(),s=_n[t];if(s)return{environment:{...s,dashboardUrl:r||s.dashboardUrl,dashboardApiUrl:i||s.dashboardApiUrl,apiUrl:a||s.apiUrl,webUrl:o||s.webUrl},source:n};if(r&&i&&a&&o)return{environment:{name:t,dashboardUrl:r,dashboardApiUrl:i,apiUrl:a,webUrl:o},source:n};throw new E(`Unknown environment "${t}". Known environments are production and local; define another by setting FMT_DASHBOARD_URL, FMT_DASHBOARD_API_URL, FMT_API_URL and FMT_WEB_URL.`)}function bn(e){return F=yn(e.settings),F.environment}function xn(e){return e.environment.name!==`production`||e.source===`FMT_ENV`}function Sn(){return F||(F=yn(mn())),F}function I(){return Sn().environment}var L=an({DOT_FORMAT_DIR:()=>En,ENGINE_DIR:()=>V,ENVS_DIR:()=>Dn,FORMAT_ENGINE_PATH:()=>Mn,PUBLIC_DIR:()=>wn,SETTINGS_FILE:()=>z,STUDIO_APP_ALIAS:()=>Tn,_dirname:()=>R,getCredentialsFile:()=>kn,getDotTempDir:()=>jn,getEnvDir:()=>On,getPdfBuildDir:()=>B,getStateFile:()=>An});import*as Cn from"@format.dev/compile/server/project/paths";sn(L,Cn);const R=a(r(ze(import.meta.url)),`..`),wn=a(R,`public`),Tn=`/@format/studio`,En=a(Re.homedir(),Be),z=a(En,`settings.json`),Dn=a(En,`envs`),On=()=>a(Dn,I().name),kn=()=>a(On(),`credentials.json`),An=()=>a(On(),`state.json`),jn=()=>process.env.FMT_DOT_TMP_DIR?.trim()||s(R,`..`,Ve),B=e=>a(e,`node_modules`,`.cache`,`format-studio`,`pdf-build`),V=a(R,`engine`),Mn=e=>a(V,e,`format_engine.js`),H={diagnostics:{sanitization:null,remoteAssets:null,imageFormats:null,unsupportedElements:null},auth:{token:null,failed:!1},engine:{requested:null,resolved:null},activeDocumentAssetSources:null,skipNextConfigRestart:!1},U={armConfigRestartSkip(){H.skipNextConfigRestart=!0},consumeConfigRestartSkip(){return H.skipNextConfigRestart?(H.skipNextConfigRestart=!1,!0):!1},getToken(){if(!H.auth.token)throw new E(`Auth token not initialized`);return H.auth.token},setToken(e){H.auth.token=e},clearToken(){H.auth.token=null},isAuthFailed(){return H.auth.failed},setAuthFailed(){H.auth.failed=!0},clearAuthFailed(){H.auth.failed=!1},setEngineVersions(e){H.engine.requested=e.requested,H.engine.resolved=e.resolved},getEngineRequested(){if(!H.engine.requested)throw new E(`Requested engine not set`);return H.engine.requested},getEngineResolved(){if(!H.engine.resolved)throw new E(`Resolved engine not set`);return H.engine.resolved},setSanitizationDiagnostics(e){H.diagnostics.sanitization=e},setRemoteAssetDiagnostics(e){H.diagnostics.remoteAssets=e},setImageFormatDiagnostics(e){H.diagnostics.imageFormats=e},setUnsupportedElementDiagnostics(e){H.diagnostics.unsupportedElements=e},getDiagnostics(){return H.diagnostics},setActiveDocumentAssetSources(e){H.activeDocumentAssetSources=e},getActiveDocumentAssetSources(){return H.activeDocumentAssetSources}};function Nn(e){return async(t,n,r)=>{let i=t.url?.match(/^\/api\/documents\/([^\/]+)\/data\/([^\/]+)$/);if(!i)return r();if(U.isAuthFailed())return j(n,new A(401,N));let[,a,o]=i,s=await ct(a,o,C.getConfig());if(!s){let n=o===He?`Please create a default.json file in the ${a}/data directory. Refer to our documentation for more information.`:`Failed to load ${a} with variant ${o}. Please check the URL or create a ${o}.json file in the ${a}/data directory. Refer to our documentation for more information.`;return M(e,{scope:`document`,path:t.url,message:n,dismissible:!1}),r()}O({res:n,status:200,data:s})}}function Pn(){return async(e,t)=>{try{if(U.isAuthFailed())throw new A(401,N);O({res:t,status:200,data:await dt(C.getConfig())})}catch(e){j(t,e)}}}const Fn={react:`.tsx`,vue:`.vue`,html:`.ts`};async function In(e){let{wanted:t,styling:n,config:r}=e;if(!t||n===void 0||!Pe({framework:r.framework,method:n}).setupProject)return null;let i=S(),a=rt(i);if(!a)return _.warn(`Skipping project setup: no Format config file found to amend.`),null;let s=o(i,(0,L.getDocumentsDir)(r));U.armConfigRestartSkip();let c=await Me({wanted:t,styling:n,config:r,projectRoot:i,formatConfigPath:a,documentsGlobBase:s});try{let e=await it(a);C.setConfig(e.config)}catch(e){_.warn(`Failed to reload the Format config after project setup.`,e)}return c}function Ln(e){if(e==null)return;if(typeof e!=`string`)return e;let t=e.trim();if(t!==``)try{return JSON.parse(t)}catch{throw new A(400,`The data you provided isn't valid JSON.`)}}function Rn(e){let t=e=>e!=null;if(!t(e.width)&&!t(e.height))return;if(!t(e.width)||!t(e.height))throw new A(400,`A page size needs both a width and a height.`);let n=t=>{let n=e[t],r=typeof n==`number`||typeof n==`string`,i=r?nt(String(n)):void 0;if(i===void 0)throw new A(400,`Invalid ${t}${r?`: "${n}"`:``}. ${Qe}`);return i};return{width:n(`width`),height:n(`height`)}}function zn(e){return async(t,n,r)=>{if(t.method!==`POST`)return r();try{if(U.isAuthFailed())throw new A(401,N);let r=await k(t);if(typeof r.name!=`string`)throw new A(400,`A document name is required.`);let i=r.styling===void 0?void 0:String(r.styling),a=C.getConfig(),o=r.schema===!0,s=typeof r.schemaKind==`string`&&tt(r.schemaKind)?r.schemaKind:void 0,c=Rn(r),l=Ln(r.data),u=await Ae({config:a,projectRoot:S(),name:r.name,styling:i,emitSchema:o,schemaKind:s,width:c?.width,height:c?.height,data:l}),d=await je({wanted:r.installDependencies===!0,projectRoot:S(),emitSchema:o,schemaKind:s,missingStylingDependencies:u.prerequisites.missingDependencies.map(e=>e.name)}),f=await In({wanted:r.installDependencies===!0,styling:i,config:a});await Fe(u);let p={name:u.documentName,variants:[He],extension:Fn[a.framework],lastModified:Date.now()},m=await Pe({framework:a.framework,method:i??Ze}).checkPrerequisites({config:C.getConfig(),projectRoot:S()});if(d.attempted&&d.ok||f!==null)try{f!==null&&e.updateInitConfig(JSON.stringify(C.getConfig())),await e.restart()}catch(e){_.warn(`Failed to restart the render worker after project setup.`,e)}O({res:n,status:201,data:{document:p,prerequisites:m,install:d,projectSetup:f}})}catch(e){if(e instanceof Xe||e instanceof ke)return j(n,new A(400,e.message));j(n,e)}}}async function Bn(e){try{return await b(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Vn(e){let{dataFilePath:t,documentName:i,variant:a,hasDataFiles:o}=e,s=`${n(r(t))}/${n(t)}`,c=await Bn(t);if(c===null)return a===He&&!o?{ok:!0,data:{}}:{ok:!1,title:`Missing data file`,message:`The \`${a}\` variant of \`${i}\` has no data file. Add \`${s}\`, or pick another variant.`};try{return{ok:!0,data:JSON.parse(c)}}catch(e){return{ok:!1,title:`Invalid data file`,message:`\`${s}\` in \`${i}\` isn't valid JSON.\n\n\`\`\`\n${e.message}\n\`\`\``}}}const Hn=async(e,t)=>{try{return await e.ssrLoadModule(t)}catch(e){return _.error(`Failed to load module at path: ${t}`,e),null}};async function Un(e){let t=performance.now(),n={},{dataFilePath:r,variant:i,config:a,documentName:o,server:s,renderWorker:c}=e;_.debug(`Render input args`,JSON.stringify({dataFilePath:r,config:a}));try{if(!a.framework)throw new E(`Framework not provided or invalid: ${a.framework}. Must be one of: ${de.join(`, `)}`);if(r){let e=await Vn({dataFilePath:r,documentName:o,variant:i,hasDataFiles:(await ot(o,a)).length>0});if(!e.ok)return M(s,{scope:`document`,dismissible:!1,title:e.title,message:e.message}),_.error(e.message),null;n=e.data}let l=await ve(st(o,a));if(l){let{default:e}=await Hn(s,l);if(e||_.warn(`Schema File found, but no valid schema found at ${l}. Ensure your schema library follows the Standard Schema V1 spec and you are using a default export. Read more in our docs.`),e){let t=await ye(e,n);if(!t.ok){let{errors:e}=t;return M(s,{scope:`document`,dismissible:!1,message:`Data validation failed for ${o}. Check your schema and data.`,details:e}),_.error(`Data validation failed for ${o}. Check your schema and data.`,e),null}n=t.data}}let{framework:u}=a,d=U.getEngineResolved();_.debug(`Delegating render to worker (framework=${u}, engine=${d})`);let f=await c.devRender({entryFilePath:e.entryFilePath,data:n,framework:u,engineVersion:d});return _.info(`Loaded "${o}" document in: ${(performance.now()-t).toFixed(2)}ms`),f.html}catch(e){let t=e?.code===mt;throw M(s,{scope:`document`,dismissible:!1,title:t?`Document restriction`:`Document rendering error`,message:t?e.message:void 0,...!t&&{stack:e.stack}}),e}}const Wn=new Set(gt.map(e=>e.toLowerCase()));function Gn(e){return St(xt,e,!0)}function Kn(e){let t={},n=Ct(e);wt(n,Wn,e=>{t[e]=(t[e]??0)+1}),Et(n);let r=Gn(n),i=yt().use(bt,r).runSync(n),a=Tt(i),o=Object.values(t).reduce((e,t)=>e+t,0),s=o===0?null:{removedElements:o,removedTags:t};return{html:String(a),diagnostics:s,tree:i}}const qn=[`.webp`,`.avif`];function Jn(e){let t=e.toLowerCase();return qn.some(e=>t.endsWith(e))}function Yn(e){return e.filter(Jn).sort()}const Xn=new Set(_t.map(e=>e.toLowerCase()));function Zn(e,t){if(e.type===`element`&&e.tagName){let n=e.tagName.toLowerCase();Xn.has(n)&&t.add(n)}for(let n of e.children||[])Zn(n,t);for(let n of e.content?.children||[])Zn(n,t)}function Qn(e){let t=new Set;return Zn(e,t),[...t].sort()}function $n(){let e=C.getConfig(),t=S(),n=e.dotEnvPath??`.env`;return i(n)?n:a(t,n)}async function er(e,t){return ar(await Promise.all([...e].sort().map(async e=>(await t(e)).map(e=>`${e.path}:${e.mtimeMs}:${e.size}`).sort().join(`
2
- `))))}async function tr(e){let{inputs:t,directories:n,key:r,stat:i,listDir:a}=e;return{files:(await Promise.all(t.map(async e=>({path:e,stats:await i(e)})))).filter(e=>e.stats!==null).map(({path:e,stats:t})=>({path:e,mtimeMs:t.mtimeMs,size:t.size})).sort((e,t)=>e.path.localeCompare(t.path)),directories:[...n].sort(),directoriesHash:await er(n,a),key:r}}async function nr(e){let{manifest:t,key:n,stat:r,listDir:i}=e;return t.key!==n||t.files.length===0||await er(t.directories,i)!==t.directoriesHash?!1:(await Promise.all(t.files.map(async e=>{let t=await r(e.path);return t!==null&&t.mtimeMs===e.mtimeMs&&t.size===e.size}))).every(Boolean)}function rr(e,t){let n=o(s(t),s(e));return n===``||!n.startsWith(`..${c}`)&&n!==`..`&&!n.startsWith(`/`)}function ir(e,t){let n=s(t);return e.files.some(e=>e.path===n)||e.directories.some(e=>rr(n,e))?!0:e.files.some(e=>r(e.path)===n)}function ar(e){return w(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function or(e){let t=w(`sha256`);for(let n of e)t.update(typeof n==`string`?n:Buffer.from(n)),t.update(`\0`);return t.digest(`hex`)}function sr(){let e=new Map,t=Promise.resolve(),n=e=>{let n=t.then(e,e);return t=n.catch(()=>{}),n},r=(t,r)=>{let i={running:Promise.resolve(),dirty:!1},a=(async()=>{let e=await n(r);return i.dirty?(i.dirty=!1,n(r)):e})().finally(()=>{e.get(t)===i&&e.delete(t)});return i.running=a,e.set(t,i),a};return{run(t,n){let i=e.get(t);return i?(i.dirty=!0,i.running):r(t,n)},isRunning(t){return e.has(t)},isBusy(){return e.size>0}}}function cr(e={fetchRemote:oe,fetchRemoteIfChanged:se}){let t=new Map,n=new Map;async function r(n){let r=t.get(n.url);if(!r){let r=await e.fetchRemote(n);return t.set(n.url,r),r}try{let i=await e.fetchRemoteIfChanged({...n,validators:r.validators});return i?(t.set(n.url,i),i):r}catch(e){if(!(e instanceof ae))throw e;return _.debug(`Could not reach ${n.url} to check for changes, using the copy from earlier`),r}}function i(e){let t=n.get(e.url);if(t)return t;let i=r(e).finally(()=>n.delete(e.url));return n.set(e.url,i),i}return{beginCheck(){let e=new Set;return async n=>{let r=t.get(n.url);if(r&&e.has(n.url))return r;let a=await i(n);return e.add(n.url),a}},clear(){t.clear(),n.clear()}}}const lr=(e,t)=>a(e,t,`build`),ur=(e,t)=>a(e,t,`inputs.json`),dr=(e,t)=>a(e,t,`pdfs`);async function fr(e,t){try{let n=await b(ur(e,t),`utf-8`),r=JSON.parse(n);return!Array.isArray(r.files)||!Array.isArray(r.directories)||typeof r.key!=`string`?null:r}catch{return null}}async function pr(e,t,n){let r=ur(e,t);await y(s(r,`..`),{recursive:!0}),await x(r,JSON.stringify(n),`utf-8`)}async function mr(e,t){await De(ur(e,t),{force:!0}).catch(()=>{})}async function hr(e,t,n){try{return await b(a(dr(e,t),`${n}.pdf`))}catch{return null}}async function gr(e,t,n,r){let i=dr(e,t);try{await y(i,{recursive:!0}),await x(a(i,`${n}.pdf`),r),await vr(i)}catch(e){_.debug(`Could not cache the generated PDF`,e)}}async function _r(e){let{pdfBuildDir:t,documentName:n,key:r,cache:i,generate:a}=e;if(i){let e=await hr(t,n,r);if(e)return{bytes:e,cached:!0}}let o=await a();return i&&await gr(t,n,r,o),{bytes:o,cached:!1}}async function vr(e){let t=(await Te(e).catch(()=>[])).filter(e=>e.endsWith(`.pdf`));if(t.length<=5)return;let n=(await Promise.all(t.map(async t=>({name:t,mtimeMs:(await Oe(a(e,t)).catch(()=>null))?.mtimeMs??0})))).sort((e,t)=>t.mtimeMs-e.mtimeMs).slice(5);await Promise.all(n.map(t=>De(a(e,t.name),{force:!0}).catch(()=>{})))}const W=async e=>{let t=await Oe(e).catch(()=>null);return!t||!t.isFile()?null:{mtimeMs:t.mtimeMs,size:t.size}},yr=async e=>{let t=await Te(e,{recursive:!0,withFileTypes:!0}).catch(()=>[]);return(await Promise.all(t.filter(e=>e.isFile()).map(async e=>{let t=a(e.parentPath,e.name),n=await W(t);return n?{path:t,mtimeMs:n.mtimeMs,size:n.size}:null}))).filter(e=>e!==null)},G=new Map,br=new Map,xr=sr();let Sr=1,Cr=null;const wr=cr(),Tr=new Set;function Er(e){Cr=e}function K(e,t){Cr?.({documentName:e,state:t})}const Dr=(e,t)=>`${e}/${t}`;function Or(e,t){return{documents:[e],remoteAssets:!0,inlineRemoteCss:!0,validateSchema:!1,clean:!1,outDir:t}}function kr(e){return ar({options:e.options,config:e.config,sdkVersion:Pt.sdkVersion,engineTarget:Pt.engineTarget})}function Ar(e,t){return[(0,L.getSharedAssetsDir)(t),a((0,L.getDocumentsDir)(t),e,Mt)]}async function jr(e){let{documentName:t,outDir:n,key:r}=e,i=await fr(B(S()),t);return!i||await W(At(n,t))===null||!await nr({manifest:i,key:r,stat:W,listDir:yr})?null:(_.debug(`Reusing the PDF bundle on disk for "${t}"`),{buildId:Sr++,outDir:n,manifest:i})}async function Mr(e){let{documentName:t,config:n,outDir:r,key:i,background:a,remoteFetch:o}=e,s=B(S()),c=Or(t,r);K(t,`building`);let l=performance.now(),{inputs:u}=await Dt(c,{useDiskCache:!1,remoteFetch:o,quiet:a}),d=$n(),f=await tr({inputs:await W(d)===null?u:[...u,d],directories:Ar(t,n),key:i,stat:W,listDir:yr});return await pr(s,t,f),_.debug(`Built the PDF bundle for "${t}" in ${(performance.now()-l).toFixed(0)}ms`),{buildId:Sr++,outDir:r,manifest:f}}async function Nr(e){let{documentName:t,config:n,background:r=!1,remoteFetch:i=wr.beginCheck()}=e,a=B(S()),o=lr(a,t),s=kr({documentName:t,config:n,options:Or(t,o)}),c=G.get(t);return!Tr.has(t)&&c&&c.manifest.key===s&&await nr({manifest:c.manifest,key:s,stat:W,listDir:yr})?c:xr.run(t,async()=>{let e=Tr.has(t),c=G.get(t);if(!e&&c&&c.manifest.key===s&&await nr({manifest:c.manifest,key:s,stat:W,listDir:yr}))return c;try{let a=(e?null:await jr({documentName:t,config:n,outDir:o,key:s}))??await Mr({documentName:t,config:n,outDir:o,key:s,background:r,remoteFetch:i});return Tr.delete(t),G.set(t,a),K(t,`ready`),a}catch(e){throw G.delete(t),await mr(a,t),K(t,`error`),e}})}async function Pr(e){let{documentName:t,variant:n,config:r,remoteFetch:i}=e,a=await Nr({documentName:t,config:r,remoteFetch:i}),o=(await W(lt(t,n,r)))?.mtimeMs??null,s=Dr(t,n),c=br.get(s);if(c&&c.buildId===a.buildId&&c.dataMtimeMs===o)return{html:c.html,outDir:a.outDir};let l=await jt({outDir:a.outDir,documentName:t,variant:n,config:r,remoteAssets:!0,remoteFetch:i});return br.set(s,{buildId:a.buildId,dataMtimeMs:o,html:l}),{html:l,outDir:a.outDir}}async function Fr(e){let{documentName:t,variant:n,config:r,stampHtml:i,cachePdf:a,generatePdf:o}=e,s=wr.beginCheck();await Ir({documentName:t,config:r,remoteFetch:s});let{html:c,outDir:l}=await Pr({documentName:t,variant:n,config:r,remoteFetch:s}),u=i(c),d=await b(kt(l,t)).catch(()=>void 0),f=await _r({pdfBuildDir:B(S()),documentName:t,key:or([u,d??new Uint8Array]),cache:a,generate:()=>o({html:u,assets:d})});return f.cached&&_.debug(`Serving "${t}" (${n}) from the PDF cache`),f}async function Ir(e){let{documentName:t,config:n,remoteFetch:r}=e,i=await b(kt((await Nr({documentName:t,config:n,remoteFetch:r})).outDir,t)).catch(()=>void 0);i&&(await Promise.all(ce(i).map(async e=>{let t=await r({url:e.url});return Buffer.compare(t.bytes,e.bytes)!==0}))).some(Boolean)&&(_.debug(`A remote asset used by "${t}" changed, rebuilding its PDF bundle`),Tr.add(t),G.delete(t),Rr(t),K(t,`stale`))}function Lr(e,t){for(let[t,n]of G)ir(n.manifest,e)&&(G.delete(t),Rr(t),K(t,`stale`))}function Rr(e){for(let t of br.keys())t.startsWith(`${e}/`)&&br.delete(t)}let q=null;function zr(e){let{documentName:t,config:n}=e;q&&clearTimeout(q),q=setTimeout(()=>{q=null,Br({documentName:t,config:n})},1e3),q.unref?.()}async function Br(e){let{documentName:t,config:n}=e;if(pn(await P().catch(()=>({}))))try{await Nr({documentName:t,config:n,background:!0})}catch(e){_.debug(`Background PDF build for "${t}" failed`,e)}}function Vr(){q&&(clearTimeout(q),q=null)}async function Hr(e){let{entryFilePath:t,config:n}=e;try{let e=await Nt({entryFilePath:t,config:n,outDir:Ot(n),sharedAssetsOutDirName:at});U.setActiveDocumentAssetSources(e)}catch(e){_.debug(`Asset source resolution skipped`,e)}}function Ur(){U.setSanitizationDiagnostics(null),U.setRemoteAssetDiagnostics(null),U.setImageFormatDiagnostics(null),U.setUnsupportedElementDiagnostics(null)}function Wr(e,t){return async(n,r,i)=>{let a=n.url?.match(/^\/api\/render\/([^\/]+)\/([^\/]+)$/);if(!a)return i();let[,o,s]=a;try{if(U.isAuthFailed())throw new A(401,N);let n=C.getConfig(),i=await pt({documentName:o,config:n}),a=await Un({entryFilePath:i,dataFilePath:ut(o,s,n),variant:s,config:n,server:e,documentName:o,renderWorker:t});if(typeof a!=`string`)throw new A(500,`Render output must be HTML.`);let c=Kn(a);me()>=ht.DEBUG&&_.debug(`Final HTML (post-sanitize)
3
- `,await pe(c.html,`html`)),U.setSanitizationDiagnostics(c?.diagnostics?{documentName:o,variant:s,...c.diagnostics,timestamp:Date.now()}:null),await Hr({entryFilePath:i,config:n});let l=ue(c.html);U.setRemoteAssetDiagnostics(l.length>0?{documentName:o,variant:s,urls:l,timestamp:Date.now()}:null);let u=Yn(le(c.html));U.setImageFormatDiagnostics(u.length>0?{documentName:o,variant:s,assets:u,timestamp:Date.now()}:null);let d=Qn(c.tree);U.setUnsupportedElementDiagnostics(d.length>0?{documentName:o,variant:s,tags:d,timestamp:Date.now()}:null),zr({documentName:o,config:n}),r.setHeader(`Content-Type`,`text/html`),r.setHeader(`Cache-Control`,`no-store, no-cache, must-revalidate, max-age=0`),r.setHeader(`Pragma`,`no-cache`),r.setHeader(`Expires`,`0`),r.end(c.html);return}catch(e){Ur(),e?.code===mt?_.error(e.message):_.error(`Render error`,e),j(r,e);return}}}function Gr(){return async(e,n,r)=>{let i=e.url?.replace(`/@studio`,``);if(!i){r();return}let a=t.join(wn,i);try{await v.access(a);let e=await v.readFile(a),r=vt(t.extname(i).toLowerCase());if(r){n.setHeader(`Content-Type`,r),zt()&&n.setHeader(`Cache-Control`,`no-store`),n.end(e);return}}catch{}r()}}function Kr(){return(e,t)=>{let n=Lt(new URL(e.url??``,un).searchParams.get(`mode`),{delivery:`url`,baseUrl:`/@studio/fonts`});t.setHeader(`Content-Type`,`text/css`),t.setHeader(`Cache-Control`,`no-store`),t.end(n)}}function qr(){return async(e,n,r)=>{let i=e.url?.split(`?`)[0];if(!i){r();return}let a;try{a=decodeURIComponent(i.replace(/^\/+/,``))}catch{r();return}let o=t.resolve(Rt,t.normalize(a)),s=t.resolve(Rt);if(!o.startsWith(s+t.sep)){n.statusCode=403,n.end(`Forbidden`);return}let c=vt(t.extname(a).toLowerCase());if(!c){r();return}try{let e=await v.readFile(o);n.setHeader(`Content-Type`,c),n.end(e);return}catch{r()}}}async function Jr(e,n){for(let r of e){let e=t.resolve(r,n),i=t.resolve(r);if(e.startsWith(i+t.sep))try{if((await v.stat(e)).isFile())return e}catch{}}return null}const Yr=new Set([`.svg`,`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.avif`,`.ico`]),Xr=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function Zr(e){return Yr.has(e)?`image`:Xr.has(e)?`font`:`other`}async function Qr(e,n){let r=[],i=async(e,a)=>{let o;try{o=await v.readdir(e,{withFileTypes:!0})}catch{return}for(let s of o){let o=a?`${a}/${s.name}`:s.name;if(s.isDirectory()){await i(t.join(e,s.name),o);continue}if(!(!s.isFile()||s.name.startsWith(`.`)))try{let i=await v.stat(t.join(e,s.name));r.push({path:o,size:i.size,type:Zr(t.extname(s.name).toLowerCase()),source:n})}catch{}}};return await i(e,``),r}function $r(){return async(e,n,r)=>{if(e.method!==`GET`)return r();let i=e.url?.match(/^\/api\/documents\/([^/]+)\/assets$/);if(!i)return r();try{if(U.isAuthFailed())throw new A(401,N);let e=decodeURIComponent(i[1]),r=C.getConfig(),a=t.resolve((0,L.getDocumentsDir)(r),e,`assets`),[o,s]=await Promise.all([Qr(a,`document`),Qr((0,L.getSharedAssetsDir)(r),`shared`)]),c=new Set(o.map(e=>e.path));O({res:n,status:200,data:{assets:[...o,...s.filter(e=>!c.has(e.path))]}})}catch(e){j(n,e)}}}function ei(e){return async(e,n,r)=>{if(e.method!==`GET`&&e.method!==`HEAD`)return r();if(U.isAuthFailed()){n.statusCode=401,n.end(N);return}let i=new URL(e.url??``,un).pathname;if(i.startsWith(`/.well-known/`)||i.startsWith(`/@fs/`)||i.startsWith(`/@id/`)||i.startsWith(`/@vite/`))return r();let a=vt(t.extname(i).toLowerCase());if(!a)return r();let o=(0,L.getSharedAssetsDir)(C.getConfig()),s=[U.getActiveDocumentAssetSources()?.documentAssetsDir,o].filter(e=>!!e),c;try{c=decodeURIComponent(i.slice(1))}catch{return r()}let l=await Jr(s,t.normalize(c));if(!l)return r();try{let e=await v.readFile(l);n.setHeader(`Content-Type`,a),n.setHeader(`Cache-Control`,`no-store`),n.setHeader(`Pragma`,`no-cache`),n.setHeader(`Expires`,`0`),n.end(e);return}catch{return r()}}}function ti(e){return e?.code===`EEXIST`}async function ni(e){try{let{mtimeMs:t}=await Oe(e);return Date.now()-t>12e4}catch{return!0}}async function ri(e,t){let n=`${e}.lock`,i=Date.now()+1e4;for(await y(r(n),{recursive:!0,mode:448});;)try{await(await we(n,`wx`,384)).close();break}catch(e){if(!ti(e))throw e;if(await ni(n)){await De(n,{force:!0});continue}if(Date.now()>i)throw new E(`Another Studio process is holding ${n}. Try again in a moment.`);await Ht(50)}try{return await t()}finally{await De(n,{force:!0})}}async function ii(e,t){let n=`${e}.${Ft(6).toString(`hex`)}.tmp`;await y(r(e),{recursive:!0,mode:448}),await x(n,t,{mode:384}),await Ce(n,384),await Ee(n,e)}async function ai(e){let t=kn();await ri(t,async()=>{let n=await J(),r=t=>t.org.id===e.org.id,i=n.some(r)?n.map(t=>r(t)?e:t):[...n,e];await ii(t,JSON.stringify(i,null,2))})}async function J(){return await ge(kn())||(_.debug(`Credentials file not found or empty`),[])}async function oi(e){return e&&(await J()).find(t=>t.org.id===e)||null}const si=[`format_engine.js`,`format_engine_bg.wasm`],ci=`.engine-digest`,li=/^[0-9a-f]{64}$/;function ui(e){return si.every(t=>u(a(V,e,t)))}function di(e){let t=a(V,e,ci);if(!u(t))return null;try{let e=d(t,`utf8`).trim();return li.test(e)?e:null}catch{return null}}function fi(e,t){ee(a(e,ci),`${t}\n`)}function pi(e,t){return ui(e)?di(e)===t:!1}const mi=/^[0-9a-f]{64}$/;function hi(e){let t;try{t=new URL(e).hostname}catch{return!1}return t===`localhost`||t===`::1`||t===`[::1]`||/^127(?:\.\d{1,3}){3}$/.test(t)}function gi(e,t){return e?t==null?hi(e)?{ok:!0,digest:null}:{ok:!1,reason:`no expected SHA-256 was supplied for a remote engine`}:mi.test(t)?{ok:!0,digest:t}:{ok:!1,reason:`'${t}' is not a SHA-256`}:{ok:!1,reason:`the credentials name no engine URL`}}function _i(e,t){let n=gi(e,t);if(!n.ok)throw new E(`Engine download refused: ${n.reason}. Reconnect Studio to obtain a usable one.`);return n.digest}async function Y(){let e=await ge(An());return _.debug(`State loaded`,{hasState:!!e,currentOrgId:e?.currentOrgId}),e||{}}async function vi(e){await y(On(),{recursive:!0}),await x(An(),JSON.stringify(e,null,2))}async function yi(e){let t=await Y();t.currentOrgId=e,await vi(t)}const bi=2,xi=e=>Ft(e).toString(`base64url`);function Si(e){return w(`sha256`).update(e).digest(`base64url`)}function Ci(){return xi(16)}function wi(e){let{mode:t,port:n,state:r}=e,i=xi(32),a=t===`local`;return{attemptId:xi(16),mode:t,codeVerifier:i,codeChallenge:Si(i),port:a?n:void 0,state:a?r:void 0}}function Ti(){return Re.platform()===`darwin`?Re.hostname().replace(/\.local$/,``):Re.hostname()}function Ei(e){let{dashboardUrl:t,attempt:n,deviceName:r,linkedOrganizationIds:i=[]}=e,a=new URL(`/studio/link`,t);return a.searchParams.set(`v`,`2`),a.searchParams.set(`mode`,n.mode),a.searchParams.set(`attempt`,n.attemptId),a.searchParams.set(`challenge`,n.codeChallenge),a.searchParams.set(`device`,r),n.port!==void 0&&n.state&&(a.searchParams.set(`port`,String(n.port)),a.searchParams.set(`state`,n.state)),i.length>0&&a.searchParams.set(`linked`,i.join(`,`)),a.href}function X(e){return`${Di(process.env.npm_config_user_agent)}format ${e}`}function Di(e=``){return e.startsWith(`pnpm/`)?`pnpm exec `:e.startsWith(`yarn/`)?`yarn `:e.startsWith(`bun/`)?`bunx `:e.startsWith(`npm/`)?`npx `:``}const Oi=/^[A-Za-z0-9_-]{22}$/;var ki=class extends E{constructor(){super(`That code is not valid. Check you copied all of it, or start again.`),this.name=`InvalidSignInCodeError`}},Ai=class extends E{constructor(){super(`Format no longer accepts connections from this version of Studio. Run \`${X(`update latest`)}\`, then connect again.`),this.name=`UnsupportedSignInProtocolError`}},ji=class extends E{constructor(){super(`That account can no longer connect Studio to the organization it chose.`),this.name=`SignInRefusedError`}};async function Mi(e){let{apiUrl:t,attempt:n,requestedEngine:r,signal:i}=e,a=e.code.trim();if(!Oi.test(a))throw new ki;let{data:o,error:s,status:c}=await Vt(`${t}/studio/link/exchange`,{method:`POST`,body:{protocol:2,code:a,codeVerifier:n.codeVerifier,attemptId:n.attemptId,mode:n.mode,port:n.port,requestedEngine:r},signal:i});if(c===200&&o)return o;throw s===`invalid_grant`?new ki:s===`unsupported_protocol`?new Ai:c===403?new ji:c===null||c>=500||s===`server_error`?new D(`Format did not confirm the connection, so the code may or may not have been used.`):new E(`Connection failed: ${s}`)}async function Ni(e){let{apiUrl:t,refreshToken:n}=e;await Vt(`${t}/studio/session/revoke`,{method:`POST`,body:{refreshToken:n},signal:AbortSignal.timeout(1e4)})}function Pi(e){let t=new URL(e);return t.searchParams.set(`connected`,`1`),t.toString()}const Fi=`window.close()`,Ii=`'sha256-${w(`sha256`).update(Fi).digest(`base64`)}'`,Li=`/fonts/mona-sans.woff2`,Ri=a(wn,`fonts/mona-sans/mona-sans.woff2`),zi={success:`#2f9e5e`,error:`#d0472b`,warning:`#e8833f`,progress:`#0e85ff`};function Bi(){try{return d(a(wn,`format-logo.svg`),`utf8`)}catch{return`<strong>Format</strong>`}}function Vi(e){return e.replace(/[&<>"']/g,e=>`&#${e.charCodeAt(0)};`)}const Hi=`
4
- @font-face { font-family: 'Format Studio UI'; font-weight: 100 900; font-display: swap; src: url('${Li}') format('woff2') }
5
- :root { color-scheme: light dark; --gray-100: #f8f8f8; --gray-200: #f2f2f2; --gray-800: #434343; --gray-900: #222222; --island: #ffffff; --island-border: #e7e7e7; --muted: #757575; --fs-color-logo: #1e1e1e }
6
- @media (prefers-color-scheme: dark) { :root { --gray-100: #181818; --gray-200: #303030; --gray-800: #d4d4d4; --gray-900: #f2f2f2; --island: #0d0d0d; --island-border: #424242; --muted: #a3a3a3; --fs-color-logo: #f2f2f2 } }
7
- * { box-sizing: border-box }
8
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; background: var(--gray-100); color: var(--gray-900); font: 500 15px/1.5 'Format Studio UI', system-ui, sans-serif; letter-spacing: -0.1px; -webkit-font-smoothing: antialiased }
9
- .dialog { width: min(100%, 420px); background: var(--island); border: 1px solid var(--island-border); border-radius: 16px; box-shadow: 0 24px 80px rgb(0 0 0 / 12%); overflow: hidden }
10
- header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 20px 20px 0 }
11
- header svg { display: block; height: 15px; width: auto }
12
- .content { display: flex; flex-direction: column; gap: 15px; padding: 20px }
13
- h1 { margin: 0; font-size: 20px; font-weight: 650; letter-spacing: -0.4px; line-height: 1.2 }
14
- p { margin: 0; color: var(--gray-800); overflow-wrap: anywhere }
15
- .status { display: inline-flex; align-items: center; gap: 8px; padding: 2px 10px 2px 8px; border-radius: 9999px; background: var(--gray-200); font-size: 13px }
16
- .status::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: var(--tone) }
17
- footer { padding: 12px 20px; border-top: 1px solid var(--island-border); background: color-mix(in srgb, var(--gray-900) 3%, transparent); font-size: 13px; color: var(--muted) }
18
- `;let Ui=null;function Wi(e){let{title:t,body:n,tone:r,status:i,closeTab:a=!1}=e,o=a?`<script>${Fi}<\/script>`:``;return Ui??(Ui=Bi()),`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${Vi(t)}</title><style>${Hi}</style></head><body><main class="dialog" style="--tone: ${zi[r]}"><header aria-label="Format Studio">${Ui}<span class="status">${Vi(i)}</span></header><div class="content"><h1>${Vi(t)}</h1><p>${Vi(n)}</p></div><footer>You can close this tab.</footer></main>${o}</body></html>`}var Gi=class extends E{constructor(e=`The request was closed without connecting an organization.`){super(e),this.name=`LinkCancelledError`}},Ki=class extends Gi{constructor(){super(`You've already connected all your organizations.`),this.name=`NothingToLinkError`}};const qi=`/done`,Ji={"content-type":`text/html; charset=utf-8`,"cache-control":`no-store`,"referrer-policy":`no-referrer`,"x-content-type-options":`nosniff`,"content-security-policy":`default-src 'none'; style-src 'unsafe-inline'; font-src 'self'`};async function Yi(e){if(!e)return null;let t,n=new Promise(e=>{t=setTimeout(()=>e(null),12e4).unref()});try{return await Promise.race([e.catch(()=>null),n])}finally{clearTimeout(t)}}function Xi(e,t,n){let r=n.closeTab?{...Ji,"content-security-policy":`${Ji[`content-security-policy`]}; script-src ${Ii}`}:Ji;e.writeHead(t,r),e.end(Wi(n))}function Zi(e){return e.kind===`signed-in`?{title:`Studio connected`,body:`Go back to your terminal or Studio to carry on.`,tone:`success`,status:`Connected`}:{title:`Connection did not finish`,body:e.message,tone:`error`,status:`Not connected`}}async function Qi(e){let t=await b(Ri).catch(()=>null);if(!t){e.writeHead(404).end();return}e.writeHead(200,{"content-type":`font/woff2`,"cache-control":`no-store`,"x-content-type-options":`nosniff`}),e.end(t)}async function $i(e){let{state:t,signal:n}=e,r=null,i=!1,a=()=>{},o=()=>{},s=()=>{},c=new Promise(e=>{s=e}),l=new Promise((e,t)=>{a=e,o=t});l.catch(()=>{});let u=Ut((e,n)=>{let l=new URL(e.url??`/`,`http://127.0.0.1`);if(e.method!==`GET`){n.writeHead(405).end();return}if(l.pathname===Li){Qi(n);return}if(l.pathname===qi&&r){Xi(n,200,Zi(r)),s(),setTimeout(d,1e3).unref();return}if(l.pathname!==`/callback`){n.writeHead(404).end();return}let u=l.searchParams.get(`code`),f=l.searchParams.get(`state`)===t;if(f&&!u&&l.searchParams.get(`outcome`)===`all-linked`&&!i){Xi(n,200,{title:`Nothing to connect`,body:`You've already connected all your organizations.`,tone:`progress`,status:`Already connected`,closeTab:!0}),o(new Ki),setTimeout(d,1e3).unref();return}if(!(f&&u)){Xi(n,400,{title:`This request does not match`,body:`This page came from a different request. Go back to your terminal and use the link it printed.`,tone:`warning`,status:`Wrong request`});return}if(i){Xi(n,409,{title:`Already connecting`,body:`Go back to your terminal to see how it went.`,tone:`progress`,status:`In progress`});return}i=!0,a({code:u,finish:async e=>{let t=e.kind===`signed-in`?await Yi(e.returnTo):null;if(t)return n.writeHead(303,{...Ji,location:Pi(t)}),n.end(),setTimeout(d,1e3).unref(),!0;r=e,n.writeHead(303,{...Ji,location:qi}),n.end(),setTimeout(d,1e4).unref();let i=new Promise(e=>setTimeout(e,5e3).unref());return await Promise.race([c,i]),!1}})});function d(){s(),n.removeEventListener(`abort`,f),u.close(),u.closeAllConnections()}function f(){o(n.reason),d()}await new Promise((e,t)=>{u.once(`error`,t),u.listen(0,`127.0.0.1`,()=>e())});let{port:p}=u.address();return n.addEventListener(`abort`,f,{once:!0}),n.aborted&&f(),{port:p,received:l,close:d}}function ea(e){"@babel/helpers - typeof";return ea=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},ea(e)}function ta(e,t){if(ea(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(ea(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function na(e){var t=ta(e,`string`);return ea(t)==`symbol`?t:t+``}function ra(e,t,n){return(t=na(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const ia=()=>X(`auth start`),aa=()=>`If your browser can't reach Studio, cancel this request and run \`${ia()}\` to connect with a code.`,oa={ci:`This job needs Studio credentials.`,ssh:`Studio is running over SSH.`,container:`Studio is running in a container.`};var sa=class extends E{constructor(e,t){let n=e===`ci`?`Connect Studio outside CI, then provide the saved credentials to this job.`:`Run \`${ia()}\` to connect with a one-time code. If your browser can reach this machine, run \`${X(`dev --auth-mode local`)}\` instead.`;super(`Studio isn't connected (AUTH_REQUIRED). ${oa[e]} ${n} Read more: ${t}/docs/studio/authentication#on-a-remote-machine`),ra(this,`code`,`AUTH_REQUIRED`),this.name=`AuthRequiredError`}};function ca(e){console.log([``,` ${be.styleText(`bold`,`Connect Studio`)}`,``,` Open the link to choose an organization and approve the connection.`,``,` ${be.styleText(`cyan`,e)}`,``,` ${aa()}`,``].join(`
19
- `))}const la=[`/.dockerenv`,`/run/.containerenv`],ua=[`KUBERNETES_SERVICE_HOST`,`CODESPACES`,`REMOTE_CONTAINERS`,`GITPOD_WORKSPACE_ID`],da=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function fa(e){return e!==void 0&&e!==``&&e!==`0`&&e.toLowerCase()!==`false`}function pa(e){let{env:t,authMode:n,fileExists:r=u}=e;return n===`local`?{kind:`local`}:fa(t.CI)?{kind:`auth-required`,reason:`ci`}:da.some(e=>fa(t[e]))?{kind:`auth-required`,reason:`ssh`}:fa(t.container)||ua.some(e=>fa(t[e]))||la.some(e=>r(e))?{kind:`auth-required`,reason:`container`}:{kind:`local`}}function ma(){let{dashboardUrl:e,dashboardApiUrl:t}=I();return{dashboardUrl:e,refreshUrl:`${t}/studio/refresh`}}let ha=!1;function ga(){ha=!1}function _a(){return ha?!1:(ha=!0,!0)}function va(e){return be.inspect(e,{depth:null,colors:!0})}function ya(e){if(!e||typeof e!=`object`)return!1;let t=e;return!(typeof t.id!=`string`||typeof t.name!=`string`||`logo`in t&&t.logo!==void 0&&typeof t.logo!=`string`||typeof t.isPersonal!=`boolean`)}function ba(e){if(!e||typeof e!=`object`)return!1;let t=e;return!(typeof t.sub!=`string`||typeof t.name!=`string`||typeof t.sid!=`string`||typeof t.engine!=`string`||typeof t.plan!=`string`||typeof t.pageLimit!=`number`||`email`in t&&typeof t.email!=`string`||!ya(t.org))}function Z(e){try{let t=e.split(`.`);if(t.length!==3)throw new E(`Invalid JWT format`);let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=Buffer.from(n,`base64`).toString(`utf-8`),i=JSON.parse(r);if(!ba(i))throw new E(`Invalid JWT payload`);return i}catch(e){return _.warn(`Failed to decode JWT payload:`,va(e)),null}}const xa=`The link expired. Start again to get a new link.`;let Sa;function Ca(e){Sa=e}function wa(){let e=pa({env:process.env,authMode:Sa});if(e.kind===`auth-required`)throw new sa(e.reason,I().webUrl)}function Ta(e,t){t.open&&ie(e)}function Ea(){let e=()=>{},t=()=>{},n=!1;return{studioUrl:new Promise(t=>{e=t}),browserSent:new Promise(e=>{t=e}),expectBrowser:e=>{n=!0,e.then(t,()=>t(!1))},studioListening:r=>{e(r),n||t(!1)}}}async function Da(e){let{attempt:t,code:n,requestedEngine:r,signal:i}=e,{dashboardApiUrl:a}=I(),o=await Mi({apiUrl:a,attempt:t,code:n,requestedEngine:r,signal:i}).catch(e=>{throw i.aborted?new Gi:e});if(i.aborted)throw await Ni({apiUrl:a,refreshToken:o.refreshToken}),new Gi;try{return await ja({authResult:o,requestedEngine:r})}catch(e){throw await Ni({apiUrl:a,refreshToken:o.refreshToken}),e}}function Oa(e){return e instanceof Error?e.message:`Connection failed.`}async function ka(e,t){wa();let n=AbortSignal.timeout(9e5),r=t?.signal?AbortSignal.any([t.signal,n]):n,i=Ci(),a=await $i({state:i,signal:r}),o=wi({mode:`local`,port:a.port,state:i}),s=Ei({dashboardUrl:I().dashboardUrl,attempt:o,deviceName:Ti(),linkedOrganizationIds:t?.linkedOrganizationIds});r.aborted||ca(s);let c=()=>{},l=new Promise(e=>{c=e});return{loginUrl:s,waitForLogin:(async()=>{let i=await a.received.catch(e=>{throw a.close(),c(!1),e instanceof Ki?e:n.aborted?new E(`${xa} ${aa()}`):new Gi});try{let n=await Da({attempt:o,code:i.code,requestedEngine:e,signal:r}),a=i.finish({kind:`signed-in`,returnTo:t?.returnTo});return a.then(c,()=>c(!1)),t?.returnTo||await a,zt()&&_.debug(`Login success`,{org:n.org.id,engine:n.engine}),n}catch(e){throw c(!1),await i.finish({kind:`failed`,message:Oa(e)}),e}})(),browserSentOn:l}}function Aa(e){let{accessToken:t,requestedEngine:n,expectedOrgId:r}=e,i=Z(t);if(!i)throw new E(`Failed to decode access token`);let{engine:a,org:o}=i,s=i.exp;if(typeof s==`number`){let e=Math.floor(Date.now()/1e3);if(s<e)throw new E(`Access token is already expired (expired ${e-s}s ago, exp=${s}, now=${e})`)}if(a!==n&&!a.startsWith(`${n}-edge.`))throw new E(`Engine version mismatch (requested: ${n}, resolved: ${a})`);if(r&&o.id!==r)throw new E(`Organization ID mismatch`);return{engine:a,org:o}}async function ja(e){let{authResult:t,requestedEngine:n,expectedOrgId:r,signInAttemptId:i}=e,{accessToken:a,engineUrl:o,engineDigest:s}=t,{engine:c,org:l}=Aa({accessToken:a,requestedEngine:n,expectedOrgId:r});return await ai({org:l,...t,...i&&{signInAttemptId:i}}),{org:l,accessToken:a,engineUrl:o,engineDigest:s,engine:c}}async function Ma(e,t){let n=await oi(e);if(!n||!n.refreshToken)throw Error(`No refresh token found for org`);let r=await Ia({refreshToken:n.refreshToken,requestedEngine:t,orgId:e});return U.setToken(r.accessToken),{accessToken:r.accessToken,engineUrl:r.engineUrl,engineDigest:r.engineDigest}}async function Na(){let e=Z(U.getToken());if(!e)throw new E(`Failed to decode current token`);let{accessToken:t}=await Ma(e.org.id,U.getEngineRequested());return t}function Pa({server:e}){let t=setInterval(async()=>{try{zt()&&_.debug(`Refreshing engine licence`);let t=Z(U.getToken());if(!t)throw Error(`Failed to decode current token`);let n=t.org.id,{accessToken:r}=await Ma(n,U.getEngineRequested()),i=U.isAuthFailed();U.clearAuthFailed(),zt()&&_.debug(`Engine licence refreshed`),e.ws.send({type:`custom`,event:`token-refreshed`,data:r}),i&&e.ws.send({type:`custom`,event:`auth-restored`}),ga()}catch(t){_.error(`Failed to refresh licence:`,va(t)),_a()&&(U.setAuthFailed(),e.ws.send({type:`custom`,event:`token-refresh-failed`,data:{message:N,details:[{message:`Token refresh failed`,error:va(t)}]}}))}},3e3*1e3);return t.unref(),()=>clearInterval(t)}function Fa(e){let{status:t,message:n}=e;return t===null||t>=500?new D(n??`Format servers are unreachable`):new cn(n??`Refresh token rejected`)}async function Ia(e){let{refreshToken:t,requestedEngine:n,orgId:r}=e;_.debug(`Refreshing credentials from stored refresh token`);let{data:i,error:a,status:o}=await Vt(ma().refreshUrl,{method:`POST`,body:{refreshToken:t,requestedEngine:n}});if(a||!i)throw _.debug(`Token refresh failed`),Fa({status:o,message:a});return _.debug(`Refresh result: success`),await ja({authResult:i,requestedEngine:n,expectedOrgId:r})}async function La(e,t,n){let{loginUrl:r,waitForLogin:i,browserSentOn:a}=await ka(e,{returnTo:n?.studioUrl});n?.expectBrowser(a),Ta(r,t);let o=await i;return await yi(o.org.id),o}function Ra(e){let t=Z(e);if(!t)return!1;let n=t.exp;return typeof n==`number`?n>Math.floor(Date.now()/1e3)+60:!1}function za(e,t){if(!Ra(e.accessToken))return null;let n=Z(e.accessToken);if(!n||!(n.engine===t||n.engine.startsWith(`${t}-edge.`)))return null;let r=gi(e.engineUrl,e.engineDigest);return!r.ok||!pi(n.engine,r.digest)?null:{org:e.org,accessToken:e.accessToken,engineUrl:e.engineUrl,engineDigest:e.engineDigest,engine:n.engine}}async function Ba(e,t,n){let{currentOrgId:r}=await Y(),i=await oi(r);if(!r||!i?.refreshToken)return await La(e,t,n);let a=za(i,e);if(a)return _.debug(`Access token still valid and engine present — skipping refresh`),a;try{return await Ia({requestedEngine:e,refreshToken:i.refreshToken,orgId:r})}catch(i){if(_.debug(`Authentication error details for org ${r}:`,va(i)),i instanceof D)throw i;return _.info(`Your last Studio session has ended. Reconnect to continue.`),await La(e,t,n)}}function Va(e){let{dashboardUrl:t}=I(),n=Ha();return n?`${t}/studio/open?${new URLSearchParams({organizationId:n,to:e}).toString()}`:t}function Ha(){try{return Z(U.getToken())?.org.id??null}catch{return null}}function Ua(e){let{stampEngineVersion:t}=I();return t?(Gt.debug(`Stamping data-engine="${t}" for local engine`),Bt(e,t)):e}const Wa={MISSING_API_KEY:"No Format API key found. Add `FORMAT_API_KEY` to your `.env` file or environment variables.",INVALID_API_KEY:"Your Format API key is invalid or revoked. Check `FORMAT_API_KEY` in your `.env` file or environment variables.",VERIFY_SERVICE_ERROR:`Could not verify your API key right now — the verification service is temporarily unavailable. Try again shortly.`},Ga=new Set([`MISSING_API_KEY`,`INVALID_API_KEY`]);function Ka(){return Va(`api-keys`)}function qa(e){let t=e?.detail;if(!t||typeof t!=`object`)return null;let n=t;return!n.error||typeof n.error!=`object`?null:{code:n.error.code,message:n.error.message}}function Ja(e){let t=qa(e),n=t?.code?Ga.has(t.code):!1,r=t?.code?Wa[t.code]:void 0;if(n)return`${r??t?.message??Wa.INVALID_API_KEY}\n\nYou can generate a new API key [here](${Ka()}).`;if(r)return r;if(t?.message)return t.message;let i=e?.message;return typeof i==`string`&&i?i:`Something went wrong generating the PDF. Check the server logs.`}function Ya(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Xa(e){let t=Ya(e,`missing`),n=Ya(e,`brokenRemote`),r=[...t,...n];if(r.length===0)return Ja(e);let i=r.map(e=>`- \`${e}\``).join(`
20
- `),a=[];return t.length>0&&a.push("Add the missing files to your `sharedAssetsDir` or the document's assets folder."),n.length>0&&a.push(`Make sure any remote assets are reachable when generating the PDF.`),`Couldn't generate PDF due to the following assets being missing:\n\n${i}\n\n${a.join(` `)}`}function Za(e){return async(t,n,r)=>{let i=t.url?.match(/^\/api\/download\/([^\/]+)\/([^\/]+)$/);if(!i)return r();if(U.isAuthFailed())return j(n,new A(401,N));let[,a,o]=i,s=t.url??`/api/download/${a}/${o}`,c=t=>{M(e,{path:s,...t})};if(!process.env.FORMAT_API_KEY?.trim())return c({title:`PDF downloads require an API key`,message:`Create an API key [here](${Ka()}) then add as \`FORMAT_API_KEY\` to your \`.env\` file. No restart needed.`}),j(n,new A(400,`Missing API key`));let l=async e=>{let t=e.getReader(),n=[],r=0;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;i&&(n.push(i),r+=i.length)}}finally{t.releaseLock()}let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.length;return i};try{let{config:e}=await g();if(!e)throw new E(`Could not find Format config file`);let t=I().apiUrl,r=new Wt({baseUrl:t}),{bytes:i,cached:s}=await Fr({documentName:a,variant:o,config:e,stampHtml:Ua,cachePdf:!I().stampEngineVersion,generatePdf:async e=>{Gt.debug(`Sending PDF request to API with HTML`,e.html);let t=await r.pdf(e.html,e.assets?{assets:e.assets}:void 0);if(!t.isPdf)throw new A(500,`Failed to generate PDF`);if(!t.body)throw new A(500,`No PDF content received`);return l(t.body)}}),c=`${a}-${o}.pdf`;n.statusCode=200,n.setHeader(`Content-Type`,`application/pdf`),n.setHeader(`Content-Disposition`,`attachment; filename="${c}"`),n.setHeader(`Cache-Control`,`no-store, no-cache, must-revalidate, max-age=0`),n.setHeader(`Pragma`,`no-cache`),n.setHeader(`Expires`,`0`),n.setHeader(`Content-Length`,i.length.toString()),n.setHeader(`x-format-studio-cache`,s?`hit`:`miss`),n.end(Buffer.from(i));return}catch(e){console.error(`Download error:`,e),c({title:`PDF generation error`,message:Xa(e)}),n.headersSent?n.end():j(n,e)}}}function Qa(){return async(e,t)=>{try{O({res:t,status:200,data:U.getDiagnostics()})}catch(e){j(t,e)}}}function $a(e,n,r){let i=t.join(e,`app`,`manifest.json`);if(!u(i))throw new E(`Manifest file not found`);try{let a=JSON.parse(d(i,`utf-8`))[r];if(!a)throw new E(`Entry '${r}' not found in manifest`);return t.join(e,n,a)}catch(e){Gt.warn(`Failed to read manifest file:`,e)}}var eo=`if (import.meta.hot) {
21
- let hasReportedDisconnect = false
22
-
23
- const removeEnginePages = () => {
24
- const existing = document.querySelector('#format-pages')
25
- existing && existing.remove()
26
- }
27
-
28
- const reportAuthFailure = async () => {
29
- try {
30
- await fetch('/api/auth/failed', {
31
- method: 'POST',
32
- headers: {
33
- 'Content-Type': 'application/json'
34
- },
35
- body: JSON.stringify({ reason: 'set_licence_failed' })
36
- })
37
- } catch {
38
- // Best-effort only.
39
- }
40
- }
41
-
42
- const markAuthFailed = (notifyServer = false) => {
43
- removeEnginePages()
44
-
45
- if (window.engine) {
46
- window.engine = null
47
- }
48
-
49
- if (notifyServer) {
50
- reportAuthFailure()
51
- }
52
- }
53
-
54
- const emitAuthError = () => {
55
- window.dispatchEvent(
56
- new CustomEvent('studio:error', {
57
- detail: {
58
- data: {
59
- kind: 'auth',
60
- message: 'Your Studio session has expired. Reconnect to continue.',
61
- title: 'Authentication error',
62
- link: {
63
- href: '/api/auth/login',
64
- label: 'Reconnect Studio'
65
- }
66
- }
67
- }
68
- })
69
- )
70
- }
71
-
72
- import.meta.hot.on('studio-server-error', data => {
73
- const title = data.title || 'Server error'
74
-
75
- window.dispatchEvent(
76
- new CustomEvent('studio:error', {
77
- detail: { data: { ...data, title } }
78
- })
79
- )
80
- })
81
-
82
- import.meta.hot.on('vite:ws:connect', async () => {
83
- if (!window.engine) {
84
- return
85
- }
86
-
87
- try {
88
- const res = await fetch('/api/engine-token')
89
- const { token } = await res.json()
90
-
91
- if (token) {
92
- window.engine.set_licence(token)
93
- console.log('[format] Token refreshed on WebSocket reconnect')
94
- }
95
- } catch {
96
- // Best-effort — the next scheduled refresh will retry.
97
- }
98
- })
99
-
100
- import.meta.hot.on('vite:ws:disconnect', () => {
101
- if (hasReportedDisconnect) {
102
- return
103
- }
104
-
105
- hasReportedDisconnect = true
106
-
107
- window.dispatchEvent(
108
- new CustomEvent('studio:error', {
109
- detail: {
110
- data: {
111
- kind: 'server-disconnected',
112
- message: 'Format Studio server not connected. Close this tab and restart the server.',
113
- title: 'Server not connected'
114
- }
115
- }
116
- })
117
- )
118
- })
119
-
120
- // A page restored from the back/forward cache comes back with a closed
121
- // socket and the disconnect error above already on screen. Its state is
122
- // stale either way, so it starts again from the server.
123
- window.addEventListener('pageshow', event => {
124
- if (event.persisted) {
125
- window.location.reload()
126
- }
127
- })
128
-
129
- import.meta.hot.on('hmr', data => {
130
- window.dispatchEvent(new CustomEvent('studio:hmr', { detail: data }))
131
- })
132
-
133
- import.meta.hot.on('pdf-build-status', data => {
134
- window.dispatchEvent(new CustomEvent('studio:pdf-build-status', { detail: data }))
135
- })
136
-
137
- import.meta.hot.on('documents-changed', () => {
138
- window.dispatchEvent(new CustomEvent('studio:documents-changed'))
139
- })
140
-
141
- import.meta.hot.on('token-refresh-failed', data => {
142
- markAuthFailed()
143
- emitAuthError()
144
- })
145
-
146
- import.meta.hot.on('auth-restored', () => {
147
- window.dispatchEvent(new CustomEvent('studio:auth-restored', { detail: { restartEngine: true } }))
148
- })
149
-
150
- import.meta.hot.on('org-linked', data => {
151
- window.dispatchEvent(new CustomEvent('studio:org-linked', { detail: data }))
152
- })
153
-
154
- import.meta.hot.on('org-link-failed', data => {
155
- window.dispatchEvent(new CustomEvent('studio:org-link-failed', { detail: data }))
156
- })
157
-
158
- // The dashboard closed the request because every organisation is already
159
- // connected. Nothing failed, so the app stops waiting without reporting anything.
160
- import.meta.hot.on('org-link-cancelled', data => {
161
- window.dispatchEvent(new CustomEvent('studio:org-link-cancelled', { detail: data }))
162
- })
163
-
164
- import.meta.hot.on('token-refreshed', jwt => {
165
- // Reload organisation metadata even if the engine has not loaded.
166
- window.dispatchEvent(new CustomEvent('studio:token-refreshed'))
167
-
168
- if (!window.engine) {
169
- return
170
- }
171
-
172
- try {
173
- window.engine.set_licence(jwt)
174
- } catch (error) {
175
- console.error('Failed to set licence', error)
176
- markAuthFailed(true)
177
- emitAuthError()
178
- }
179
- })
180
- }
181
- `;function to(){try{let e=$a(R,`app`,`index.css`);if(e&&u(a(R,`public`,n(e))))return`/@studio/${n(e)}`}catch{}return`/@studio/index.css`}function no(e){return`
182
- <!DOCTYPE html>
183
- <html lang="en" class="html is-loading">
184
- <head>
185
- <meta charset="utf-8" />
186
- <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no" />
187
- <title>Format Studio</title>
188
- <base href="${un}:${e}/" />
189
- <link rel="stylesheet" href="${to()}" />
190
- <link rel="icon" type="image/png" href="/@studio/favicon-96x96.png" sizes="96x96" />
191
- <link rel="icon" type="image/svg+xml" href="/@studio/favicon.svg" />
192
- <link rel="shortcut icon" href="/@studio/favicon.ico" />
193
- <link rel="apple-touch-icon" sizes="180x180" href="/@studio/apple-touch-icon.png" />
194
- <meta name="apple-mobile-web-app-title" content="Format Studio" />
195
- <link rel="manifest" href="/@studio/site.webmanifest" />
196
- </head>
197
- <body class="body">
198
- <div id="loader">
199
- <div class="spinner"></div>
200
- </div>
201
- <div id="studio-ui" class="studio-ui"></div>
202
- <div id="user-root" inert></div>
203
-
204
- <script type="module" src="${Tn}"><\/script>
205
- <script type="module">${eo}<\/script>
206
- </body>
207
- </html>
208
- `}function ro(e){return async(t,n,r,i)=>{if(!(t.url===`/`||t.url?.match(/^\/[^/.]+$/)))return r();let a=no(e),o=await i.transformIndexHtml(`/@studio`,a);n.setHeader(`Content-Type`,`text/html`),n.end(o)}}const io=[...new Set([...Object.values(et).flat(),...Object.values($e)])];async function ao(){try{let e=await Ne(S());return io.filter(t=>e.has(t))}catch{return[]}}function oo(){return async(e,t)=>{try{let e=U.getEngineResolved();O({res:t,status:200,data:{...await Y(),engineVersion:e,enginePath:Mn(e),framework:C.getConfig().framework,projectName:n(S()),webUrl:I().webUrl,installedDependencies:await ao()}})}catch(e){j(t,e)}}}function so(){return async(e,t,n)=>{if(e.method===`GET`){try{O({res:t,status:200,data:await P()})}catch(e){j(t,e)}return}if(e.method===`PUT`||e.method===`PATCH`){try{let n=await k(e),r={...await P(),...n};await gn(r),O({res:t,status:200,data:r})}catch(e){j(t,e)}return}n?n():O({res:t,status:405,data:{error:`Method not allowed`}})}}function co(){return{platform:T.platform(),arch:T.arch(),release:T.release(),type:T.type(),hostname:T.hostname(),userInfo:{username:T.userInfo().username,homedir:T.userInfo().homedir}}}function lo(){return async(e,t)=>{try{O({res:t,status:200,data:{os:co()}})}catch(e){j(t,e)}}}function uo(){return async(e,t)=>{O({res:t,status:200,data:{token:U.getToken()}})}}function fo(){return(e,t,n)=>{if(e.url!==`/health`)return n();t.statusCode=200,t.end(`ok`)}}function po(){return async(e,t)=>{try{O({res:t,status:200,data:(await J()).map(e=>({...e.org,email:Z(e.accessToken)?.email}))})}catch(e){j(t,e)}}}async function mo(e,t,n){let r=s(V,t),i=_i(e,n);if(_.debug(`Engine directory: ${V}`),_.debug(`Engine version directory: ${r}`),i!==null&&pi(t,i))return _.debug(`Engine already downloaded`),r;_.debug(`Downloading engine`);let{data:o,error:c}=await Vt(e,{responseType:`arrayBuffer`});if(c)throw _.error(`Failed to download engine. Are you connected to the internet?`),new E(`Engine download error: ${c}`);if(!o)throw new E(`Engine download error: No data returned`);let l=Buffer.from(o);if(i!==null){let e=w(`sha256`).update(l).digest(`hex`);if(e!==i)throw new E(`Engine ${t} failed verification: expected SHA-256 ${i}, downloaded bytes hash to ${e}. Nothing was installed.`)}let u=s(V,`.tmp-${t}-${process.pid}-${Date.now()}`);m(u,{recursive:!0,force:!0});try{new Kt(l).extractAllTo(u,!0),ho(u);let e=f(u,{withFileTypes:!0}).filter(e=>e.isDirectory());if(e.length!==1)throw new E(`Unexpected engine archive layout: ${e.length} top-level directories`);i!==null&&fi(a(u,e[0].name),i),m(r,{recursive:!0,force:!0}),p(a(u,e[0].name),r)}finally{m(u,{recursive:!0,force:!0})}for(let e of f(V,{withFileTypes:!0}))e.isDirectory()&&e.name!==t&&!e.name.startsWith(`.`)&&m(a(V,e.name),{recursive:!0,force:!0});return r}function ho(e){for(let t of f(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let n=a(e,t.name);if(t.name===`__MACOSX`){m(n,{recursive:!0,force:!0});continue}ho(n)}}var go=class extends E{constructor(e,t){super(t),this.problem=e,this.name=`ConnectionPreparationError`}};async function _o(e,t,n){let r,i;try{let a=Aa({accessToken:e.accessToken,requestedEngine:t,expectedOrgId:n});r=a.engine,i=a.org}catch(e){throw new go(`mismatch`,`Format returned credentials that do not match: ${String(e)}`)}if(e.engineUrl)try{await mo(e.engineUrl,r,e.engineDigest)}catch(e){throw new go(`engine`,`The engine could not be downloaded: ${String(e)}`)}return{org:i,accessToken:e.accessToken,requestedEngine:t,engine:r}}async function vo(e){await yi(e.org.id),U.setToken(e.accessToken),U.setEngineVersions({requested:e.requestedEngine,resolved:e.engine})}const yo=`Reconnect Studio to this organization. If your access has changed, contact an organization admin.`;function bo(){return async(e,t)=>{try{let{orgId:n}=await k(e);if(!n)throw new A(400,`Select an organization to continue.`);let r=await oi(n);if(!r?.refreshToken)throw new A(404,yo);let i=U.getEngineRequested(),a;try{a=await Ia({refreshToken:r.refreshToken,requestedEngine:i,orgId:n})}catch(e){throw e instanceof D?new A(503,`Studio couldn't connect to Format. Check your connection and try again.`):new A(401,yo)}let o;try{o=await _o(a,i,n)}catch(e){throw new A(502,e instanceof go&&e.problem===`engine`?`Studio couldn't download the rendering engine. Try again.`:`Studio couldn't verify this connection. Try again.`)}await vo(o),O({res:t,status:200,data:{success:!0,org:o.org}})}catch(e){j(t,e)}}}let Q=null;function xo(e){return Q===e?(Q=null,!0):!1}function So(){let e=Q;Q=null,e?.controller.abort()}function Co(e){return async(t,n)=>{So();let r={id:It(),controller:new AbortController};Q=r;try{let t=U.getEngineRequested(),{loginUrl:i,waitForLogin:a}=await ka(t,{linkedOrganizationIds:(await J()).map(e=>e.org.id),signal:r.controller.signal}),o=!1;a.then(async n=>{if(Q!==r)return;let i=await _o(n,t);xo(r)&&(o=!0,await vo(i),ga(),U.clearAuthFailed(),e.ws.send({type:`custom`,event:`org-linked`,data:i.org}))}).catch(t=>{if(!(!o&&!xo(r))){if(t instanceof Gi){_.debug(`Nothing left to link`);let n=t instanceof Ki?t.message:void 0;e.ws.send({type:`custom`,event:`org-link-cancelled`,data:{attemptId:r.id,message:n}});return}_.error(`Link organization failed`,t),e.ws.send({type:`custom`,event:`org-link-failed`,data:{message:To(t),attemptId:r.id}})}}),O({res:n,status:200,data:{loginUrl:i,attemptId:r.id}})}catch(e){xo(r),j(n,e)}}}function wo(){return async(e,t)=>{try{let{attemptId:n}=await k(e),r=Q!==null&&Q.id===n;r&&So(),O({res:t,status:200,data:{cancelled:r}})}catch(e){j(t,e)}}}function To(e){return e instanceof Error&&e.message===xa?xa:e instanceof go?`Organization connected, but Studio couldn't finish switching. Your current organization is still active. Try switching again.`:`Couldn't connect the organization. Try again.`}function Eo(e){return async(t,n,r)=>t.method===`GET`&&t.url===`/api/organizations`?po()(t,n):t.method===`POST`&&t.url===`/api/organizations/switch`?bo()(t,n):t.method===`POST`&&t.url===`/api/organizations/add`?Co(e)(t,n):t.method===`POST`&&t.url===`/api/organizations/add/cancel`?wo()(t,n):r()}let $=null;async function Do(e){if($)return $;let t=U.getEngineRequested(),n=(await Y()).currentOrgId,r=e.resolvedUrls?.local[0]??null;return $=await ka(t,{returnTo:Promise.resolve(r)}),$.waitForLogin.then(async r=>{let i=U.isAuthFailed(),a=await _o(r,t);if(await vo(a),ga(),U.clearAuthFailed(),a.org.id!==n){e.ws.send({type:`custom`,event:`org-linked`,data:a.org});return}e.ws.send({type:`custom`,event:`token-refreshed`,data:a.accessToken}),i&&e.ws.send({type:`custom`,event:`auth-restored`})}).catch(e=>{_.error(`Login flow failed`,e)}).finally(()=>{$=null}),$}function Oo(e){return async(t,n,r)=>{let i=t.url?.split(`?`)[0];if(t.method!==`GET`||i!==`/api/auth/login`)return r();try{let t=await Do(e);n.statusCode=302,n.setHeader(`Location`,t.loginUrl),n.end()}catch(e){j(n,e)}}}function ko(){return async(e,t,n)=>{let r=e.url?.split(`?`)[0];if(e.method!==`POST`||r!==`/api/auth/failed`)return n();try{Number(e.headers[`content-length`]??0)>0&&await k(e),U.setAuthFailed(),O({res:t,status:200,data:{ok:!0}})}catch(e){j(t,e)}}}function Ao(e){return async(t,n,r)=>{let i=t.url?.split(`?`)[0];if(t.method!==`POST`||i!==`/api/auth/refresh`)return r();try{let t=U.isAuthFailed(),r=await Na();ga(),U.clearAuthFailed(),e.ws.send({type:`custom`,event:`token-refreshed`,data:r}),t&&e.ws.send({type:`custom`,event:`auth-restored`}),O({res:n,status:200,data:{token:r}})}catch(e){_.error(`On-demand token refresh failed`,e);let t=e instanceof D;O({res:n,status:t?503:401,data:{error:t?dn:N}})}}}function jo(e,t){return{name:`format-studio-middleware`,apply:`serve`,configureServer(n){n.middlewares.use(fo()),n.middlewares.use(Oo(n)),n.middlewares.use(ko()),n.middlewares.use(Ao(n)),n.middlewares.use(`/@studio/fonts.css`,Kr()),n.middlewares.use(`/@studio/fonts`,qr()),n.middlewares.use(`/@studio`,Gr()),n.middlewares.use(ei(n)),n.middlewares.use(`/api/engine-token`,uo()),n.middlewares.use(Nn(n)),n.middlewares.use($r()),n.middlewares.use(`/api/documents`,zn(t)),n.middlewares.use(`/api/documents`,Pn()),n.middlewares.use(Wr(n,t)),n.middlewares.use(`/api/diagnostics`,Qa()),n.middlewares.use(`/api/state`,oo()),n.middlewares.use(`/api/settings`,so()),n.middlewares.use(`/api/system`,lo()),n.middlewares.use(Eo(n)),n.middlewares.use(Za(n)),n.middlewares.use((t,r,i)=>ro(e)(t,r,i,n))}}}const Mo={parser:`typescript`},No=e=>`${`/`.replace(/\/$/,``)}/${e.replace(/^\.?\//,``)}`,Po=`
209
- export const loadDocumentData = async (documentName, variant = 'default') => {
210
- try {
211
- const baseUrl = window.location.origin
212
- const response = await fetch(\`\${baseUrl}/api/documents/\${documentName}/data/\${variant}\`)
213
-
214
- if (!response.ok) {
215
- throw new Error(\`Failed to load data for \${documentName}/\${variant}\`)
216
- }
217
-
218
- return await response.json()
219
- } catch (error) {
220
- console.error('Failed to load document data:', error)
221
- return {}
222
- }
223
- }
224
- `;function Fo(){return`const globs = import.meta.glob("${No(`*/index.${`{${Ie.join(`,`).replace(/\./g,``)}}`}`)}");`}function Io(e){return e.map(e=>{let t=No(`./${e.name}/index${e.extension}`);return`"${e.name}": () => {
225
- const loader = globs["${t}"];
226
-
227
- if (!loader) {
228
- throw new Error("Component not found for ${t}");
229
- }
230
-
231
- return loader();
232
- }`}).join(`,
233
- `)}async function Lo(e){if(e.length===0)throw new E(qe);let t=`
234
- import React from "react"
235
- import ReactDOM from "react-dom/client"
236
-
237
- ${Po}
238
-
239
- ${Fo()}
240
-
241
- export const components = {
242
- ${Io(e)}
243
- }
244
- `;return await qt.format(t,Mo)}async function Ro(e){if(e.length===0)throw new E(qe);let t=`
245
- import { createApp } from "vue"
246
-
247
- ${Po}
248
-
249
- ${Fo()}
250
-
251
- export const components = {
252
- ${Io(e)}
253
- }
254
- `;return await qt.format(t,Mo)}async function zo(e){if(e.length===0)throw new E(qe);let t=`
255
- import { Eta } from 'eta'
256
- const eta = new Eta({ varName: 'data' })
257
-
258
- ${Po}
259
-
260
- ${Fo()}
261
-
262
- export const components = {
263
- ${Io(e)}
264
- }
265
- `;return await qt.format(t,Mo)}const Bo={react:Lo,vue:Ro,html:zo};async function Vo(e,t){return await Bo[t.framework](e)}const Ho=`virtual:generate-modules`;function Uo(){return{name:`user-virtual-module`,apply:`serve`,resolveId(e){if(e===Ho)return e},async load(e){if(e===Ho){let e=C.getConfig();return await Vo(await ft(e),e)}}}}const Wo=/\.(css|scss|sass|less)(\?inline)?$/i;function Go(){return{name:`auto-inline-css`,enforce:`pre`,resolveId(e,t,n){return n?.ssr||!Wo.test(e)||!t||/\?inline($|&)/.test(e)?null:this.resolve(e+`?inline`,t)}}}function Ko(t,n){let r=e.relative(e.resolve(n),e.resolve(t));return r===``||!r.startsWith(`..`)&&!e.isAbsolute(r)}function qo(e,t){for(let n of t)if(Ko(e,n))return!0;return!1}async function Jo(e){try{let t=await b(e);return w(`sha256`).update(t).digest(`hex`).slice(0,8)}catch{return null}}function Yo(t={}){let n=(t.watchDirs??[]).map(t=>e.resolve(t)),r=t.documentsDir?e.resolve(t.documentsDir):null,i=t.onFileChanged??(()=>{});return{name:`hot-update-notifier`,apply:`serve`,configureServer(t){if(n.length===0&&!r)return;let a=null,o=null,s=async()=>{if(!o)return;let{event:e,file:n}=o;o=null,_.debug(`HMR asset event detected (${e})`,n),t.ws.send({type:`custom`,event:`hmr`,data:{file:n,ts:Date.now(),hash:e===`unlink`||e===`unlinkDir`?null:await Jo(n),event:e}})},c=(t,r)=>{let i=e.resolve(r);qo(i,n)&&(o={event:t,file:i},a&&clearTimeout(a),a=setTimeout(()=>void s(),75))},l=null,u=()=>{_.debug(`documents change settled, client refreshing documents`),t.ws.send({type:`custom`,event:`documents-changed`,data:{ts:Date.now()}})},d=(t,n)=>{!r||!Ko(e.resolve(n),r)||(_.debug(`documents ${t}: ${n}`),l&&clearTimeout(l),l=setTimeout(u,100))},f=[...n,...r?[r]:[]];for(let e of f)t.watcher.add(e);r&&_.debug(`Watching for document changes in: ${r}`);let p=e=>{i(e),c(`add`,e),d(`add`,e)},m=e=>{i(e),c(`change`,e)},ee=e=>{i(e),c(`unlink`,e),d(`unlink`,e)},h=e=>{i(e),c(`addDir`,e),d(`addDir`,e)},te=e=>{i(e),c(`unlinkDir`,e),d(`unlinkDir`,e)};t.watcher.on(`add`,p),t.watcher.on(`change`,m),t.watcher.on(`unlink`,ee),t.watcher.on(`addDir`,h),t.watcher.on(`unlinkDir`,te),t.httpServer?.once(`close`,()=>{for(let e of f)t.watcher.unwatch(e);a&&clearTimeout(a),l&&clearTimeout(l),t.watcher.off(`add`,p),t.watcher.off(`change`,m),t.watcher.off(`unlink`,ee),t.watcher.off(`addDir`,h),t.watcher.off(`unlinkDir`,te)})},async handleHotUpdate(e){if(i(e.file),n.length>0&&qo(e.file,n))return[];_.debug(`HMR file update detected`,e.file);let t=await Jo(e.file);return e.server.ws.send({type:`custom`,event:`hmr`,data:{file:e.file,ts:Date.now(),hash:t,modules:e.modules.map(e=>e.url)}}),[]}}}const Xo={appDir:a(R,`app`),engineDir:V};function Zo(e,t=Xo){return[re(e),t.appDir,t.engineDir]}function Qo(){let e=new Set,t=new Map;return function(n={}){let r=[$n()],i={};for(let e of r){if(!l.existsSync(e))continue;let t=xe(l.readFileSync(e,`utf8`));Object.assign(i,t)}let a=n.keyFilter??(()=>!0),o=new Set(Object.keys(i).filter(a));for(let n of e)if(!o.has(n))if(t.has(n)){let e=t.get(n);e===void 0?delete process.env[n]:process.env[n]=e,t.delete(n)}else delete process.env[n];for(let e of o)t.has(e)||t.set(e,process.env[e]),process.env[e]=i[e];e=o}}const $o=Qo();function es(e={}){return $o(e)}function ts(e){return t=>{let n=s($n()),r=null,i=t=>{s(t)===n&&(r&&clearTimeout(r),r=setTimeout(()=>{e()},75))};t.watcher.add(n),t.watcher.on(`add`,i),t.watcher.on(`change`,i),t.watcher.on(`unlink`,i),t.httpServer?.once(`close`,()=>{r&&clearTimeout(r),t.watcher.unwatch(n),t.watcher.off(`add`,i),t.watcher.off(`change`,i),t.watcher.off(`unlink`,i)})}}function ns(e,t){let n=!1,r=null,i=i=>{r&&clearTimeout(r),r=setTimeout(async()=>{if(!n){n=!0;try{_.info(`Config file changed — restarting Format Studio server...`);let{config:n}=await g(e);C.setConfig(n),await t?.(),await i.restart()}catch(e){_.error(`Restart failed.`,e);let t={message:`Failed to restart Format Studio server after config file change.`};e instanceof Error&&e.message&&(t.details=[{message:e.message}]),M(i,t)}finally{n=!1}}},120)};return t=>{let n=n=>{n===e&&(U.consumeConfigRestartSkip()||i(t))};t.watcher.add(e),t.watcher.on(`change`,n),t.watcher.on(`add`,n),t.watcher.on(`unlink`,n),t.httpServer?.once(`close`,()=>{t.watcher.unwatch(e),t.watcher.off(`change`,n),t.watcher.off(`add`,n),t.watcher.off(`unlink`,n)})}}function rs(e,t,n=`pre`){return{name:e,enforce:n,async configResolved(e){for(let n of t.configResolved??[])await n(e)},async configureServer(e){for(let n of t.configureServer??[])await n(e)},async handleHotUpdate(e){for(let n of t.handleHotUpdate??[])await n(e)},async buildStart(){for(let e of t.buildStart??[])await e()},async closeBundle(){for(let e of t.closeBundle??[])await e()}}}function is(e,t={}){let{onRestart:n}=t,r=()=>{es(),_e(he())};return rs(`format:hooks`,{configResolved:[r],configureServer:[r,ts(r),ns(e,n)]})}async function as(){let e=await g();return C.setConfig(e.config),es(),e}function os(e=process.env.FMT_ENGINE_VERSION,t=I()){return e?.trim()||(t.stampEngineVersion??`0.4.0`)}const ss={FMT_ENV:`the FMT_ENV variable`,settings:`saved settings`,default:`the default`},cs=e=>ss[e],ls=e=>e.port?Number(e.port):process.env.PORT?Number(process.env.PORT):1234;async function us(e){let{config:t,filepath:n}=await as(),r=$n();u(r)||_.debug(`No .env file found at startup: ${r}`),_e(he()),bn({settings:await P()});let i=Sn();xn(i)&&_.info(`Environment: ${i.environment.name} (from ${cs(i.source)})`);let a=ls(e),o=S();_.info(`Loading Format Studio...`),_.debug(`Format dev options`,e),_.debug(`CWD: ${o}`),_.debug(`User config: ${JSON.stringify(t)}`),_.debug(`Log level: ${me()}`),_.debug(`Checking dependency versions`);try{Qt(o)}catch(e){_.error(e.message),process.exit(1)}let c=await Zt(o);if(c.pinnedVersion||(_.error(`No "version" field found in your Format config. Run \`${X(`update latest`)}\` to pin a release.`),process.exit()),c.mismatches.length>0){_.error(`Some installed Format packages do not match the pinned version (${c.pinnedVersion}):`);for(let e of c.mismatches)_.error(` ${e.name} ${e.actual} (expected ${e.expected})`);_.error(`Run \`${X(`update`)}\` to bring everything in line.`),process.exit()}let l=os();_.debug(`Engine requested: ${l}`),Ca(e.authMode);let d=Ea();try{_.debug(`Authenticating`);let t=await Ba(l,e,d);if(!t)throw new E(`Failed to authenticate`);let{accessToken:n,engineUrl:r,engineDigest:i,engine:a}=t;if(!n)throw new E(`Access token missing from credentials`);if(!r)throw new E(`Engine URL missing from access token`);U.setToken(n),U.setEngineVersions({requested:l,resolved:a}),await mo(r,a,i)}catch(e){e instanceof sa&&(console.error(e.message),process.exit(3)),_.error(`Failed to start Format Studio`),e instanceof D&&(_.error(dn),process.exit()),_.error(`Error: ${e.message}`),process.exit()}let f=(0,L.getSharedAssetsDir)(t),{isDirectory:p}=await fe(f),m=p;!p&&t.sharedAssetsDir&&_.error(`Shared assets directory (sharedAssetsDir) not found or is not a directory: ${t.sharedAssetsDir} (${f})`);let{baseViteConfig:ee,frameworkPlugins:re,stylePlugins:ae}=Yt(),oe=new $t({log:e=>_.debug(e),warn:e=>_.warn(e),allowedReadPaths:[o],sandbox:`standard`}),se=[()=>void oe.dispose(),Vr];process.once(`exit`,()=>{for(let e of se)e()});let ce=()=>process.exit();process.once(`SIGINT`,ce),process.once(`SIGTERM`,ce);let le=await te(ne(ee,{clearScreen:!1,configFile:!1,server:{port:a,strictPort:!0,fs:{allow:Zo(o)},watch:{ignored:Le,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}},plugins:[Yo({watchDirs:[r,...m?[f]:[]],documentsDir:(0,L.getDocumentsDir)(t),onFileChanged:e=>Lr(e,t)}),is(n),Jt(!1),Go(),Uo(),jo(a,oe),...re,...ae],optimizeDeps:{entries:!1,exclude:[`dist/app`]},define:{DEFAULT_VARIANT:JSON.stringify(He),VARIANT_PARAM:JSON.stringify(Je)},build:{rollupOptions:{input:{}}},cacheDir:s(jn(),`vite-cache`),resolve:{dedupe:[`react`,`react-dom`],alias:{[Tn]:$a(R,`app`,`index.js`)},mainFields:[]}}));Er(e=>{le.ws.send({type:`custom`,event:`pdf-build-status`,data:e})}),await oe.initDev({root:o,framework:t.framework,configJson:JSON.stringify(t),decodeStyleEntities:Xt({framework:t.framework})});try{await le.listen()}catch(e){if(!/already in use/i.test(e.message))throw e;_.error(fn(a)),process.exit(1)}se.push(Pa({server:le}));let ue=`${un}:${a}`;d.studioListening(ue),e.open&&!await d.browserSent&&await ie(ue);let de=[`FORMAT STUDIO`,`————————————————————————`,ue,`————————————————————————`,`Build something amazing.`],pe=Math.max(...de.map(e=>e.length))+8,g=`═`.repeat(pe+2);console.log(h(`╔${g}╗`)),de.forEach(e=>{let t=e.padStart((pe+e.length)/2).padEnd(pe);console.log(h(`║ ${t} ║`))}),console.log(h(`╚${g}╝`))}export{P as C,bn as S,E as T,ri as _,ja as a,On as b,Ni as c,Ei as d,wi as f,J as g,yi as h,Z as i,X as l,Y as m,os as n,ji as o,Ti as p,as as r,Mi as s,us as t,bi as u,ii as v,D as w,I as x,jn as y};