@zortexhq/indra-v2.5 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/box-level1-setup.js +1 -1
- package/dist/calcom-level1-setup.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/connector-worker.js +1 -1
- package/dist/discord-level1-setup.js +1 -1
- package/dist/dropbox-level1-setup.js +1 -1
- package/dist/figma-level1-setup.js +1 -1
- package/dist/freshdesk-level1-setup.js +1 -1
- package/dist/freshrss-level1-setup.js +1 -1
- package/dist/front-level1-setup.js +1 -1
- package/dist/gateway.js +1 -1
- package/dist/google-chat-level1-setup.js +1 -1
- package/dist/google-contacts-level1-setup.js +1 -1
- package/dist/hubspot-level1-setup.js +1 -1
- package/dist/joplin-selection.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mattermost-level1-setup.js +1 -1
- package/dist/mcp.js +2 -2
- package/dist/measurement-context.js +1 -1
- package/dist/miniflux-level1-setup.js +1 -1
- package/dist/nextcloud-level1-setup.js +1 -1
- package/dist/operation-telemetry.js +1 -0
- package/dist/prepared-level1-setup.js +1 -0
- package/dist/product-feedback.js +2 -2
- package/dist/profile.js +1 -1
- package/dist/proton-mail-level1-setup.js +1 -1
- package/dist/recovery-launch.js +10 -0
- package/dist/recovery-support.js +1 -1
- package/dist/recovery-surface.js +1 -0
- package/dist/recovery.js +1 -1
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +1 -1
- package/dist/resident-telemetry.js +1 -0
- package/dist/resource-telemetry.js +1 -0
- package/dist/salesforce-level1-setup.js +1 -1
- package/dist/smartsheet-level1-setup.js +1 -1
- package/dist/startup.js +2 -2
- package/dist/thunderbird-level1-setup.js +1 -1
- package/dist/wakatime-level1-setup.js +1 -1
- package/dist/wallabag-level1-setup.js +1 -1
- package/dist/web.js +2 -2
- package/dist/zendesk-level1-setup.js +1 -1
- package/dist/zoom-level1-setup.js +1 -1
- package/dist/zulip-level1-setup.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/operational-hub.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/chatgpt.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/mcp-feedback.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/package.json +2 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/galaxy-text.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/localizer.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/server.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app.html +98 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-client.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-forms.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-panel.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy-renderer.js +13 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy.html +141 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-state.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/panels-live.js +3 -3
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/product.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.css +12 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/original/fonts/LICENSE.txt +92 -0
- package/node_modules/@zortexhq/plugin-jev-autopilot/dist/feedback.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-bridge.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-autopilot/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-actions.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/driver.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/operational-browser.js +1 -0
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/session-routes.js +1 -1
- package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/shared-session.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/activity.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/collection-status.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/indra.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/local-cloud.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/observations.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-posthog/dist/source-ids.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/api/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/resource-sampler.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/package.json +3 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/collection.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/observations.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/source-ids.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/upstream-tools.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/device-identity.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/resources.js +1 -0
- package/node_modules/@zortexhq/plugin-telemetry/package.json +3 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/storage-metadata.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/storage-metadata.js +1 -0
- package/package.json +6 -6
- package/profiles/core.yml +1 -0
- package/release-provenance.json +26 -26
- package/update-manifest.json +419 -197
- package/dist/recovery-page.js +0 -215
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readGalaxySnapshot}from"./snapshot.js";import{galaxyRoute}from"./routes.js";import{startGalaxyServer,LOOPBACK_HOSTS}from"./server.js";import{producePortrait}from"./portrait-producer.js";import{configuredSourceIds,connectionStates,progressStates,supportStates}from"./original-adapter.js";import{readSyncProgress}from"./sync-progress.js";export{readGalaxySnapshot}from"./snapshot.js";export{readSyncProgress}from"./sync-progress.js";export{localizer,localizerScript,LANGUAGE_KEY}from"./localizer.js";export const name="zortex-galaxy-ui";export const inject=["zortexSqliteVault"];const releaseVersion=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.]{1,40})?$/;const SYNC_READ_MS=4e3;export async function apply(ctx,config={}){const host=config?.host??"127.0.0.1",port=config?.port??0;if(!LOOPBACK_HOSTS.includes(host))throw Error("Galaxy listens on a loopback address only.");if(!Number.isSafeInteger(port)||port<0||port>65535)throw Error("Galaxy port must be 0-65535.");const productVersion=typeof config?.productVersion==="string"&&releaseVersion.test(config.productVersion)?config.productVersion:null;const readSnapshot=config.snapshotReader??(()=>readGalaxySnapshot(ctx.zortexSqliteVault));const unavailableSnapshot=()=>({version:1,status:"unavailable",generatedAt:new Date().toISOString(),totalItems:0,first:null,latest:null,sources:[],daily:[],hourly:[],sourceDays:[],records:[]});let snapshot=config.snapshotReader?await readSnapshot().catch(()=>unavailableSnapshot()):await readSnapshot();const lifetime=new AbortController;const service=name2=>ctx.get(name2);let portrait={state:"unavailable",reason:"cached_vectors_unavailable"};const analyze=value=>config.snapshotReader?Promise.resolve({state:"unavailable",reason:"cached_vectors_unavailable"}):producePortrait(ctx.zortexSqliteVault,value,service("zortexGeminiSearch"),lifetime.signal);const configuredSources=configuredSourceIds(config.configuredSources);const installed=async()=>{if(config.sourceInventory){try{const value=await config.sourceInventory();return Array.isArray(value)?connectionStates(value.filter(row=>row?.configuration!=="required")):null}catch{return null}}if(config.snapshotReader&&!config.connectionStatus)return null;if(config.connectionStatus){try{const value=await config.connectionStatus();return Array.isArray(value)?connectionStates(value):null}catch{return null}}const hub=service("zortexConnectorHub");try{const value=(await hub?.status())?.ok;return Array.isArray(value)?connectionStates(value):null}catch{return null}};const progress=async()=>{if(config.sourceProgress){try{return progressStates(await config.sourceProgress())}catch{return[]}}if(config.snapshotReader)return[];const fleet=service("indraFleet");try{return progressStates((await fleet?.status())?.sources)}catch{return[]}};const support=async()=>{try{return supportStates(await config.sourceSupport?.())}catch{return[]}};let active=true;let syncRead;const syncProgress=async()=>{if(!active||config.snapshotReader)return void 0;if(!syncRead||Date.now()-syncRead.at>=SYNC_READ_MS)syncRead={at:Date.now(),value:readSyncProgress(ctx.zortexSqliteVault,{journal:service("zortexConnectorProcessJournal"),scheduler:service("indraSourceSync"),signal:lifetime.signal})};return syncRead.value};const route=await galaxyRoute(()=>snapshot,installed,productVersion,async durationMs=>{const telemetry=service("zortexTelemetry");await telemetry?.record({operation:"product.galaxy_opened",outcome:"ok",durationMs,code:snapshot.coverageNote?.providerCache==="unavailable"||snapshot.coverageNote?.bounded?"live_local_partial":"live_local"}).catch(()=>void 0)},configuredSources,progress,()=>portrait,syncProgress,configuredSourceIds(config.directorySources??config.catalogSources),support,config.openConnection,service("zortexProductAccount"));const page=await startGalaxyServer(route,{host,port,entry:"/zortex-galaxy/app.html"});ctx.effect(()=>()=>page.close(),`${name}: local page server`);ctx.reflect.provide("zortexGalaxyPage",{url:page.url,origin:page.origin,port:page.port});ctx.reflect.provide("zortexGalaxyReader",page.reader);if(config?.announce===true)ctx.logger.info("Galaxy page: %s",page.url);let readAt=Date.now(),pending;const refresh=()=>pending??=(async()=>{try{const next=await readSnapshot();if(!active)return;const measured=await analyze(next);if(active){snapshot=next;portrait=measured;readAt=Date.now()}}catch{if(active)snapshot={...snapshot,status:"unavailable"}}finally{pending=void 0}})();void refresh();const timer=setInterval(()=>{if(snapshot.status==="unavailable"||Date.now()-readAt>=6e4)void refresh()},5e3);timer.unref();ctx.effect(()=>()=>{active=false;lifetime.abort();clearInterval(timer)},`${name}: aggregate refresh`)}
|
|
1
|
+
import{readGalaxySnapshot}from"./snapshot.js";import{galaxyRoute}from"./routes.js";import{startGalaxyServer,LOOPBACK_HOSTS}from"./server.js";import{producePortrait}from"./portrait-producer.js";import{configuredSourceIds,connectionStates,progressStates,supportStates}from"./original-adapter.js";import{readSyncProgress}from"./sync-progress.js";export{readGalaxySnapshot}from"./snapshot.js";export{readSyncProgress}from"./sync-progress.js";export{localizer,localizerScript,LANGUAGE_KEY}from"./localizer.js";export const name="zortex-galaxy-ui";export const inject=["zortexSqliteVault"];const releaseVersion=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.]{1,40})?$/;const SYNC_READ_MS=4e3;export async function apply(ctx,config={}){const host=config?.host??"127.0.0.1",port=config?.port??0;if(!LOOPBACK_HOSTS.includes(host))throw Error("Galaxy listens on a loopback address only.");if(!Number.isSafeInteger(port)||port<0||port>65535)throw Error("Galaxy port must be 0-65535.");const productVersion=typeof config?.productVersion==="string"&&releaseVersion.test(config.productVersion)?config.productVersion:null;const readSnapshot=config.snapshotReader??(()=>readGalaxySnapshot(ctx.zortexSqliteVault));const unavailableSnapshot=()=>({version:1,status:"unavailable",generatedAt:new Date().toISOString(),totalItems:0,first:null,latest:null,sources:[],daily:[],hourly:[],sourceDays:[],records:[]});let snapshot=config.snapshotReader?await readSnapshot().catch(()=>unavailableSnapshot()):await readSnapshot();const lifetime=new AbortController;const service=name2=>ctx.get(name2);let portrait={state:"unavailable",reason:"cached_vectors_unavailable"};const analyze=value=>config.snapshotReader?Promise.resolve({state:"unavailable",reason:"cached_vectors_unavailable"}):producePortrait(ctx.zortexSqliteVault,value,service("zortexGeminiSearch"),lifetime.signal);const configuredSources=configuredSourceIds(config.configuredSources);const installed=async()=>{if(config.sourceInventory){try{const value=await config.sourceInventory();return Array.isArray(value)?connectionStates(value.filter(row=>row?.configuration!=="required")):null}catch{return null}}if(config.snapshotReader&&!config.connectionStatus)return null;if(config.connectionStatus){try{const value=await config.connectionStatus();return Array.isArray(value)?connectionStates(value):null}catch{return null}}const hub=service("zortexConnectorHub");try{const value=(await hub?.status())?.ok;return Array.isArray(value)?connectionStates(value):null}catch{return null}};const progress=async()=>{if(config.sourceProgress){try{return progressStates(await config.sourceProgress())}catch{return[]}}if(config.snapshotReader)return[];const fleet=service("indraFleet");try{return progressStates((await fleet?.status())?.sources)}catch{return[]}};const support=async()=>{try{return supportStates(await config.sourceSupport?.())}catch{return[]}};let active=true;let syncRead;const syncProgress=async()=>{if(!active||config.snapshotReader)return void 0;if(!syncRead||Date.now()-syncRead.at>=SYNC_READ_MS)syncRead={at:Date.now(),value:readSyncProgress(ctx.zortexSqliteVault,{journal:service("zortexConnectorProcessJournal"),scheduler:service("indraSourceSync"),signal:lifetime.signal})};return syncRead.value};const route=await galaxyRoute(()=>snapshot,installed,productVersion,async durationMs=>{const telemetry=service("zortexTelemetry");await telemetry?.record({operation:"product.galaxy_opened",outcome:"ok",durationMs,code:snapshot.coverageNote?.providerCache==="unavailable"||snapshot.coverageNote?.bounded?"live_local_partial":"live_local"}).catch(()=>void 0)},configuredSources,progress,()=>portrait,syncProgress,configuredSourceIds(config.directorySources??config.catalogSources),support,config.openConnection,service("zortexProductAccount"),config.connectionRequest);const page=await startGalaxyServer(route,{host,port,entry:"/zortex-galaxy/app.html"});ctx.effect(()=>()=>page.close(),`${name}: local page server`);ctx.reflect.provide("zortexGalaxyPage",{url:page.url,origin:page.origin,port:page.port});ctx.reflect.provide("zortexGalaxyReader",page.reader);if(config?.announce===true)ctx.logger.info("Galaxy page: %s",page.url);let readAt=Date.now(),pending;const refresh=()=>pending??=(async()=>{try{const next=await readSnapshot();if(!active)return;const measured=await analyze(next);if(active){snapshot=next;portrait=measured;readAt=Date.now()}}catch{if(active)snapshot={...snapshot,status:"unavailable"}}finally{pending=void 0}})();void refresh();const timer=setInterval(()=>{if(snapshot.status==="unavailable"||Date.now()-readAt>=6e4)void refresh()},5e3);timer.unref();ctx.effect(()=>()=>{active=false;lifetime.abort();clearInterval(timer)},`${name}: aggregate refresh`)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const LANGUAGE_KEY="zortex-language";export function localizer(text,options={}){const KEY="zortex-language";const LANGS=[["en","English"],["zh-Hans","\u7B80\u4F53\u4E2D\u6587"],["zh-Hant","\u7E41\u9AD4\u4E2D\u6587"]];const valid=value=>LANGS.some(([id])=>id===value)?value:"en";let lang="en";try{lang=valid(localStorage.getItem(KEY))}catch{}const exact=new Map,patterns=[];for(const[en,zh]of Object.entries(text)){if(!/\{\d\}/.test(en)){exact.set(en,zh);continue}const order=[];const source=en.split(/\{(\d)\}/).map((part,i)=>i%2?(order.push(Number(part)),"(.+?)"):part.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("");patterns.push([new RegExp(`^${source}$`),order,zh])}const fixed=pattern=>pattern.source.split("(.+?)").join("").length;patterns.sort((a,b)=>fixed(b[0])-fixed(a[0]));const pick=zh=>zh[lang==="zh-Hant"?1:0];const tr=(en,depth=0)=>{if(lang==="en"||depth>3)return en;const[,lead,core,tail]=/^(\s*)([\s\S]*?)(\s*)$/.exec(en);if(!core||!/[A-Za-z]/.test(core))return en;const hit=exact.get(core);if(hit)return lead+pick(hit)+tail;for(const[pattern,order,zh]of patterns){const found=pattern.exec(core);if(found)return lead+order.reduce((out,n,i)=>out.replace(`{${n}}`,()=>tr(found[i+1],depth+1)),pick(zh))+tail}return en};const ATTRS=["aria-label","title","placeholder"];const shownText=new WeakMap,shownAttrs=new WeakMap;const skip=node=>!node||!!node.closest?.("script,style,[data-no-translate]");const skipText=parent2=>skip(parent2)||!!parent2.closest?.("textarea");const one=node=>{const was=shownText.get(node),en=was&&node.data===was.shown?was.en:node.data,shown=tr(en);shownText.set(node,{en,shown});if(node.data!==shown)node.data=shown};const attr=(el,name)=>{const value=el.getAttribute(name);if(value===null)return;let all=shownAttrs.get(el);if(!all)shownAttrs.set(el,all={});const was=all[name],en=was&&value===was.shown?was.en:value,shown=tr(en);all[name]={en,shown};if(value!==shown)el.setAttribute(name,shown)};const walk=node=>{if(node.nodeType===3){if(!skipText(node.parentNode))one(node);return}if(node.nodeType!==1||skip(node))return;for(const name of ATTRS)attr(node,name);for(const child of[...node.childNodes])walk(child)};let picker;const apply=next=>{lang=valid(next);document.documentElement.lang=lang;walk(document.documentElement);if(picker)picker.value=lang};new MutationObserver(records=>{for(const record of records){if(record.type==="characterData"){if(!skipText(record.target.parentNode))one(record.target)}else if(record.type==="attributes"){if(!skip(record.target))attr(record.target,record.attributeName)}else record.addedNodes.forEach(walk)}}).observe(document.documentElement,{subtree:true,childList:true,characterData:true,attributes:true,attributeFilter:ATTRS});addEventListener("storage",event=>{if(event.key===KEY)apply(event.newValue??"en")});const anchor=options.picker?document.querySelector(options.picker):null;let framed=false;try{framed=parent!==window
|
|
1
|
+
export const LANGUAGE_KEY="zortex-language";export function localizer(text,options={}){const KEY="zortex-language";const LANGS=[["en","English"],["zh-Hans","\u7B80\u4F53\u4E2D\u6587"],["zh-Hant","\u7E41\u9AD4\u4E2D\u6587"]];const valid=value=>LANGS.some(([id])=>id===value)?value:"en";let lang="en";try{lang=valid(localStorage.getItem(KEY))}catch{}const exact=new Map,patterns=[];for(const[en,zh]of Object.entries(text)){if(!/\{\d\}/.test(en)){exact.set(en,zh);continue}const order=[];const source=en.split(/\{(\d)\}/).map((part,i)=>i%2?(order.push(Number(part)),"(.+?)"):part.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("");patterns.push([new RegExp(`^${source}$`),order,zh])}const fixed=pattern=>pattern.source.split("(.+?)").join("").length;patterns.sort((a,b)=>fixed(b[0])-fixed(a[0]));const pick=zh=>zh[lang==="zh-Hant"?1:0];const tr=(en,depth=0)=>{if(lang==="en"||depth>3)return en;const[,lead,core,tail]=/^(\s*)([\s\S]*?)(\s*)$/.exec(en);if(!core||!/[A-Za-z]/.test(core))return en;const hit=exact.get(core);if(hit)return lead+pick(hit)+tail;for(const[pattern,order,zh]of patterns){const found=pattern.exec(core);if(found)return lead+order.reduce((out,n,i)=>out.replace(`{${n}}`,()=>tr(found[i+1],depth+1)),pick(zh))+tail}return en};const ATTRS=["aria-label","title","placeholder"];const shownText=new WeakMap,shownAttrs=new WeakMap;const skip=node=>!node||!!node.closest?.("script,style,[data-no-translate]");const skipText=parent2=>skip(parent2)||!!parent2.closest?.("textarea");const one=node=>{const was=shownText.get(node),en=was&&node.data===was.shown?was.en:node.data,shown=tr(en);shownText.set(node,{en,shown});if(node.data!==shown)node.data=shown};const attr=(el,name)=>{const value=el.getAttribute(name);if(value===null)return;let all=shownAttrs.get(el);if(!all)shownAttrs.set(el,all={});const was=all[name],en=was&&value===was.shown?was.en:value,shown=tr(en);all[name]={en,shown};if(value!==shown)el.setAttribute(name,shown)};const walk=node=>{if(node.nodeType===3){if(!skipText(node.parentNode))one(node);return}if(node.nodeType!==1||skip(node))return;for(const name of ATTRS)attr(node,name);for(const child of[...node.childNodes])walk(child)};let picker;const apply=next=>{lang=valid(next);document.documentElement.lang=lang;walk(document.documentElement);if(picker)picker.value=lang};new MutationObserver(records=>{for(const record of records){if(record.type==="characterData"){if(!skipText(record.target.parentNode))one(record.target)}else if(record.type==="attributes"){if(!skip(record.target))attr(record.target,record.attributeName)}else record.addedNodes.forEach(walk)}}).observe(document.documentElement,{subtree:true,childList:true,characterData:true,attributes:true,attributeFilter:ATTRS});addEventListener("storage",event=>{if(event.key===KEY)apply(event.newValue??"en")});const anchor=options.picker?document.querySelector(options.picker):null;let framed=false;try{framed=parent!==window&&(!!options.parentShell&&parent.location.pathname.endsWith(options.parentShell)||parent.document.getElementById("twin")?.contentWindow===window)}catch{}if(anchor||options.float&&!framed){picker=document.createElement("select");picker.className="zx-language";picker.dataset.noTranslate="";picker.setAttribute("aria-label","Language \xB7 \u8BED\u8A00 \xB7 \u8A9E\u8A00");for(const[id,name]of LANGS)picker.append(new Option(name,id));picker.addEventListener("change",()=>{try{localStorage.setItem(KEY,picker.value)}catch{}apply(picker.value)});if(anchor)anchor.before(picker);else{picker.style.cssText="position:fixed;top:16px;right:72px;z-index:2147483647;padding:6px 10px;font:13px/1.2 system-ui,sans-serif;color:#e8e8ea;background:rgba(20,22,28,.72);border:1px solid rgba(255,255,255,.22);border-radius:100px;cursor:pointer";document.body.append(picker)}}apply(lang)}export function localizerScript(text,options={}){const data=value=>JSON.stringify(value).replace(/</g,"\\u003c");return`(${localizer.toString()})(${data(text)},${data(options)});`}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{localizerScript}from"./localizer.js";import{GALAXY_TEXT}from"./galaxy-text.js";import{originalGraph,originalNodes,originalHistory,sourceCoverage}from"./original-adapter.js";const base=new URL("../src/original/",import.meta.url);const integration=new URL("../src/integration/",import.meta.url);const types={js:"text/javascript",css:"text/css",html:"text/html",json:"application/json",svg:"image/svg+xml",png:"image/png",woff2:"font/woff2"};const iconAliases={"google-chrome":"chrome","google-drive":"drive","google-calendar":"gcal","apple-notes":"notes"};export function localIconEntries(value){if(!value||typeof value!=="object"||Array.isArray(value))return{};return Object.fromEntries(Object.entries(value).filter(([id,filename])=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(id)&&typeof filename==="string"&&/^[a-z0-9][a-z0-9-]{0,63}\.svg$/.test(filename)))}export async function galaxyRoute(snapshot,installed,productVersion,onLoaded=async()=>{},configuredSources=[],progress=async()=>[],portrait=()=>({state:"unavailable",reason:"cached_vectors_unavailable"}),sync=async()=>void 0,directorySources=[],support=async()=>[],openConnection,account){const token=randomUUID();const provenance=JSON.parse(await readFile(new URL("provenance.json",base),"utf8").then(s=>s.replace(/^\uFEFF/,"")));const allowed=new Set(provenance.files.map(row=>row.path));const upstreamIcons=JSON.parse(await readFile(new URL("icons/sources.json",base),"utf8"));const iconSources=Object.fromEntries(Object.entries(upstreamIcons).filter(([id,source])=>["a","m","s","f"].includes(source)&&allowed.has(`icons/${id}.${source==="s"?"svg":"png"}`)));const localManifest=await readFile(new URL("icons/local-sources.json",base),"utf8").then(s=>JSON.parse(s),error=>{if(error.code==="ENOENT")return{};throw error});const localIcons=localIconEntries(localManifest);const localPaths=Object.fromEntries(await Promise.all(Object.entries(localIcons).map(async([id,filename])=>{const path=`icons/local/${filename}`;try{await readFile(new URL(path,base));return[id,path]}catch{return[id,""]}})).then(rows=>rows.filter(([,path])=>path)));const localAllowed=new Set(Object.values(localPaths));const coverage=async()=>{const read=await sync();return{read,rows:sourceCoverage(snapshot(),await installed(),configuredSources,await progress(),read?.sources??[],directorySources,await support())}};let previousSnapshot,previousPortrait,renderRevision="";const revision=(value,measured)=>{if(value!==previousSnapshot||measured!==previousPortrait){const stable={...value,generatedAt:"1970-01-01T00:00:00.000Z"};const native=measured.state==="measured-subset"&&value.status==="live-local"?measured.portrait:void 0;renderRevision=createHash("sha256").update(JSON.stringify(value.status==="live-local"?[value.status,value.records?.map(record=>record.key),native?.rows??originalGraph(stable),native?.nodes??originalNodes(stable),native?.history??originalHistory(stable)]:[value.status])).digest("hex");previousSnapshot=value;previousPortrait=measured}return renderRevision};return{kind:"prefix",path:"/zortex-galaxy",async handler(req,res){const url=new URL(req.url??"/","http://localhost");const file=url.pathname.slice("/zortex-galaxy/".length);res.setHeader("Cache-Control","no-store");res.setHeader("X-Content-Type-Options","nosniff");res.setHeader("Content-Security-Policy","default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; worker-src 'self' blob:; connect-src 'self'; frame-ancestors 'self'");if(url.search){res.statusCode=400;res.end("Galaxy does not accept demo parameters.");return}if(file.startsWith("account/")){res.setHeader("Content-Type","application/json; charset=utf-8");if(!account){res.statusCode=503;res.end(JSON.stringify({error:"Account service is unavailable."}));return}if(file==="account/status"&&req.method==="GET"){res.end(JSON.stringify(await account.status()));return}const origin=req.headers.origin;if(req.method!=="POST"||req.headers["x-zortex-galaxy"]!==token||origin!==`http://${req.headers.host}`){res.statusCode=403;res.end("{}");return}let raw="";for await(const chunk of req){raw+=chunk;if(raw.length>1024){res.statusCode=413;res.end("{}");return}}let input;try{input=JSON.parse(raw);if(!input||typeof input!=="object"||Array.isArray(input))throw Error()}catch{res.statusCode=400;res.end("{}");return}try{if(file==="account/request"&&typeof input.email==="string")res.end(JSON.stringify(await account.requestCode(input.email)));else if(file==="account/verify"&&typeof input.code==="string")res.end(JSON.stringify(await account.verify(input.code)));else if(file==="account/logout"){await account.logout();res.end("{}")}else{res.statusCode=400;res.end("{}")}}catch(error){res.statusCode=400;res.end(JSON.stringify({error:error instanceof Error?error.message:"Sign-in failed."}))}return}if(file==="loaded"){const origin=req.headers.origin;if(req.method!=="POST"||req.headers["x-zortex-galaxy"]!==token||!origin||!["http:","https:"].some(scheme=>origin===`${scheme}//${req.headers.host}`)){res.statusCode=403;res.end();return}const durationMs=Number(req.headers["x-zortex-render-ms"]);if(!Number.isFinite(durationMs)||durationMs<0||durationMs>6e5){res.statusCode=400;res.end();return}if(snapshot().status==="live-local")await onLoaded(Math.round(durationMs));res.statusCode=204;res.end();return}if(file==="connect"){const origin=req.headers.origin;if(req.method!=="POST"||req.headers["x-zortex-galaxy"]!==token||!origin||origin!==`http://${req.headers.host}`||!openConnection){res.statusCode=403;res.end();return}let raw="";for await(const chunk of req){raw+=chunk;if(raw.length>1024){res.statusCode=413;res.end();return}}let source;try{source=JSON.parse(raw).source}catch{res.statusCode=400;res.end();return}if(typeof source!=="string"||!/^[a-z][a-z0-9._-]{0,95}$/i.test(source)){res.statusCode=400;res.end();return}const current=await installed();if(!current?.some(row=>row.source===source&&row.state!=="unavailable"&&row.registration!=="deferred")){res.statusCode=409;res.end("Source is not registered or is unavailable.");return}try{const destination=new URL(await openConnection(source));if(destination.protocol!=="http:"||destination.hostname!=="127.0.0.1"||destination.username||destination.password||destination.pathname!=="/"||destination.search||!destination.hash)throw Error("Invalid help URL");res.setHeader("Content-Type","application/json; charset=utf-8");res.end(JSON.stringify({url:destination.href}));return}catch{res.statusCode=503;res.end("Connection help is unavailable.");return}}if(req.method!=="GET"&&req.method!=="HEAD"){res.statusCode=405;res.end();return}let body;const measured=portrait(),native=measured.state==="measured-subset"&&snapshot().status==="live-local"?measured.portrait:void 0;if(file==="snapshot.json"){const{read,rows}=await coverage();const value=snapshot();body=JSON.stringify({...value,renderRevision:revision(value,measured),productVersion,portrait:native?{state:"measured-subset",evidence:native.rows.evidence}:{state:"unavailable",reason:measured.state==="unavailable"?measured.reason:"metadata_unavailable"},coverage:rows,sync:read?{generatedAt:read.generatedAt,facts:read.facts,counts:read.counts,runs:read.runs,schedule:read.schedule,...read.errorCode?{errorCode:read.errorCode}:{}}:null})}else if(file==="star-graph-data.json"){if(snapshot().status!=="live-local"){res.statusCode=503;res.end("Local records are not available.");return}body=JSON.stringify(native?.rows??originalGraph(snapshot()))}else if(file==="star-graph-nodes.json")body=JSON.stringify(native?.nodes??originalNodes(snapshot()));else if(file==="star-graph-history.json")body=JSON.stringify(native?.history??originalHistory(snapshot()));else if(file==="abilities.json")body=JSON.stringify({apps:(await coverage()).rows.map(r=>({id:r.source,name:r.source,group:"Local sources"})),iconSources,iconAliases,localIconPaths:localPaths});else if(file==="i18n.js")body=localizerScript(GALAXY_TEXT,{picker:"#account"});else if(file==="i18n-twin.js")body=localizerScript(GALAXY_TEXT,{float:true,parentShell:"/zortex-galaxy/app.html"});else if(file==="product-model.js")body=await readFile(new URL("portrait-model.js",integration));else if(file==="upstream-product-model.js")body=await readFile(new URL("product-model.js",base));else if(["panels-live.js","live-state.js","live-model.js","sync-model.js","refresh-model.js"].includes(file))body=await readFile(new URL(file,integration));else if(file==="product.js"||file==="product.css"||file==="shell.css"||file==="account.js"||file==="account.css")body=await readFile(new URL(file,integration));else if(file==="app.js")body=await readFile(new URL("shell.js",integration));else if(allowed.has(file)||localAllowed.has(file)){body=await readFile(new URL(file,base));if(file==="star-graph.html")body=body.toString().replace("</head>",`<meta name="zortex-galaxy-token" content="${token}"><link rel="stylesheet" href="product.css"></head>`).replace("</body>",'<script src="i18n-twin.js"><\/script></body>').replace("</body>",'<script type="module" src="product.js"><\/script></body>');if(file==="star-graph.js")body=body.toString().replace("galaxy.live ? mountLinks","galaxy.live && rows.mode !== 'record-map' ? mountLinks").replace("`${when}. Each part of it comes from one of these measurements.`","r.mode === 'record-map' ? `${when}. Real record map; semantic portrait has not been calculated. Geometry is layout only.` : r.evidence?.semantic === 'measured-subset' ? `${when}. Measured from an authored subset with existing vectors. Unknown dimensions use layout defaults; see coverage.` : `${when}. Each part of it comes from one of these measurements.`");if(file==="app.html")body=body.toString().replace("</head>",`<meta name="zortex-galaxy-token" content="${token}"><link rel="stylesheet" href="shell.css"><link rel="stylesheet" href="account.css"></head>`).replace("</body>",'<script src="account.js" defer><\/script><script src="i18n.js"><\/script></body>')}if(body===void 0){res.statusCode=404;res.end("Not found");return}const mime=types[file.split(".").at(-1)??""]??"application/octet-stream";res.setHeader("Content-Type",`${mime}${mime.startsWith("text/")||mime==="application/json"||mime==="image/svg+xml"?"; charset=utf-8":""}`);res.end(req.method==="HEAD"?void 0:body)}}}
|
|
1
|
+
import{readFile}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{localizerScript}from"./localizer.js";import{GALAXY_TEXT}from"./galaxy-text.js";import{originalGraph,originalNodes,originalHistory,sourceCoverage}from"./original-adapter.js";const base=new URL("../src/original/",import.meta.url);const integration=new URL("../src/integration/",import.meta.url);const types={js:"text/javascript",css:"text/css",html:"text/html",json:"application/json",svg:"image/svg+xml",png:"image/png",woff2:"font/woff2"};const iconAliases={"google-chrome":"chrome","google-drive":"drive","google-calendar":"gcal","apple-notes":"notes"};export function localIconEntries(value){if(!value||typeof value!=="object"||Array.isArray(value))return{};return Object.fromEntries(Object.entries(value).filter(([id,filename])=>/^[a-z0-9][a-z0-9-]{0,63}$/.test(id)&&typeof filename==="string"&&/^[a-z0-9][a-z0-9-]{0,63}\.svg$/.test(filename)))}export async function galaxyRoute(snapshot,installed,productVersion,onLoaded=async()=>{},configuredSources=[],progress=async()=>[],portrait=()=>({state:"unavailable",reason:"cached_vectors_unavailable"}),sync=async()=>void 0,directorySources=[],support=async()=>[],openConnection,account,connectionRequest){const token=randomUUID();const provenance=JSON.parse(await readFile(new URL("provenance.json",base),"utf8").then(s=>s.replace(/^\uFEFF/,"")));const allowed=new Set(provenance.files.map(row=>row.path));const upstreamIcons=JSON.parse(await readFile(new URL("icons/sources.json",base),"utf8"));const iconSources=Object.fromEntries(Object.entries(upstreamIcons).filter(([id,source])=>["a","m","s","f"].includes(source)&&allowed.has(`icons/${id}.${source==="s"?"svg":"png"}`)));const localManifest=await readFile(new URL("icons/local-sources.json",base),"utf8").then(s=>JSON.parse(s),error=>{if(error.code==="ENOENT")return{};throw error});const localIcons=localIconEntries(localManifest);const localPaths=Object.fromEntries(await Promise.all(Object.entries(localIcons).map(async([id,filename])=>{const path=`icons/local/${filename}`;try{await readFile(new URL(path,base));return[id,path]}catch{return[id,""]}})).then(rows=>rows.filter(([,path])=>path)));const localAllowed=new Set(Object.values(localPaths));const coverage=async()=>{const read=await sync();return{read,rows:sourceCoverage(snapshot(),await installed(),configuredSources,await progress(),read?.sources??[],directorySources,await support())}};let previousSnapshot,previousPortrait,renderRevision="";const revision=(value,measured)=>{if(value!==previousSnapshot||measured!==previousPortrait){const stable={...value,generatedAt:"1970-01-01T00:00:00.000Z"};const native=measured.state==="measured-subset"&&value.status==="live-local"?measured.portrait:void 0;renderRevision=createHash("sha256").update(JSON.stringify(value.status==="live-local"?[value.status,value.records?.map(record=>record.key),native?.rows??originalGraph(stable),native?.nodes??originalNodes(stable),native?.history??originalHistory(stable)]:[value.status])).digest("hex");previousSnapshot=value;previousPortrait=measured}return renderRevision};return{kind:"prefix",path:"/zortex-galaxy",async handler(req,res){const url=new URL(req.url??"/","http://localhost");const file=url.pathname.slice("/zortex-galaxy/".length);res.setHeader("Cache-Control","no-store");res.setHeader("X-Content-Type-Options","nosniff");res.setHeader("Content-Security-Policy","default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; worker-src 'self' blob:; connect-src 'self'; frame-ancestors 'self'");if(url.search){res.statusCode=400;res.end("Galaxy does not accept demo parameters.");return}if(file==="connections"){res.setHeader("Content-Type","application/json; charset=utf-8");if(req.method!=="POST"){res.statusCode=405;res.end(JSON.stringify({error:"method_not_allowed"}));return}if(req.headers["x-zortex-galaxy"]!==token||req.headers.origin!==`http://${req.headers.host}`){res.statusCode=403;res.end(JSON.stringify({error:"forbidden"}));return}if(!connectionRequest){res.statusCode=503;res.end(JSON.stringify({error:"connection_service_unavailable"}));return}if(!String(req.headers["content-type"]??"").toLowerCase().startsWith("application/json")){res.statusCode=400;res.end(JSON.stringify({error:"invalid_input"}));return}let raw="",bytes=0;for await(const chunk of req){bytes+=Buffer.byteLength(chunk);if(bytes>65536){res.statusCode=413;res.end(JSON.stringify({error:"request_too_large"}));return}raw+=chunk}let input;try{input=JSON.parse(raw);if(!input||typeof input!=="object"||Array.isArray(input))throw Error()}catch{res.statusCode=400;res.end(JSON.stringify({error:"invalid_input"}));return}const controller=new AbortController;const abort=()=>{if(!res.writableEnded)controller.abort()};res.once("close",abort);try{const result=await connectionRequest(input,controller.signal);res.statusCode=Number.isInteger(result.status)&&result.status>=200&&result.status<=599?result.status:500;res.end(JSON.stringify(result.body))}catch{if(!res.writableEnded){res.statusCode=503;res.end(JSON.stringify({error:"connection_service_unavailable"}))}}finally{res.off("close",abort)}return}if(file.startsWith("account/")){res.setHeader("Content-Type","application/json; charset=utf-8");if(!account){res.statusCode=503;res.end(JSON.stringify({error:"Account service is unavailable."}));return}if(file==="account/status"&&req.method==="GET"){res.end(JSON.stringify(await account.status()));return}const origin=req.headers.origin;if(req.method!=="POST"||req.headers["x-zortex-galaxy"]!==token||origin!==`http://${req.headers.host}`){res.statusCode=403;res.end("{}");return}let raw="";for await(const chunk of req){raw+=chunk;if(raw.length>1024){res.statusCode=413;res.end("{}");return}}let input;try{input=JSON.parse(raw);if(!input||typeof input!=="object"||Array.isArray(input))throw Error()}catch{res.statusCode=400;res.end("{}");return}try{if(file==="account/request"&&typeof input.email==="string")res.end(JSON.stringify(await account.requestCode(input.email)));else if(file==="account/verify"&&typeof input.code==="string")res.end(JSON.stringify(await account.verify(input.code)));else if(file==="account/logout"){await account.logout();res.end("{}")}else{res.statusCode=400;res.end("{}")}}catch(error){res.statusCode=400;res.end(JSON.stringify({error:error instanceof Error?error.message:"Sign-in failed."}))}return}if(file==="loaded"){const origin=req.headers.origin;if(req.method!=="POST"||req.headers["x-zortex-galaxy"]!==token||!origin||!["http:","https:"].some(scheme=>origin===`${scheme}//${req.headers.host}`)){res.statusCode=403;res.end();return}const durationMs=Number(req.headers["x-zortex-render-ms"]);if(!Number.isFinite(durationMs)||durationMs<0||durationMs>6e5){res.statusCode=400;res.end();return}if(snapshot().status==="live-local")await onLoaded(Math.round(durationMs));res.statusCode=204;res.end();return}if(file==="connect"){const origin=req.headers.origin;if(req.method!=="POST"||req.headers["x-zortex-galaxy"]!==token||!origin||origin!==`http://${req.headers.host}`||!openConnection){res.statusCode=403;res.end();return}let raw="";for await(const chunk of req){raw+=chunk;if(raw.length>1024){res.statusCode=413;res.end();return}}let source;try{source=JSON.parse(raw).source}catch{res.statusCode=400;res.end();return}if(typeof source!=="string"||!/^[a-z][a-z0-9._-]{0,95}$/i.test(source)){res.statusCode=400;res.end();return}const current=await installed();if(!current?.some(row=>row.source===source&&row.state!=="unavailable"&&row.registration!=="deferred")){res.statusCode=409;res.end("Source is not registered or is unavailable.");return}try{const destination=new URL(await openConnection(source));if(destination.protocol!=="http:"||destination.hostname!=="127.0.0.1"||destination.username||destination.password||destination.pathname!=="/"||destination.search||!destination.hash)throw Error("Invalid help URL");res.setHeader("Content-Type","application/json; charset=utf-8");res.end(JSON.stringify({url:destination.href}));return}catch{res.statusCode=503;res.end("Connection help is unavailable.");return}}if(req.method!=="GET"&&req.method!=="HEAD"){res.statusCode=405;res.end();return}let body;const measured=portrait(),native=measured.state==="measured-subset"&&snapshot().status==="live-local"?measured.portrait:void 0;if(file==="runtime.json")body=JSON.stringify({mode:"local",canConnect:!!connectionRequest,accountLabel:"This computer"});else if(file==="app.html")body=(await readFile(new URL("app.html",integration),"utf8")).replace("</head>",`<meta name="zortex-galaxy-token" content="${token}"></head>`);else if(file==="star-graph.html")body=(await readFile(new URL("galaxy.html",integration),"utf8")).replace("</head>",`<meta name="zortex-galaxy-token" content="${token}"></head>`);else if(file==="star-graph.js")body=await readFile(new URL("galaxy-renderer.js",integration));else if(file==="snapshot.json"){const{read,rows}=await coverage();const value=snapshot();body=JSON.stringify({...value,renderRevision:revision(value,measured),productVersion,portrait:native?{state:"measured-subset",evidence:native.rows.evidence}:{state:"unavailable",reason:measured.state==="unavailable"?measured.reason:"metadata_unavailable"},coverage:rows,sync:read?{generatedAt:read.generatedAt,facts:read.facts,counts:read.counts,runs:read.runs,schedule:read.schedule,...read.errorCode?{errorCode:read.errorCode}:{}}:null})}else if(file==="star-graph-data.json"){if(snapshot().status!=="live-local"){res.statusCode=503;res.end("Local records are not available.");return}body=JSON.stringify(native?.rows??originalGraph(snapshot()))}else if(file==="star-graph-nodes.json")body=JSON.stringify(native?.nodes??originalNodes(snapshot()));else if(file==="star-graph-history.json")body=JSON.stringify(native?.history??originalHistory(snapshot()));else if(file==="abilities.json")body=JSON.stringify({apps:(await coverage()).rows.map(r=>({id:r.source,name:r.source,group:"Local sources"})),iconSources,iconAliases,localIconPaths:localPaths});else if(file==="i18n.js")body=localizerScript(GALAXY_TEXT,{picker:"#account"});else if(file==="i18n-twin.js")body=localizerScript(GALAXY_TEXT,{float:true,parentShell:"/zortex-galaxy/app.html"});else if(file==="product-model.js")body=await readFile(new URL("portrait-model.js",integration));else if(file==="upstream-product-model.js")body=await readFile(new URL("product-model.js",base));else if(["app-i18n.js","app-i18n-twin.js","app-model.js","connection-client.js","connection-forms.js","connection-panel.js","panels-live.js","live-state.js","live-model.js","sync-model.js","refresh-model.js"].includes(file))body=await readFile(new URL(file,integration));else if(file==="product.js"||file==="product.css"||file==="shell.css"||file==="account.js"||file==="account.css")body=await readFile(new URL(file,integration));else if(file==="app.js")body=await readFile(new URL("shell.js",integration));else if(allowed.has(file)||localAllowed.has(file)){body=await readFile(new URL(file,base))}if(body===void 0){res.statusCode=404;res.end("Not found");return}const mime=types[file.split(".").at(-1)??""]??"application/octet-stream";res.setHeader("Content-Type",`${mime}${mime.startsWith("text/")||mime==="application/json"||mime==="image/svg+xml"?"; charset=utf-8":""}`);res.end(req.method==="HEAD"?void 0:body)}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createServer}from"node:http";import{randomBytes,timingSafeEqual}from"node:crypto";export const LOOPBACK_HOSTS=["127.0.0.1","::1"];const sameSecret=(given,expected)=>{const a=Buffer.from(given),b=Buffer.from(expected);return a.length===b.length&&timingSafeEqual(a,b)};function cookie(req,name){for(const part of(req.headers.cookie??"").split(";")){const index=part.indexOf("=");if(index>0&&part.slice(0,index).trim()===name)return part.slice(index+1).trim()}return void 0}function end(res,status,text){res.statusCode=status;res.setHeader("Cache-Control","no-store");if(text)res.setHeader("Content-Type","text/plain; charset=utf-8");res.end(text)}export async function startGalaxyServer(route,options){const launchToken=randomBytes(24).toString("base64url"),session=randomBytes(32).toString("base64url");let cookieName="",allowedHosts=new Set;const server=createServer((req,res)=>{const host=req.headers.host??"";if(!allowedHosts.has(host))return end(res,403);const origin2=req.headers.origin;if(origin2!==void 0&&origin2!==`http://${host}`)return end(res,403);let url;try{url=new URL(req.url??"/",`http://${host}`)}catch{return end(res,400)}const signedIn=(()=>{const value=cookie(req,cookieName);return value!==void 0&&sameSecret(value,session)})();if(url.pathname==="/"||url.pathname==="/index.html"){if(req.method!=="GET"&&req.method!=="HEAD")return end(res,405);const token=url.searchParams.get("token");if(token!==null&&!sameSecret(token,launchToken))return end(res,401,"This Zortex address has expired. Open the address printed by indra web.");if(token===null&&!signedIn)return end(res,401,"Open the address printed by indra web.");if(token!==null)res.setHeader("Set-Cookie",`${cookieName}=${session}; Path=/; HttpOnly; SameSite=Strict`);res.setHeader("Referrer-Policy","no-referrer");res.setHeader("Location",options.entry);return end(res,302)}const matches=route.kind==="exact"?url.pathname===route.path:url.pathname===route.path||url.pathname.startsWith(route.path+"/");if(!matches)return end(res,404);if(!signedIn)return end(res,401);Promise.resolve(route.handler(req,res)).catch(()=>{if(!res.headersSent)end(res,500);else res.destroy()})});server.headersTimeout=2e4;server.requestTimeout=6e4;await new Promise((resolve,reject)=>{server.once("error",reject);server.listen({host:options.host,port:options.port,exclusive:true},()=>{server.off("error",reject);resolve()})});const port=server.address().port;cookieName=`zortex_galaxy_${port}`;allowedHosts=new Set([`127.0.0.1:${port}`,`localhost:${port}`,`[::1]:${port}`]);const origin=options.host==="::1"?`http://[::1]:${port}`:`http://127.0.0.1:${port}`;const lifetime=new AbortController;let closing;const reader={async fetch(request){const refused=status=>new Response(null,{status,headers:{"Cache-Control":"no-store"}});if(lifetime.signal.aborted)return refused(503);if(!["GET","HEAD"].includes(request.method))return refused(405);const url=new URL(request.url);if(url.search||!url.pathname.startsWith("/zortex-galaxy/")||url.pathname==="/zortex-galaxy/loaded")return refused(400);if(url.pathname==="/zortex-galaxy/account"||url.pathname.startsWith("/zortex-galaxy/account/"))return refused(403);const response=await fetch(origin+url.pathname,{method:request.method,redirect:"manual",headers:{Cookie:`${cookieName}=${session}`},signal:AbortSignal.any([request.signal,lifetime.signal])});if(response.status>=300&&response.status<400){await response.body?.cancel();return refused(502)}const headers=new Headers({"Cache-Control":"no-store"});for(const key of["Content-Type","Content-Security-Policy","X-Content-Type-Options"]){const value=response.headers.get(key);if(value!==null)headers.set(key,value)}return new Response(response.body,{status:response.status,headers})}};return{port,origin,url:`${origin}/?token=${launchToken}`,reader,close:()=>closing??=new Promise(resolve=>{lifetime.abort();server.close(()=>resolve());server.closeAllConnections()})}}
|
|
1
|
+
import{createServer}from"node:http";import{randomBytes,timingSafeEqual}from"node:crypto";export const LOOPBACK_HOSTS=["127.0.0.1","::1"];const sameSecret=(given,expected)=>{const a=Buffer.from(given),b=Buffer.from(expected);return a.length===b.length&&timingSafeEqual(a,b)};function cookie(req,name){for(const part of(req.headers.cookie??"").split(";")){const index=part.indexOf("=");if(index>0&&part.slice(0,index).trim()===name)return part.slice(index+1).trim()}return void 0}function end(res,status,text){res.statusCode=status;res.setHeader("Cache-Control","no-store");if(text)res.setHeader("Content-Type","text/plain; charset=utf-8");res.end(text)}export async function startGalaxyServer(route,options){const launchToken=randomBytes(24).toString("base64url"),session=randomBytes(32).toString("base64url");let cookieName="",allowedHosts=new Set;const server=createServer((req,res)=>{const host=req.headers.host??"";if(!allowedHosts.has(host))return end(res,403);const origin2=req.headers.origin;if(origin2!==void 0&&origin2!==`http://${host}`)return end(res,403);let url;try{url=new URL(req.url??"/",`http://${host}`)}catch{return end(res,400)}const signedIn=(()=>{const value=cookie(req,cookieName);return value!==void 0&&sameSecret(value,session)})();if(url.pathname==="/"||url.pathname==="/index.html"){if(req.method!=="GET"&&req.method!=="HEAD")return end(res,405);const token=url.searchParams.get("token");if(token!==null&&!sameSecret(token,launchToken))return end(res,401,"This Zortex address has expired. Open the address printed by indra web.");if(token===null&&!signedIn)return end(res,401,"Open the address printed by indra web.");if(token!==null)res.setHeader("Set-Cookie",`${cookieName}=${session}; Path=/; HttpOnly; SameSite=Strict`);res.setHeader("Referrer-Policy","no-referrer");res.setHeader("Location",options.entry);return end(res,302)}const matches=route.kind==="exact"?url.pathname===route.path:url.pathname===route.path||url.pathname.startsWith(route.path+"/");if(!matches)return end(res,404);if(!signedIn)return end(res,401);Promise.resolve(route.handler(req,res)).catch(()=>{if(!res.headersSent)end(res,500);else res.destroy()})});server.headersTimeout=2e4;server.requestTimeout=6e4;await new Promise((resolve,reject)=>{server.once("error",reject);server.listen({host:options.host,port:options.port,exclusive:true},()=>{server.off("error",reject);resolve()})});const port=server.address().port;cookieName=`zortex_galaxy_${port}`;allowedHosts=new Set([`127.0.0.1:${port}`,`localhost:${port}`,`[::1]:${port}`]);const origin=options.host==="::1"?`http://[::1]:${port}`:`http://127.0.0.1:${port}`;const lifetime=new AbortController;let closing;const reader={async fetch(request){const refused=status=>new Response(null,{status,headers:{"Cache-Control":"no-store"}});if(lifetime.signal.aborted)return refused(503);if(!["GET","HEAD"].includes(request.method))return refused(405);const url=new URL(request.url);if(url.search||!url.pathname.startsWith("/zortex-galaxy/")||url.pathname==="/zortex-galaxy/loaded")return refused(400);if(url.pathname==="/zortex-galaxy/account"||url.pathname.startsWith("/zortex-galaxy/account/"))return refused(403);if(url.pathname==="/zortex-galaxy/runtime.json")return new Response(request.method==="HEAD"?null:JSON.stringify({mode:"remote",canConnect:false,accountLabel:"Your workspace",loginUrl:"https://zortex.me/account"}),{status:200,headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}});const response=await fetch(origin+url.pathname,{method:request.method,redirect:"manual",headers:{Cookie:`${cookieName}=${session}`},signal:AbortSignal.any([request.signal,lifetime.signal])});if(response.status>=300&&response.status<400){await response.body?.cancel();return refused(502)}const headers=new Headers({"Cache-Control":"no-store"});for(const key of["Content-Type","Content-Security-Policy","X-Content-Type-Options"]){const value=response.headers.get(key);if(value!==null)headers.set(key,value)}return new Response(response.body,{status:response.status,headers})}};return{port,origin,url:`${origin}/?token=${launchToken}`,reader,close:()=>closing??=new Promise(resolve=>{lifetime.abort();server.close(()=>resolve());server.closeAllConnections()})}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{const menu=document.getElementById("account-menu");if(!menu)return;const
|
|
1
|
+
(()=>{const menu=document.getElementById("account-menu");if(!menu)return;const t=(en,cn,tw=cn)=>document.documentElement.lang==="zh-Hant"?tw:document.documentElement.lang.toLowerCase().startsWith("zh")?cn:en;const trigger=document.createElement("button");trigger.type="button";trigger.setAttribute("role","menuitem");menu.prepend(trigger);const dialog=document.createElement("dialog");dialog.className="zortex-account";dialog.setAttribute("aria-labelledby","zortex-account-title");dialog.innerHTML='<form><h2 id="zortex-account-title"></h2><p class="account-description"></p><label class="account-email-label" for="zortex-email"></label><input id="zortex-email" type="email" autocomplete="email" maxlength="254" required><button type="button" class="account-send"></button><label class="account-code-label" for="zortex-code"></label><input id="zortex-code" type="text" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{8}" maxlength="8"><p class="account-message" role="status" aria-live="polite"></p><div class="account-actions"><button type="button" class="account-close"></button><button type="button" class="account-logout"></button><button type="submit" class="account-verify"></button></div></form>';document.body.append(dialog);const el=s=>dialog.querySelector(s),form=el("form"),email=el("#zortex-email"),code=el("#zortex-code"),message=el(".account-message"),send=el(".account-send"),verify=el(".account-verify"),logout=el(".account-logout");let status={state:"signed_out"},busy=false,requestedEmail="",cooldown=0,hosted=false;const runtimeReady=fetch("runtime.json",{cache:"no-store"}).then(r=>r.ok?r.json():{}).then(value=>{hosted=value.mode==="mock"}).catch(()=>{});async function api(path,body){await runtimeReady;const response=await fetch("account/"+path,{method:body===void 0?"GET":"POST",headers:body===void 0?{}:{"content-type":"application/json","x-zortex-galaxy":document.querySelector('meta[name="zortex-galaxy-token"]')?.content||""},...body===void 0?{}:{body:JSON.stringify(body)},cache:"no-store"});if(hosted&&[401,403].includes(response.status)){location.assign("/account");throw Error("Sign in to continue.")}const data=response.status===204?{}:await response.json();if(!response.ok)throw Error(data.error||t("Sign-in is unavailable. Try again.","\u767B\u5F55\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u91CD\u8BD5\u3002","\u767B\u5165\u66AB\u6642\u7121\u6CD5\u4F7F\u7528\uFF0C\u8ACB\u91CD\u8A66\u3002"));return data}function render(){const signed=status.state==="signed_in",name=status.displayName||status.label;if(signed&&name){const accountName=document.getElementById("account-name");accountName.textContent=name;accountName.dataset.noTranslate="";document.getElementById("avatar").textContent=name.slice(0,1).toUpperCase()}trigger.textContent=signed?t("Your account","\u4F60\u7684\u8D26\u53F7","\u4F60\u7684\u5E33\u865F"):t("Sign in with email","\u90AE\u7BB1\u767B\u5F55","\u4EE5\u96FB\u5B50\u90F5\u4EF6\u767B\u5165");el("h2").textContent=signed?t("Your Zortex account","\u4F60\u7684 Zortex \u8D26\u53F7","\u4F60\u7684 Zortex \u5E33\u865F"):t("Sign in to Zortex","\u767B\u5F55 Zortex","\u767B\u5165 Zortex");el(".account-description").dataset.noTranslate="";el(".account-description").textContent=signed?name||status.email:t("Verify your email to keep one account across devices. With usage analytics enabled, activity is linked to this account.","\u9A8C\u8BC1\u90AE\u7BB1\u540E\uFF0C\u53EF\u8DE8\u8BBE\u5907\u4F7F\u7528\u540C\u4E00\u8D26\u53F7\u3002\u542F\u7528\u4F7F\u7528\u7EDF\u8BA1\u65F6\uFF0C\u6D3B\u52A8\u8BB0\u5F55\u4F1A\u5173\u8054\u5230\u8FD9\u4E2A\u8D26\u53F7\u3002","\u9A57\u8B49\u96FB\u5B50\u90F5\u4EF6\u5F8C\uFF0C\u53EF\u8DE8\u88DD\u7F6E\u4F7F\u7528\u540C\u4E00\u5E33\u865F\u3002\u555F\u7528\u4F7F\u7528\u7D71\u8A08\u6642\uFF0C\u6D3B\u52D5\u8A18\u9304\u6703\u95DC\u806F\u5230\u6B64\u5E33\u865F\u3002");el(".account-email-label").textContent=t("Email","\u90AE\u7BB1","\u96FB\u5B50\u90F5\u4EF6");el(".account-code-label").textContent=t("Eight-digit code","\u516B\u4F4D\u9A8C\u8BC1\u7801","\u516B\u4F4D\u9A57\u8B49\u78BC");el(".account-close").textContent=t("Close","\u5173\u95ED","\u95DC\u9589");send.textContent=t("Send code","\u53D1\u9001\u9A8C\u8BC1\u7801","\u50B3\u9001\u9A57\u8B49\u78BC");verify.textContent=t("Verify and sign in","\u9A8C\u8BC1\u5E76\u767B\u5F55","\u9A57\u8B49\u4E26\u767B\u5165");logout.textContent=t("Sign out","\u9000\u51FA\u767B\u5F55","\u767B\u51FA");for(const node of[email,send,code,verify,el(".account-email-label"),el(".account-code-label")])node.hidden=signed;logout.hidden=!signed;send.disabled=busy||Date.now()<cooldown;verify.disabled=busy||requestedEmail!==email.value.trim();logout.disabled=busy}async function action(work){if(busy)return;busy=true;message.textContent="";render();try{await work()}catch(error){message.textContent=error.message}finally{busy=false;code.value="";render()}}const open=async()=>{await statusReady;if(hosted&&status.state!=="signed_in"){location.assign("/account");return}menu.hidden=true;render();dialog.showModal();if(status.state!=="signed_in")email.focus()};trigger.addEventListener("click",open);addEventListener("zortex-account-open",open);el(".account-close").addEventListener("click",()=>dialog.close());email.addEventListener("input",render);send.addEventListener("click",()=>{if(!email.reportValidity())return;void action(async()=>{const address=email.value.trim();await api("request",{email:address});requestedEmail=address;cooldown=Date.now()+6e4;message.textContent=t("Code sent. It expires in 10 minutes.","\u9A8C\u8BC1\u7801\u5DF2\u53D1\u9001\uFF0C10 \u5206\u949F\u5185\u6709\u6548\u3002","\u5DF2\u50B3\u9001\u9A57\u8B49\u78BC\uFF0C10 \u5206\u9418\u5167\u6709\u6548\u3002");code.focus();setTimeout(render,6e4)})});form.addEventListener("submit",event=>{event.preventDefault();if(requestedEmail!==email.value.trim()||!/^\d{8}$/.test(code.value)){message.textContent=t("Request a code, then enter its eight digits.","\u8BF7\u5148\u53D1\u9001\u9A8C\u8BC1\u7801\uFF0C\u518D\u8F93\u5165\u516B\u4F4D\u6570\u5B57\u3002","\u8ACB\u5148\u50B3\u9001\u9A57\u8B49\u78BC\uFF0C\u518D\u8F38\u5165\u516B\u4F4D\u6578\u5B57\u3002");return}const entered=code.value;void action(async()=>{status=await api("verify",{code:entered});requestedEmail="";email.value="";message.textContent=t("Signed in.","\u767B\u5F55\u6210\u529F\u3002","\u767B\u5165\u6210\u529F\u3002")})});logout.addEventListener("click",()=>void action(async()=>{const hosted2=status.hosted===true;await api("logout",{});if(hosted2){location.assign("/account");return}status=await api("status");requestedEmail="";message.textContent=t("Signed out.","\u5DF2\u9000\u51FA\u767B\u5F55\u3002","\u5DF2\u767B\u51FA\u3002")}));render();const statusReady=api("status").then(value=>{status=value;render()}).catch(()=>{})})();
|