@zortexhq/indra-v2.5 0.4.0 → 0.4.1

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.
Files changed (32) hide show
  1. package/dist/auto-sync.js +1 -1
  2. package/dist/content-find.js +1 -1
  3. package/dist/gateway.js +1 -1
  4. package/dist/public-tool.js +1 -1
  5. package/dist/read-route.js +1 -1
  6. package/dist/resident-platform.js +1 -1
  7. package/node_modules/@zortexhq/plugin-connector-activitywatch/dist/provider.js +1 -1
  8. package/node_modules/@zortexhq/plugin-connector-core/dist/api/connectors.js +1 -1
  9. package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -0
  10. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  11. package/node_modules/@zortexhq/plugin-connector-level1/dist/action-content.js +1 -0
  12. package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/content.js +1 -0
  13. package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/specs.js +1 -1
  14. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  15. package/node_modules/@zortexhq/plugin-connector-netease/dist/provider.js +1 -1
  16. package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
  17. package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
  18. package/node_modules/@zortexhq/plugin-connector-outlook/dist/mail-sync.js +1 -1
  19. package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
  20. package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
  21. package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
  22. package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
  23. package/node_modules/@zortexhq/plugin-connector-youtube/dist/content.js +1 -0
  24. package/node_modules/@zortexhq/plugin-connector-youtube/dist/full-sync.js +1 -1
  25. package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
  26. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/content-acquisition.js +1 -0
  27. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  28. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -0
  29. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  30. package/package.json +6 -6
  31. package/release-provenance.json +22 -22
  32. package/update-manifest.json +108 -72
@@ -1 +1 @@
1
- import{randomUUID}from"node:crypto";import makeWASocket,{Browsers,DisconnectReason,fetchLatestBaileysVersion,jidDecode}from"baileys";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{sessionStore}from"./auth-state.js";import{toRecords}from"./messages.js";import{openPairingPage}from"./pairing-page.js";import{TransientMessageBuffer,TRANSIENT_MESSAGE_LIMIT}from"./transient-buffer.js";export const SOURCE="whatsapp-web";const silent={level:"silent",child:()=>silent,trace(){},debug(){},info(){},warn(){},error(){},fatal(){}};async function defaultSocket(auth,fullHistory){const version=await Promise.race([fetchLatestBaileysVersion().then(r=>r.version).catch(()=>void 0),new Promise(resolve=>setTimeout(resolve,5e3))]);return makeWASocket({auth,logger:silent,browser:Browsers.macOS("Chrome"),syncFullHistory:fullHistory,markOnlineOnConnect:false,...version?{version}:{}})}const statusCode=update=>update.lastDisconnect?.error?.output?.statusCode;function nativeAccount(socket){const identity=jidDecode(socket?.user?.id);return identity?.server==="s.whatsapp.net"&&/^[1-9][0-9]{4,19}$/u.test(identity.user)?identity.user:void 0}export function createWhatsappProvider({vault,socket,pairingPage=openPairingPage,openUrl=openConnectionUrl,payloadRetention="cache",pairingTimeoutMs=18e4,resumeTimeoutMs=2e4,historyTimeoutMs=3e4}){if(!["cache","transient"].includes(payloadRetention)||[pairingTimeoutMs,resumeTimeoutMs,historyTimeoutMs].some(ms=>!Number.isInteger(ms)||ms<1||ms>6e5))throw Error("Invalid WhatsApp retention or timeout configuration.");const transient=payloadRetention==="transient",makeSocket=socket??(auth=>defaultSocket(auth,!transient));const info={source:SOURCE,label:"WhatsApp",group:"Connector / Chat",auth:"native-browser"};const jobs=new Map,names=new Map,buffer=new TransientMessageBuffer,pairings=new Set;const initializing=new Set;let live,resuming,closed=false,closing;let writes=Promise.resolve(),persistTimer;const fail=(code,message)=>businessError(code,message,"plugin");const enqueue=task=>{writes=writes.then(task,task).catch(()=>void 0);return writes};const track=task=>{initializing.add(task);void task.then(()=>initializing.delete(task),()=>initializing.delete(task));return task};const notify=entry=>{for(const wake of entry.waiters)wake()};const owned=(entry,sock=entry.socket)=>!closed&&!entry.stopped&&live===entry&&entry.socket===sock;function remember(jid,name){if(!jid||jid.length>512||!name)return;names.delete(jid);names.set(jid,name.slice(0,256));if(names.size>2e3)names.delete(names.keys().next().value)}function stopLive(entry){entry.stopped=true;entry.online=false;entry.resolveOpen(false);notify(entry);entry.socket?.end();if(live===entry){live=void 0;buffer.clear();names.clear()}}function waitUntil(entry,predicate,timeout,signal){if(predicate())return Promise.resolve(true);if(signal?.aborted||closed||entry.stopped)return Promise.resolve(false);return new Promise(resolve=>{const finish=value=>{clearTimeout(timer);entry.waiters.delete(wake);signal?.removeEventListener("abort",abort);resolve(value)};const wake=()=>{if(predicate())finish(true);else if(closed||entry.stopped)finish(false)};const abort=()=>finish(false),timer=setTimeout(()=>finish(false),timeout);entry.waiters.add(wake);signal?.addEventListener("abort",abort,{once:true});wake()})}async function captureAuthority(accountId){const custody=vault.bindingCustody;if(!custody)return transient?fail("failed_precondition","Transient WhatsApp requires durable native account custody."):ok(void 0);const selected=await custody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return fail("failed_precondition","WhatsApp needs one explicit native account binding.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(selected.ok.binding.id),{purpose:"L1",audience:SOURCE});if(!("ok"in current))return current;const value=current.ok;if(value.binding.identity.source!==SOURCE||value.binding.identity.issuer!==SOURCE||value.binding.identity.subject!==accountId||value.binding.identity.tenant!==null||value.material.kind!=="oauth"||value.resource.kind!=="oauth"||value.resource.owner.kind!=="resident"||value.material.credential.clientId!=="whatsapp-linked-device"||!value.grant.scopes.includes("messages.read"))return fail("permission_denied","WhatsApp session custody does not match the selected native account.");return ok({binding:value.binding,grant:value.grant,resource:value.resource})}async function checkAuthority(entry){if(!entry.accountId||nativeAccount(entry.socket)!==entry.accountId)return fail("failed_precondition","WhatsApp signed-in account changed. Reconnect the selected account.");const current=await captureAuthority(entry.accountId);if(!("ok"in current))return current;const expected=entry.authority,latest=current.ok;if(expected&&(!latest||latest.binding.id!==expected.binding.id||latest.binding.revision!==expected.binding.revision||latest.grant.id!==expected.grant.id||latest.grant.revision!==expected.grant.revision||latest.grant.scopeEpoch!==expected.grant.scopeEpoch||latest.resource.id!==expected.resource.id))return fail("permission_denied","WhatsApp account permission changed while the operation was pending.");return ok(latest)}async function persistNow(entry){if(!entry.accountId||!entry.online||entry.stopped)return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}if(entry.stopped||!entry.online)return;const credential={accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]};const saved=allowed.ok&&vault.bindingCustody?await vault.bindingCustody.compareAndSwapResource({...allowed.ok.resource,updatedAt:new Date().toISOString()},{kind:"oauth",credential},allowed.ok.resource.revision):await vault.updateCredential(SOURCE,credential);if(!("ok"in saved))stopLive(entry)}function persist(entry){if(!owned(entry)||!entry.accountId)return;clearTimeout(persistTimer);persistTimer=setTimeout(()=>{void enqueue(()=>persistNow(entry))},1e3);persistTimer.unref?.()}function store(entry,sock,messages,history=false){if(!owned(entry,sock)||!entry.accountId||nativeAccount(sock)!==entry.accountId||transient&&!entry.online)return;if(transient){for(const message of messages)for(const record of toRecords(entry.accountId,[message],jid=>names.get(jid)))buffer.add(record);if(history||messages.length>0)entry.historyArrived=true;notify(entry);return}const records=toRecords(entry.accountId,messages,jid=>names.get(jid));for(let i=0;i<records.length;i+=100){const batch=records.slice(i,i+100);void enqueue(async()=>{if(!await entry.open||!owned(entry,sock))return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}await cache(vault,SOURCE,batch);entry.historyArrived=true;notify(entry)})}}async function markLoggedOut(entry){if(!entry.accountId)return;if(vault.bindingCustody&&entry.authority){const current=await vault.bindingCustody.binding(entry.authority.binding.id);if("ok"in current&&current.ok?.revision===entry.authority.binding.revision)await vault.bindingCustody.compareAndSwapBinding({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},current.ok.revision)}else{const current=await vault.connection(SOURCE);if("ok"in current&&current.ok?.accountId===entry.accountId)await vault.saveConnection({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},{accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]})}}async function start(stateStore,accountId,authority,onView,onOpen,onFailure){if(closed)throw Error("inactive");let resolveOpen;const open=new Promise(resolve=>{resolveOpen=resolve});const current={store:stateStore,open,resolveOpen,...accountId?{accountId}:{},...authority?{authority}:{},online:false,stopped:false,historyArrived:false,needsPairing:false,waiters:new Set};live=current;buffer.clear();names.clear();let restarts=0,generation=0;const failed=code=>{current.failure=code;stopLive(current);onFailure?.(code)};const connect=async()=>{if(!owned(current))return;const attempt=++generation,previous=current.socket;delete current.socket;previous?.end();const sock=await track(makeSocket(current.store.state));if(!owned(current)||attempt!==generation){sock.end();return}current.socket=sock;sock.ev.on("creds.update",()=>{if(owned(current,sock))persist(current)});sock.ev.on("connection.update",update=>{if(!owned(current,sock))return;if(update.qr){current.needsPairing=true;onView?.({state:"qr",qr:update.qr});notify(current)}if(update.connection==="open"){const linked=nativeAccount(sock);if(!linked||current.accountId&&current.accountId!==linked){failed("account_changed");return}current.accountId=linked;void(async()=>{const completed=await onOpen?.(current);if(!owned(current,sock))return;const captured=current.authority?await checkAuthority(current):await captureAuthority(linked);if(!("ok"in captured)){failed("account_permission_changed");return}if(!owned(current,sock))return;if(!current.authority)current.authority=captured.ok;current.online=true;current.needsPairing=false;restarts=0;resolveOpen(true);notify(current);completed?.()})().catch(()=>failed("pairing_unavailable"))}if(update.connection==="close"){current.online=false;notify(current);const code=statusCode(update);if(code===DisconnectReason.loggedOut){current.needsPairing=true;void enqueue(()=>markLoggedOut(current));failed("qr_scan_required");return}if(code!==DisconnectReason.connectionReplaced&&restarts++<5){void connect().catch(()=>failed("connection_unavailable"));return}failed("connection_unavailable")}});sock.ev.on("messaging-history.set",({chats,contacts,messages})=>{if(!owned(current,sock))return;for(const chat of chats)remember(chat.id,chat.name);for(const contact of contacts)remember(contact.id,contact.name??contact.notify);store(current,sock,messages,true)});sock.ev.on("chats.upsert",chats=>{if(owned(current,sock))for(const chat of chats)remember(chat.id,chat.name)});sock.ev.on("contacts.upsert",contacts=>{if(owned(current,sock))for(const contact of contacts)remember(contact.id,contact.name??contact.notify)});sock.ev.on("messages.upsert",({messages})=>{if(!owned(current,sock))return;for(const message of messages)if(!message.key.fromMe)remember(message.key.remoteJid,message.key.remoteJid?.endsWith("@g.us")?void 0:message.pushName);store(current,sock,messages)})};try{await connect()}catch(error){failed("connection_unavailable");throw error}return current}async function resume(){if(live&&!live.stopped)return live;if(resuming)return resuming;resuming=(async()=>{const connection=await vault.connection(SOURCE);if(!("ok"in connection))throw Error("account_permission_changed");if(connection.ok?.state!=="connected"||!connection.ok.accountId)return void 0;const grant=await vault.credential(SOURCE);if(!("ok"in grant))throw Error("account_permission_changed");const authority=await captureAuthority(connection.ok.accountId);if(!("ok"in authority))throw Error("account_permission_changed");const restored=sessionStore(grant.ok.accessToken,()=>{if(live)persist(live)});return start(restored,connection.ok.accountId,authority.ok)})();try{return await resuming}finally{resuming=void 0}}function cleanPairing(pair2){clearTimeout(pair2.timer);pair2.removeAbort?.();pair2.page?.close();pairings.delete(pair2)}function failPairing(pair2,code,message){if(pair2.job.state==="waiting-user"){pair2.job.state="failed";pair2.job.error={code,message};delete pair2.job.authorizationUrl;delete pair2.job.instructions;pair2.stop.abort();pair2.page?.update({state:"failed",message});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live)}cleanPairing(pair2)}function cancelPairing(pair2){if(pair2.job.state==="waiting-user")pair2.job.state="cancelled";delete pair2.job.authorizationUrl;delete pair2.job.instructions;delete pair2.job.error;pair2.stop.abort();pair2.page?.update({state:"failed",message:"WhatsApp connection was cancelled."});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live);cleanPairing(pair2)}async function pair(job,options,expectedAccountId){if(closed)throw Error("inactive");const owner={job,stop:new AbortController};pairings.add(owner);const abort=()=>failPairing(owner,"aborted","WhatsApp connection was cancelled.");options.signal?.addEventListener("abort",abort,{once:true});owner.removeAbort=()=>options.signal?.removeEventListener("abort",abort);try{owner.page=await pairingPage();if(closed||options.signal?.aborted||owner.stop.signal.aborted){abort();return}job.authorizationUrl=owner.page.url;job.instructions="Open the QR code page, then use WhatsApp on your phone: Settings \u2192 Linked devices \u2192 Link a device. The connection continues automatically after scanning.";job.error={code:"qr_scan_required",message:"Scan the WhatsApp QR code with your phone."};owner.timer=setTimeout(()=>failPairing(owner,"pairing_timeout","WhatsApp QR was not scanned before it expired."),pairingTimeoutMs);owner.timer.unref?.();const fresh=sessionStore(void 0,()=>{if(owner.entry)persist(owner.entry)});if(live)stopLive(live);owner.entry=await start(fresh,expectedAccountId,void 0,view=>{if(job.state==="waiting-user")owner.page?.update(view)},async current=>{if(job.state==="connected"&&!closed)return;if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)throw Error("aborted");const saved=await vault.saveConnection({source:SOURCE,provider:SOURCE,account:current.socket?.user?.name?.slice(0,256)||"WhatsApp",accountId:current.accountId,scopes:["messages.read"],state:"connected",updatedAt:new Date().toISOString()},{accessToken:current.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]},{signal:owner.stop.signal});if(!("ok"in saved))throw Error("custody_failed");return()=>{if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)return;clearTimeout(owner.timer);owner.removeAbort?.();job.state="connected";job.account=saved.ok.account;delete job.instructions;delete job.authorizationUrl;delete job.error;owner.page?.update({state:"connected"});owner.timer=setTimeout(()=>cleanPairing(owner),1e4);owner.timer.unref?.()}},code=>failPairing(owner,code,code==="account_changed"?"The scanned WhatsApp account does not match the selected account.":"WhatsApp pairing did not complete."));if(owner.stop.signal.aborted)stopLive(owner.entry);if(!options.automatic&&options.manualPresentation!=="return-url"&&job.state==="waiting-user")await openUrl(owner.page.url)}catch{failPairing(owner,"pairing_unavailable","WhatsApp pairing page or connection could not start.")}}return{info,...transient?{}:{requiresPersistentPayloads:true},status:()=>connectionState(vault,info),job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","WhatsApp connection job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const pairing=[...pairings].find(owner=>owner.job===job);if(pairing)cancelPairing(pairing);else if(job.state==="waiting-user")job.state="cancelled";delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:[...pairings].some(owner=>owner.job===job)?"pending":"confirmed"})},async connect(options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");const running=[...jobs.values()].find(job2=>job2.state==="waiting-user");if(running)return ok({...running});for(const[id,job2]of jobs)if(jobs.size>=32&&job2.state!=="waiting-user")jobs.delete(id);const job={id:randomUUID(),source:SOURCE,state:"waiting-user",startedAt:new Date().toISOString()};jobs.set(job.id,job);try{const selected=await vault.connection(SOURCE);if(!("ok"in selected))return selected;if(selected.ok&&!selected.ok.accountId)return fail("failed_precondition","WhatsApp needs a verified native account binding.");if(options.expectedBinding?.kind==="legacy-source"&&options.expectedBinding.source!==SOURCE)return fail("invalid_argument","WhatsApp account selection names another source.");if(options.expectedBinding?.kind==="binding"){const binding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in binding)||binding.ok.kind!=="resolved"||binding.ok.binding.id!==options.expectedBinding.bindingId)return fail("failed_precondition","WhatsApp account selection does not match this linked device.")}if(closed)return fail("unavailable","WhatsApp source is inactive.");const resumed=await track(resume());if(resumed){await waitUntil(resumed,()=>resumed.online||resumed.needsPairing,resumeTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");if(resumed.online){const allowed=await checkAuthority(resumed);if(!("ok"in allowed))return allowed;job.state="connected";if(selected.ok)job.account=selected.ok.account;return ok({...job})}if(!resumed.needsPairing){job.state="failed";job.error={code:resumed.failure??"connection_unavailable",message:resumed.failure==="account_changed"?"WhatsApp signed in as a different account.":"The existing WhatsApp session did not reconnect."};return ok({...job})}}if(options.automatic&&!transient){job.state="failed";job.error={code:"qr_scan_required",message:"WhatsApp needs one QR scan from the phone; connect it explicitly."};return ok({...job})}if(options.automatic&&selected.ok?.accountId&&vault.bindingCustody){const selectedBinding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if("ok"in selectedBinding&&selectedBinding.ok.kind==="resolved"){const grant=await vault.bindingCustody.grantForBinding(selectedBinding.ok.binding.id,"L1",SOURCE);if(!("ok"in grant))return grant;if(grant.ok?.state==="revoked")return fail("permission_denied","WhatsApp access was revoked. Reconnect explicitly to grant it again.")}}await track(pair(job,options,selected.ok?.accountId))}catch{job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp session permission or connection could not be verified."}}finally{if(job.state==="waiting-user"&&![...pairings].some(owner=>owner.job===job)){job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp did not start an owned connection job."}}}return ok({...job})},async read(request,options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;if(request.fileId!==void 0)return fail("invalid_argument","WhatsApp message reads support limit, query and time filters; file download is not supported.");if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const connection=await vault.connection(SOURCE);if(!("ok"in connection))return connection;if(connection.ok?.state!=="connected"||!connection.ok.accountId)return fail("unauthenticated","Connect WhatsApp by scanning its QR code first.");const session=await track(resume()).catch(()=>void 0);const online=session?await waitUntil(session,()=>session.online,resumeTimeoutMs,options.signal):false;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const warnings=[];let records;if(transient){if(!online||!session)return fail("unavailable","WhatsApp is offline; transient reads need the selected live session.");const allowed=await checkAuthority(session);if(!("ok"in allowed)){stopLive(session);return allowed}await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");if(!owned(session)||!session.online)return fail("unavailable","WhatsApp session ended before the message read.");const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(!session.historyArrived)return fail("unavailable","No live WhatsApp message batch has arrived for this session yet. Retry after the phone finishes linking or a message arrives.");records=buffer.snapshot();warnings.push(`This live session retains at most ${TRANSIENT_MESSAGE_LIMIT} messages and 4 MiB in memory. Messages are not saved and are cleared on restart.`)}else{if(!online)warnings.push("WhatsApp is offline right now; showing messages already saved in the Vault.");if(online&&session&&!session.historyArrived){const stored2=await vault.records(SOURCE,1);if(!("ok"in stored2)||!stored2.ok.length)await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal)}await writes;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const stored=await vault.records(SOURCE,100);if(!("ok"in stored))return stored;records=stored.ok.map(row=>row.data);if(request.query||request.since||request.until)warnings.push("Filters apply to the 100 most recent saved messages; use SQL search over z_records for older history.")}const since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity,query=request.query?.toLowerCase();records=records.filter(record=>record.sourceId?.startsWith(connection.ok.accountId+":")).filter(record=>{const at=Date.parse(record.ts??"");return at>=since&&at<=until}).filter(record=>!query||`${record.body} ${record.fields?.chat??""}`.toLowerCase().includes(query)).slice(0,request.limit??1);if(transient&&session){const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(closed||!owned(session)||options.signal?.aborted)return fail("aborted","WhatsApp read was cancelled before delivery.")}return readResult(SOURCE,records,warnings)},close(){if(closing)return closing;closing=(async()=>{closed=true;clearTimeout(persistTimer);for(const owner of[...pairings]){if(owner.job.state==="waiting-user")failPairing(owner,"aborted","WhatsApp source was closed.");else cleanPairing(owner)}await Promise.allSettled([...initializing]);await writes;if(live){const current=live;await persistNow(current).catch(()=>void 0);stopLive(current)}buffer.clear();names.clear()})();return closing}}}
1
+ import{acquiredReadCapability,unreviewedActionContent}from"@zortexhq/plugin-connector-core/api";import{randomUUID}from"node:crypto";import makeWASocket,{Browsers,DisconnectReason,fetchLatestBaileysVersion,jidDecode}from"baileys";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{sessionStore}from"./auth-state.js";import{toRecords}from"./messages.js";import{openPairingPage}from"./pairing-page.js";import{TransientMessageBuffer,TRANSIENT_MESSAGE_LIMIT}from"./transient-buffer.js";export const SOURCE="whatsapp-web";const silent={level:"silent",child:()=>silent,trace(){},debug(){},info(){},warn(){},error(){},fatal(){}};async function defaultSocket(auth,fullHistory){const version=await Promise.race([fetchLatestBaileysVersion().then(r=>r.version).catch(()=>void 0),new Promise(resolve=>setTimeout(resolve,5e3))]);return makeWASocket({auth,logger:silent,browser:Browsers.macOS("Chrome"),syncFullHistory:fullHistory,markOnlineOnConnect:false,...version?{version}:{}})}const statusCode=update=>update.lastDisconnect?.error?.output?.statusCode;function nativeAccount(socket){const identity=jidDecode(socket?.user?.id);return identity?.server==="s.whatsapp.net"&&/^[1-9][0-9]{4,19}$/u.test(identity.user)?identity.user:void 0}export function createWhatsappProvider({vault,socket,pairingPage=openPairingPage,openUrl=openConnectionUrl,payloadRetention="cache",pairingTimeoutMs=18e4,resumeTimeoutMs=2e4,historyTimeoutMs=3e4}){if(!["cache","transient"].includes(payloadRetention)||[pairingTimeoutMs,resumeTimeoutMs,historyTimeoutMs].some(ms=>!Number.isInteger(ms)||ms<1||ms>6e5))throw Error("Invalid WhatsApp retention or timeout configuration.");const transient=payloadRetention==="transient",makeSocket=socket??(auth=>defaultSocket(auth,!transient));const info={content:[acquiredReadCapability(["plugins/connector-whatsapp/README.md"]),unreviewedActionContent(["plugins/connector-whatsapp/README.md"])],source:SOURCE,label:"WhatsApp",group:"Connector / Chat",auth:"native-browser"};const jobs=new Map,names=new Map,buffer=new TransientMessageBuffer,pairings=new Set;const initializing=new Set;let live,resuming,closed=false,closing;let writes=Promise.resolve(),persistTimer;const fail=(code,message)=>businessError(code,message,"plugin");const enqueue=task=>{writes=writes.then(task,task).catch(()=>void 0);return writes};const track=task=>{initializing.add(task);void task.then(()=>initializing.delete(task),()=>initializing.delete(task));return task};const notify=entry=>{for(const wake of entry.waiters)wake()};const owned=(entry,sock=entry.socket)=>!closed&&!entry.stopped&&live===entry&&entry.socket===sock;function remember(jid,name){if(!jid||jid.length>512||!name)return;names.delete(jid);names.set(jid,name.slice(0,256));if(names.size>2e3)names.delete(names.keys().next().value)}function stopLive(entry){entry.stopped=true;entry.online=false;entry.resolveOpen(false);notify(entry);entry.socket?.end();if(live===entry){live=void 0;buffer.clear();names.clear()}}function waitUntil(entry,predicate,timeout,signal){if(predicate())return Promise.resolve(true);if(signal?.aborted||closed||entry.stopped)return Promise.resolve(false);return new Promise(resolve=>{const finish=value=>{clearTimeout(timer);entry.waiters.delete(wake);signal?.removeEventListener("abort",abort);resolve(value)};const wake=()=>{if(predicate())finish(true);else if(closed||entry.stopped)finish(false)};const abort=()=>finish(false),timer=setTimeout(()=>finish(false),timeout);entry.waiters.add(wake);signal?.addEventListener("abort",abort,{once:true});wake()})}async function captureAuthority(accountId){const custody=vault.bindingCustody;if(!custody)return transient?fail("failed_precondition","Transient WhatsApp requires durable native account custody."):ok(void 0);const selected=await custody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return fail("failed_precondition","WhatsApp needs one explicit native account binding.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(selected.ok.binding.id),{purpose:"L1",audience:SOURCE});if(!("ok"in current))return current;const value=current.ok;if(value.binding.identity.source!==SOURCE||value.binding.identity.issuer!==SOURCE||value.binding.identity.subject!==accountId||value.binding.identity.tenant!==null||value.material.kind!=="oauth"||value.resource.kind!=="oauth"||value.resource.owner.kind!=="resident"||value.material.credential.clientId!=="whatsapp-linked-device"||!value.grant.scopes.includes("messages.read"))return fail("permission_denied","WhatsApp session custody does not match the selected native account.");return ok({binding:value.binding,grant:value.grant,resource:value.resource})}async function checkAuthority(entry){if(!entry.accountId||nativeAccount(entry.socket)!==entry.accountId)return fail("failed_precondition","WhatsApp signed-in account changed. Reconnect the selected account.");const current=await captureAuthority(entry.accountId);if(!("ok"in current))return current;const expected=entry.authority,latest=current.ok;if(expected&&(!latest||latest.binding.id!==expected.binding.id||latest.binding.revision!==expected.binding.revision||latest.grant.id!==expected.grant.id||latest.grant.revision!==expected.grant.revision||latest.grant.scopeEpoch!==expected.grant.scopeEpoch||latest.resource.id!==expected.resource.id))return fail("permission_denied","WhatsApp account permission changed while the operation was pending.");return ok(latest)}async function persistNow(entry){if(!entry.accountId||!entry.online||entry.stopped)return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}if(entry.stopped||!entry.online)return;const credential={accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]};const saved=allowed.ok&&vault.bindingCustody?await vault.bindingCustody.compareAndSwapResource({...allowed.ok.resource,updatedAt:new Date().toISOString()},{kind:"oauth",credential},allowed.ok.resource.revision):await vault.updateCredential(SOURCE,credential);if(!("ok"in saved))stopLive(entry)}function persist(entry){if(!owned(entry)||!entry.accountId)return;clearTimeout(persistTimer);persistTimer=setTimeout(()=>{void enqueue(()=>persistNow(entry))},1e3);persistTimer.unref?.()}function store(entry,sock,messages,history=false){if(!owned(entry,sock)||!entry.accountId||nativeAccount(sock)!==entry.accountId||transient&&!entry.online)return;if(transient){for(const message of messages)for(const record of toRecords(entry.accountId,[message],jid=>names.get(jid)))buffer.add(record);if(history||messages.length>0)entry.historyArrived=true;notify(entry);return}const records=toRecords(entry.accountId,messages,jid=>names.get(jid));for(let i=0;i<records.length;i+=100){const batch=records.slice(i,i+100);void enqueue(async()=>{if(!await entry.open||!owned(entry,sock))return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}await cache(vault,SOURCE,batch);entry.historyArrived=true;notify(entry)})}}async function markLoggedOut(entry){if(!entry.accountId)return;if(vault.bindingCustody&&entry.authority){const current=await vault.bindingCustody.binding(entry.authority.binding.id);if("ok"in current&&current.ok?.revision===entry.authority.binding.revision)await vault.bindingCustody.compareAndSwapBinding({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},current.ok.revision)}else{const current=await vault.connection(SOURCE);if("ok"in current&&current.ok?.accountId===entry.accountId)await vault.saveConnection({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},{accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]})}}async function start(stateStore,accountId,authority,onView,onOpen,onFailure){if(closed)throw Error("inactive");let resolveOpen;const open=new Promise(resolve=>{resolveOpen=resolve});const current={store:stateStore,open,resolveOpen,...accountId?{accountId}:{},...authority?{authority}:{},online:false,stopped:false,historyArrived:false,needsPairing:false,waiters:new Set};live=current;buffer.clear();names.clear();let restarts=0,generation=0;const failed=code=>{current.failure=code;stopLive(current);onFailure?.(code)};const connect=async()=>{if(!owned(current))return;const attempt=++generation,previous=current.socket;delete current.socket;previous?.end();const sock=await track(makeSocket(current.store.state));if(!owned(current)||attempt!==generation){sock.end();return}current.socket=sock;sock.ev.on("creds.update",()=>{if(owned(current,sock))persist(current)});sock.ev.on("connection.update",update=>{if(!owned(current,sock))return;if(update.qr){current.needsPairing=true;onView?.({state:"qr",qr:update.qr});notify(current)}if(update.connection==="open"){const linked=nativeAccount(sock);if(!linked||current.accountId&&current.accountId!==linked){failed("account_changed");return}current.accountId=linked;void(async()=>{const completed=await onOpen?.(current);if(!owned(current,sock))return;const captured=current.authority?await checkAuthority(current):await captureAuthority(linked);if(!("ok"in captured)){failed("account_permission_changed");return}if(!owned(current,sock))return;if(!current.authority)current.authority=captured.ok;current.online=true;current.needsPairing=false;restarts=0;resolveOpen(true);notify(current);completed?.()})().catch(()=>failed("pairing_unavailable"))}if(update.connection==="close"){current.online=false;notify(current);const code=statusCode(update);if(code===DisconnectReason.loggedOut){current.needsPairing=true;void enqueue(()=>markLoggedOut(current));failed("qr_scan_required");return}if(code!==DisconnectReason.connectionReplaced&&restarts++<5){void connect().catch(()=>failed("connection_unavailable"));return}failed("connection_unavailable")}});sock.ev.on("messaging-history.set",({chats,contacts,messages})=>{if(!owned(current,sock))return;for(const chat of chats)remember(chat.id,chat.name);for(const contact of contacts)remember(contact.id,contact.name??contact.notify);store(current,sock,messages,true)});sock.ev.on("chats.upsert",chats=>{if(owned(current,sock))for(const chat of chats)remember(chat.id,chat.name)});sock.ev.on("contacts.upsert",contacts=>{if(owned(current,sock))for(const contact of contacts)remember(contact.id,contact.name??contact.notify)});sock.ev.on("messages.upsert",({messages})=>{if(!owned(current,sock))return;for(const message of messages)if(!message.key.fromMe)remember(message.key.remoteJid,message.key.remoteJid?.endsWith("@g.us")?void 0:message.pushName);store(current,sock,messages)})};try{await connect()}catch(error){failed("connection_unavailable");throw error}return current}async function resume(){if(live&&!live.stopped)return live;if(resuming)return resuming;resuming=(async()=>{const connection=await vault.connection(SOURCE);if(!("ok"in connection))throw Error("account_permission_changed");if(connection.ok?.state!=="connected"||!connection.ok.accountId)return void 0;const grant=await vault.credential(SOURCE);if(!("ok"in grant))throw Error("account_permission_changed");const authority=await captureAuthority(connection.ok.accountId);if(!("ok"in authority))throw Error("account_permission_changed");const restored=sessionStore(grant.ok.accessToken,()=>{if(live)persist(live)});return start(restored,connection.ok.accountId,authority.ok)})();try{return await resuming}finally{resuming=void 0}}function cleanPairing(pair2){clearTimeout(pair2.timer);pair2.removeAbort?.();pair2.page?.close();pairings.delete(pair2)}function failPairing(pair2,code,message){if(pair2.job.state==="waiting-user"){pair2.job.state="failed";pair2.job.error={code,message};delete pair2.job.authorizationUrl;delete pair2.job.instructions;pair2.stop.abort();pair2.page?.update({state:"failed",message});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live)}cleanPairing(pair2)}function cancelPairing(pair2){if(pair2.job.state==="waiting-user")pair2.job.state="cancelled";delete pair2.job.authorizationUrl;delete pair2.job.instructions;delete pair2.job.error;pair2.stop.abort();pair2.page?.update({state:"failed",message:"WhatsApp connection was cancelled."});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live);cleanPairing(pair2)}async function pair(job,options,expectedAccountId){if(closed)throw Error("inactive");const owner={job,stop:new AbortController};pairings.add(owner);const abort=()=>failPairing(owner,"aborted","WhatsApp connection was cancelled.");options.signal?.addEventListener("abort",abort,{once:true});owner.removeAbort=()=>options.signal?.removeEventListener("abort",abort);try{owner.page=await pairingPage();if(closed||options.signal?.aborted||owner.stop.signal.aborted){abort();return}job.authorizationUrl=owner.page.url;job.instructions="Open the QR code page, then use WhatsApp on your phone: Settings \u2192 Linked devices \u2192 Link a device. The connection continues automatically after scanning.";job.error={code:"qr_scan_required",message:"Scan the WhatsApp QR code with your phone."};owner.timer=setTimeout(()=>failPairing(owner,"pairing_timeout","WhatsApp QR was not scanned before it expired."),pairingTimeoutMs);owner.timer.unref?.();const fresh=sessionStore(void 0,()=>{if(owner.entry)persist(owner.entry)});if(live)stopLive(live);owner.entry=await start(fresh,expectedAccountId,void 0,view=>{if(job.state==="waiting-user")owner.page?.update(view)},async current=>{if(job.state==="connected"&&!closed)return;if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)throw Error("aborted");const saved=await vault.saveConnection({source:SOURCE,provider:SOURCE,account:current.socket?.user?.name?.slice(0,256)||"WhatsApp",accountId:current.accountId,scopes:["messages.read"],state:"connected",updatedAt:new Date().toISOString()},{accessToken:current.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]},{signal:owner.stop.signal});if(!("ok"in saved))throw Error("custody_failed");return()=>{if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)return;clearTimeout(owner.timer);owner.removeAbort?.();job.state="connected";job.account=saved.ok.account;delete job.instructions;delete job.authorizationUrl;delete job.error;owner.page?.update({state:"connected"});owner.timer=setTimeout(()=>cleanPairing(owner),1e4);owner.timer.unref?.()}},code=>failPairing(owner,code,code==="account_changed"?"The scanned WhatsApp account does not match the selected account.":"WhatsApp pairing did not complete."));if(owner.stop.signal.aborted)stopLive(owner.entry);if(!options.automatic&&options.manualPresentation!=="return-url"&&job.state==="waiting-user")await openUrl(owner.page.url)}catch{failPairing(owner,"pairing_unavailable","WhatsApp pairing page or connection could not start.")}}return{info,...transient?{}:{requiresPersistentPayloads:true},status:()=>connectionState(vault,info),job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","WhatsApp connection job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const pairing=[...pairings].find(owner=>owner.job===job);if(pairing)cancelPairing(pairing);else if(job.state==="waiting-user")job.state="cancelled";delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:[...pairings].some(owner=>owner.job===job)?"pending":"confirmed"})},async connect(options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");const running=[...jobs.values()].find(job2=>job2.state==="waiting-user");if(running)return ok({...running});for(const[id,job2]of jobs)if(jobs.size>=32&&job2.state!=="waiting-user")jobs.delete(id);const job={id:randomUUID(),source:SOURCE,state:"waiting-user",startedAt:new Date().toISOString()};jobs.set(job.id,job);try{const selected=await vault.connection(SOURCE);if(!("ok"in selected))return selected;if(selected.ok&&!selected.ok.accountId)return fail("failed_precondition","WhatsApp needs a verified native account binding.");if(options.expectedBinding?.kind==="legacy-source"&&options.expectedBinding.source!==SOURCE)return fail("invalid_argument","WhatsApp account selection names another source.");if(options.expectedBinding?.kind==="binding"){const binding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in binding)||binding.ok.kind!=="resolved"||binding.ok.binding.id!==options.expectedBinding.bindingId)return fail("failed_precondition","WhatsApp account selection does not match this linked device.")}if(closed)return fail("unavailable","WhatsApp source is inactive.");const resumed=await track(resume());if(resumed){await waitUntil(resumed,()=>resumed.online||resumed.needsPairing,resumeTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");if(resumed.online){const allowed=await checkAuthority(resumed);if(!("ok"in allowed))return allowed;job.state="connected";if(selected.ok)job.account=selected.ok.account;return ok({...job})}if(!resumed.needsPairing){job.state="failed";job.error={code:resumed.failure??"connection_unavailable",message:resumed.failure==="account_changed"?"WhatsApp signed in as a different account.":"The existing WhatsApp session did not reconnect."};return ok({...job})}}if(options.automatic&&!transient){job.state="failed";job.error={code:"qr_scan_required",message:"WhatsApp needs one QR scan from the phone; connect it explicitly."};return ok({...job})}if(options.automatic&&selected.ok?.accountId&&vault.bindingCustody){const selectedBinding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if("ok"in selectedBinding&&selectedBinding.ok.kind==="resolved"){const grant=await vault.bindingCustody.grantForBinding(selectedBinding.ok.binding.id,"L1",SOURCE);if(!("ok"in grant))return grant;if(grant.ok?.state==="revoked")return fail("permission_denied","WhatsApp access was revoked. Reconnect explicitly to grant it again.")}}await track(pair(job,options,selected.ok?.accountId))}catch{job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp session permission or connection could not be verified."}}finally{if(job.state==="waiting-user"&&![...pairings].some(owner=>owner.job===job)){job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp did not start an owned connection job."}}}return ok({...job})},async read(request,options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;if(request.fileId!==void 0)return fail("invalid_argument","WhatsApp message reads support limit, query and time filters; file download is not supported.");if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const connection=await vault.connection(SOURCE);if(!("ok"in connection))return connection;if(connection.ok?.state!=="connected"||!connection.ok.accountId)return fail("unauthenticated","Connect WhatsApp by scanning its QR code first.");const session=await track(resume()).catch(()=>void 0);const online=session?await waitUntil(session,()=>session.online,resumeTimeoutMs,options.signal):false;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const warnings=[];let records;if(transient){if(!online||!session)return fail("unavailable","WhatsApp is offline; transient reads need the selected live session.");const allowed=await checkAuthority(session);if(!("ok"in allowed)){stopLive(session);return allowed}await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");if(!owned(session)||!session.online)return fail("unavailable","WhatsApp session ended before the message read.");const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(!session.historyArrived)return fail("unavailable","No live WhatsApp message batch has arrived for this session yet. Retry after the phone finishes linking or a message arrives.");records=buffer.snapshot();warnings.push(`This live session retains at most ${TRANSIENT_MESSAGE_LIMIT} messages and 4 MiB in memory. Messages are not saved and are cleared on restart.`)}else{if(!online)warnings.push("WhatsApp is offline right now; showing messages already saved in the Vault.");if(online&&session&&!session.historyArrived){const stored2=await vault.records(SOURCE,1);if(!("ok"in stored2)||!stored2.ok.length)await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal)}await writes;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const stored=await vault.records(SOURCE,100);if(!("ok"in stored))return stored;records=stored.ok.map(row=>row.data);if(request.query||request.since||request.until)warnings.push("Filters apply to the 100 most recent saved messages; use SQL search over z_records for older history.")}const since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity,query=request.query?.toLowerCase();records=records.filter(record=>record.sourceId?.startsWith(connection.ok.accountId+":")).filter(record=>{const at=Date.parse(record.ts??"");return at>=since&&at<=until}).filter(record=>!query||`${record.body} ${record.fields?.chat??""}`.toLowerCase().includes(query)).slice(0,request.limit??1);if(transient&&session){const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(closed||!owned(session)||options.signal?.aborted)return fail("aborted","WhatsApp read was cancelled before delivery.")}return readResult(SOURCE,records,warnings)},close(){if(closing)return closing;closing=(async()=>{closed=true;clearTimeout(persistTimer);for(const owner of[...pairings]){if(owner.job.state==="waiting-user")failPairing(owner,"aborted","WhatsApp source was closed.");else cleanPairing(owner)}await Promise.allSettled([...initializing]);await writes;if(live){const current=live;await persistNow(current).catch(()=>void 0);stopLive(current)}buffer.clear();names.clear()})();return closing}}}
@@ -0,0 +1 @@
1
+ import{pinnedMethods}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";export const youtubeContent=[...["channels","subscriptions","playlists","playlistItems","videos","commentThreads"].map(resource=>({resource:`account/${resource}`,read:"implemented",acquisition:"collection",persistence:"durable",readFields:["selected-parts"],storedFields:["selected-parts"],updates:"rescan",evidence:["https://developers.google.com/youtube/v3/docs","src/full-sync.ts"],limitations:["Authorized account walk only; parts, quota and partialReasons bound coverage; inline comment replies are not complete reply history."]})),...[...pinnedMethods,...creatorMethods].filter(m=>m.httpMethod==="GET").map(m=>({resource:m.id,read:m.scopes?.length&&!m.id.endsWith(".stream")?"implemented":"unimplemented",acquisition:"lookup",persistence:"unimplemented",readFields:m.supportsMediaDownload?["content","mime"]:["data","items","nextPageToken"],storedFields:[],updates:"lookup",evidence:["src/discovery-data.ts","src/creator-data.ts","src/source.ts"],limitations:["Selected parameters, scopes and provider admission apply. No automatic durable path for this selected-method response."]})),...["personal-search-history","watch-history","watch-later","complete-authored-comment-history"].map(resource=>({resource,read:"unsupported",acquisition:"none",persistence:"not-applicable",readFields:[],storedFields:[],updates:"none",evidence:["src/full-sync.ts"],limitations:["Unavailable through the reviewed Data API path; explicit user exports are a separate acquisition path."]}))];
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{Original}from"@zortexhq/plugin-connector-framework/api";import{manifest as sourceManifest}from"./discovery-data.js";import{object}from"./schema.js";const READONLY="https://www.googleapis.com/auth/youtube.readonly";export const YOUTUBE_READ_SCOPES=Object.freeze([READONLY,"https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]);const API="https://www.googleapis.com/youtube/v3/";const HOUR=36e5,DAY=24*HOUR;const UNKNOWN_TS="1970-01-01T00:00:00.000Z";const MAX_WALK_PAGES=2e5,HEAD_IDS=3,COMMENT_SLACK_MS=DAY,QUOTA_SLACK_MS=6e4;export const YOUTUBE_INCREMENTAL_EVERY_MS=6*HOUR,YOUTUBE_FULL_EVERY_MS=7*DAY;const READ_STREAMS=["channels","subscriptions","playlists","playlistItems","videos","commentThreads"];const LISTED_ONLY=["comments","search","captions","members"];const STATIC_REASONS={channels:["brand-channels-need-own-grant"],playlistItems:["watch-history-not-in-api","watch-later-not-in-api"],comments:["authored-comments-not-in-api"],search:["search-history-not-in-api"],captions:["captions-need-force-ssl-scope"],members:["memberships-need-creator-scope"]};export const youtubeSyncManifest=(()=>{const wanted=new Set([...READ_STREAMS,...LISTED_ONLY]),copy=structuredClone(sourceManifest);delete copy.actionScopes;return{...copy,streams:copy.streams.filter(stream=>wanted.has(stream.stream)),actions:[]}})();const PHASES=["channels","subscriptions","playlists","playlistItems","uploads","likes","dislikes","comments","done"];const text=value=>typeof value==="string"?value.trim():"";const json=value=>JSON.parse(JSON.stringify(value));const instant=(...values)=>{for(const value of values)if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return UNKNOWN_TS};const reasonCode=(reason,fallback)=>(reason??"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||fallback;const shortHash=value=>createHash("sha256").update(value).digest("hex").slice(0,10);export function nextPacificMidnight(nowMs){const at=Math.floor(nowMs/1e3)*1e3;try{const parts=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}).formatToParts(new Date(at)).map(part=>[part.type,part.value]));const[y,m,d]=[Number(parts.year),Number(parts.month),Number(parts.day)];const offset=Date.UTC(y,m-1,d,Number(parts.hour),Number(parts.minute),Number(parts.second))-at;const next=Date.UTC(y,m-1,d+1)-offset;if(Number.isFinite(next)&&next>at)return next}catch{}return Math.floor((at-8*HOUR)/DAY+1)*DAY+8*HOUR}function stringRecord(value){return object(value)&&Object.values(value).every(item=>typeof item==="string")}function parseMarks(value){if(!object(value))return null;const marks={};if(value.since!==void 0){if(typeof value.since!=="string"||!Number.isFinite(Date.parse(value.since)))return null;marks.since=value.since}if(value.heads!==void 0){if(!object(value.heads)||!Object.values(value.heads).every(ids=>Array.isArray(ids)&&ids.every(id=>typeof id==="string")))return null;marks.heads=value.heads}if(value.tags!==void 0){if(!stringRecord(value.tags))return null;marks.tags=value.tags}return marks}function parseWalk(wire){if(!object(wire))return null;const w=wire;const strings=value=>Array.isArray(value)&&value.every(item=>typeof item==="string");const optionalInstant=value=>value===void 0||typeof value==="string"&&Number.isFinite(Date.parse(value));if(typeof w.account!=="string"||!w.account||w.mode!=="full"&&w.mode!=="incremental"||typeof w.startedAt!=="string"||!Number.isFinite(Date.parse(w.startedAt)))return null;if(!PHASES.includes(w.phase)||w.token!==null&&typeof w.token!=="string"||!Number.isSafeInteger(w.pages)||Number(w.pages)<0)return null;if(!strings(w.channels)||!strings(w.uploads)||w.channels.length!==w.uploads.length||!Number.isSafeInteger(w.at)||Number(w.at)<0)return null;if(!Array.isArray(w.queue)||!w.queue.every(entry=>Array.isArray(entry)&&entry.length===2&&entry.every(part=>typeof part==="string"))||w.more!==null&&typeof w.more!=="string")return null;const prior=parseMarks(w.prior),next=parseMarks(w.next);if(!prior||!next||!object(w.gaps)||!Object.values(w.gaps).every(n=>Number.isSafeInteger(n)&&Number(n)>=0))return null;if(!optionalInstant(w.completedAt)||!optionalInstant(w.fullAt)||!optionalInstant(w.quotaUntil)||w.phase==="done"&&w.completedAt===void 0)return null;return{account:w.account,mode:w.mode,startedAt:w.startedAt,phase:w.phase,token:w.token,pages:Number(w.pages),channels:[...w.channels],uploads:[...w.uploads],at:Number(w.at),queue:w.queue.map(([id,tag])=>[id,tag]),more:w.more,prior,next,gaps:{...w.gaps},...w.completedAt===void 0?{}:{completedAt:w.completedAt},...w.fullAt===void 0?{}:{fullAt:w.fullAt},...w.quotaUntil===void 0?{}:{quotaUntil:w.quotaUntil}}}function stable(value,stream,depth=0){if(Array.isArray(value))return value.map(item=>stable(item,stream,depth+1));if(!object(value))return value;const out={};for(const[key,item]of Object.entries(value)){if(key==="etag"||depth===0&&key==="statistics")continue;if(stream==="commentThreads"&&(key==="likeCount"||key==="viewerRating"||key==="canRate"))continue;out[key]=stable(item,stream,depth+1)}return out}function snippet(item){return object(item.snippet)?item.snippet:{}}function commentLine(comment){const s=object(comment)&&object(comment.snippet)?comment.snippet:{};const said=text(s.textOriginal)||text(s.textDisplay);return said?[text(s.authorDisplayName),said].filter(Boolean).join(": "):""}function describe(stream,raw){const item=raw.item,s=snippet(item),title=text(s.title);const lines=(...parts)=>parts.filter(Boolean).join("\n");switch(stream){case"channels":return{title,ts:instant(s.publishedAt),body:lines("YouTube channel: "+title,text(s.customUrl),text(s.description))};case"subscriptions":return{title,ts:instant(s.publishedAt),body:lines("Subscribed to: "+title,text(s.description))};case"playlists":return{title,ts:instant(s.publishedAt),body:lines("Playlist: "+title,text(s.description))};case"playlistItems":{const details=object(item.contentDetails)?item.contentDetails:{};const owner=text(s.videoOwnerChannelTitle);return{title,ts:instant(s.publishedAt,details.videoPublishedAt),body:lines((raw.via==="uploads"?"Uploaded: ":"In playlist: ")+title,owner?"by "+owner:"",text(s.description))}}case"videos":{const tags=Array.isArray(s.tags)?s.tags.filter(tag=>typeof tag==="string"):[];const channel=text(s.channelTitle);return{title,ts:instant(s.publishedAt),body:lines((raw.via==="dislike"?"Disliked video: ":"Liked video: ")+title,channel?"by "+channel:"",text(s.description),tags.join(", "))}}case"commentThreads":{const top=s.topLevelComment,first=commentLine(top),replies=object(item.replies)&&Array.isArray(item.replies.comments)?item.replies.comments.map(commentLine).filter(Boolean):[];const topSnippet=object(top)&&object(top.snippet)?top.snippet:{};return{title:first.slice(0,120),ts:instant(topSnippet.updatedAt,topSnippet.publishedAt),body:lines(first,...replies)}}default:throw Error("YouTube full sync does not normalize stream "+stream+".")}}export function createYouTubeProvider({parts,auth,vault,now=()=>new Date().toISOString(),incrementalEveryMs=YOUTUBE_INCREMENTAL_EVERY_MS,fullEveryMs=YOUTUBE_FULL_EVERY_MS}){if(!Number.isFinite(incrementalEveryMs)||incrementalEveryMs<0||!Number.isFinite(fullEveryMs)||fullEveryMs<0)throw Error("YouTube sync pacing must be non-negative milliseconds.");const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser"};const stop=new AbortController,pending=new Set;let closed=false;let latest=null;const codec=parts.cursorCodecV1({source:"youtube",version:2,versionKey:"v",validate:parseWalk});const fail=(code,message,retryability="non-retryable",cause)=>parts.connectorError(code,message,retryability,cause);const inactive=()=>fail("aborted","YouTube source is inactive.");const owned=task=>{const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled};const declared=new Map(youtubeSyncManifest.streams.map(stream=>[stream.stream,stream]));async function resolveGrant(){if(closed)return inactive();const connection=await vault.connection("youtube");if(!("ok"in connection))return"err"in connection?connection:fail("data_loss","YouTube connection metadata was unconfirmed.");const row=connection.ok;if(!row||row.state!=="connected")return fail("unauthenticated","Connect YouTube before syncing it.");if(typeof row.accountId!=="string"||!row.accountId.trim())return fail("failed_precondition","YouTube sync needs the verified Google subject; an email or grant id is never the account identity.");const scope=YOUTUBE_READ_SCOPES.find(candidate=>row.scopes.includes(candidate));if(!scope)return fail("permission_denied","The YouTube connection has no read scope; reconnect YouTube.");if(closed)return inactive();return Original.ok({id:"0"+createHash("sha256").update(row.accountId).digest("hex").slice(0,25).toUpperCase(),source:"youtube",account:row.accountId,scopes:[scope],expiresAt:new Date(Date.parse(now())+HOUR).toISOString()})}function checkGrant(grant){if(grant.source!=="youtube"||!grant.account?.trim())return fail("permission_denied","YouTube grant is not bound to a verified account.");if(!grant.scopes.some(scope=>YOUTUBE_READ_SCOPES.includes(scope)))return fail("permission_denied","YouTube grant has no read scope.");return void 0}async function fence(grant){if(closed||stop.signal.aborted)return inactive();const current=await vault.connection("youtube");if(!("ok"in current))return"err"in current?current:fail("data_loss","YouTube account fence was unconfirmed.");if(closed||stop.signal.aborted)return inactive();const row=current.ok;if(!row||row.state!=="connected")return fail("unauthenticated","YouTube was disconnected during the sync.");if(row.accountId!==grant.account)return fail("permission_denied","The YouTube account changed during the sync; nothing from the old grant is attributed to the new account.");if(!grant.scopes.every(scope=>row.scopes.includes(scope)))return fail("permission_denied","YouTube read consent was withdrawn.");return Original.ok(void 0)}async function call(grant,listing2,token){const url=new URL(listing2.resource,API);for(const[key,value]of Object.entries(listing2.params))url.searchParams.set(key,value);if(token)url.searchParams.set("pageToken",token);const before=await fence(grant);if(!Original.isOk(before))return before;const reply=await auth.requestRaw("youtube",url.href,{signal:stop.signal});if(closed||stop.signal.aborted)return inactive();if(!("ok"in reply)){const err="err"in reply?reply.err:void 0;if(!err||err.code==="unavailable"||err.code==="aborted")return fail("unavailable","A YouTube list request did not complete (network or request timeout); the page is retried from the same cursor.","transient",err);return reply}const after=await fence(grant);if(!Original.isOk(after))return after;return reply}function soleChannel(walk){return walk.channels.length===1?walk.channels[0]:null}function listing(walk){const page2=(resource,params)=>({resource,params:{...params,maxResults:"50"}});switch(walk.phase){case"channels":return{...page2("channels",{part:"snippet,contentDetails,brandingSettings,status,topicDetails,localizations",mine:"true"}),stream:"channels",via:"mine",owner:null};case"subscriptions":return{...page2("subscriptions",{part:"snippet",mine:"true"}),stream:"subscriptions",via:"subscription",owner:soleChannel(walk)};case"playlists":return{...page2("playlists",{part:"snippet,contentDetails,status,localizations",mine:"true"}),stream:"playlists",via:"playlist",owner:soleChannel(walk)};case"playlistItems":{const id=walk.queue[0][0];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"playlist",owner:soleChannel(walk),playlistId:id}}case"uploads":{const id=walk.uploads[walk.at];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"uploads",owner:walk.channels[walk.at],playlistId:id,head:"uploads:"+id}}case"likes":case"dislikes":{const rating=walk.phase==="likes"?"like":"dislike";return{...page2("videos",{part:"snippet,contentDetails,status,topicDetails",myRating:rating}),stream:"videos",via:rating,owner:soleChannel(walk),head:rating}}case"comments":return{resource:"commentThreads",params:{part:"snippet,replies",allThreadsRelatedToChannelId:walk.channels[walk.at],maxResults:"100",order:"time",textFormat:"plainText"},stream:"commentThreads",via:"channel-comments",owner:walk.channels[walk.at],byTime:true};case"done":throw Error("A completed YouTube walk has no listing.")}}function settle(walk){for(;;){if(walk.phase==="playlistItems"&&!walk.queue.length){if(walk.more!==null){walk.phase="playlists";walk.token=walk.more;walk.more=null}else{walk.phase="uploads";walk.at=0;walk.token=null}continue}if(walk.phase==="uploads"){while(walk.at<walk.channels.length&&!walk.uploads[walk.at])walk.at++;if(walk.at>=walk.channels.length){walk.phase="likes";walk.at=0;walk.token=null;continue}}if(walk.phase==="comments"&&walk.at>=walk.channels.length){walk.phase="done";walk.token=null;continue}return}}function finish(walk,read){switch(walk.phase){case"channels":walk.phase="subscriptions";break;case"subscriptions":walk.phase="playlists";walk.more=null;break;case"playlists":walk.phase="playlistItems";walk.queue=[];walk.more=null;break;case"playlistItems":{const[id,tag]=walk.queue.shift();if(read)walk.next.tags={...walk.next.tags,[id]:tag};break}case"uploads":walk.at++;break;case"likes":walk.phase="dislikes";break;case"dislikes":walk.phase="comments";walk.at=0;break;case"comments":walk.at++;break;case"done":break}walk.token=null}function gap(walk,stream,reason,count=1){const key=stream+":"+reason;walk.gaps[key]=(walk.gaps[key]??0)+count}function begin(account,mode,prior,fullAt,at){return{account,mode,startedAt:at,phase:"channels",token:null,pages:0,channels:[],uploads:[],at:0,queue:[],more:null,prior:mode==="full"?{}:prior,next:{},gaps:{},...fullAt===void 0?{}:{fullAt}}}function complete(walk,at){return{...walk,phase:"done",token:null,at:0,queue:[],more:null,prior:{...walk.next,since:walk.startedAt},next:{},completedAt:at,...walk.mode==="full"?{fullAt:at}:{}}}function encode(walk,notes){let attempt=codec.encode(walk);if("ok"in attempt)return attempt;if(walk.prior.tags||walk.next.tags){const{tags:_p,...prior}=walk.prior,{tags:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: playlist-marks-dropped \u2014 remembered playlist versions were dropped to keep the cursor within "+Original.SYNC_CURSOR_MAX_CHARS+" chars; those playlists are read in full");attempt=codec.encode(walk);if("ok"in attempt)return attempt}if(walk.prior.heads||walk.next.heads){const{heads:_p,...prior}=walk.prior,{heads:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: head-marks-dropped \u2014 remembered list heads were dropped to keep the cursor bounded; those lists are read in full");attempt=codec.encode(walk)}return attempt}function page(items,walk,exhausted,notes){latest=walk;const next=encode(walk,notes);if(!("ok"in next))return next;return Original.ok({items,next:next.ok,exhausted,...notes.length?{notes}:{}})}function respond(items,walk,at,notes){return walk.phase==="done"?page(items,complete(walk,at),true,notes):page(items,walk,false,notes)}function quotaWait(until){return fail("resource_exhausted","YouTube daily quota is exhausted (youtube-daily-quota-exhausted): the project's YouTube Data API units for today are used up. Quota backoff not due until "+until+", when Google resets the quota at midnight Pacific Time; the walk then resumes from its saved cursor and nothing is skipped.","retry-at-higher-level")}const RATE_LIMIT=new Set(["rateLimitExceeded","userRateLimitExceeded","RATE_LIMIT_EXCEEDED"]),DAILY=new Set(["quotaExceeded","dailyLimitExceeded"]),GRANT=new Set(["insufficientPermissions","authError","unauthorized","PERMISSION_DENIED","UNAUTHENTICATED"]);function classify(walk,reply){const what=walk.phase==="uploads"||walk.phase==="playlistItems"?"playlistItems.list":walk.phase==="likes"||walk.phase==="dislikes"?"videos.list":walk.phase==="comments"?"commentThreads.list":walk.phase+".list";if(reply.status===200){let data;try{data=JSON.parse(reply.body)}catch{return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a body that is not JSON; the page is asked again.","transient").err}}if(!object(data)||data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item)))||data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a malformed list; the page is asked again.","transient").err};return{kind:"ok",data}}const reason=parts.googleErrorReasonV1(reply.body);if((reply.status===403||reply.status===429)&&reason!==void 0&&DAILY.has(reason))return{kind:"quota"};const status=()=>parts.webStatusErrorV1(reply.status,{provider:"YouTube",what,headers:reply.headers,...reason?{detail:reason}:{},bodyOverride:code=>code===403&&reason!==void 0&&RATE_LIMIT.has(reason)?{code:"resource_exhausted",retryability:"throttling",meaning:"the provider throttled the call ("+reason+")"}:void 0})??fail("internal","YouTube "+what+" returned HTTP "+reply.status+".").err;if(reply.status===429||reply.status===403&&reason!==void 0&&RATE_LIMIT.has(reason))return{kind:"err",err:status()};if(reason==="youtubeSignupRequired"&&(reply.status===401||reply.status===403))return{kind:"gap",reason:"youtube-signup-required"};if(reply.status===401)return{kind:"err",err:status()};if(reply.status===403){if(walk.phase==="channels"||reason===void 0||GRANT.has(reason))return{kind:"err",err:status()};return{kind:"gap",reason:reasonCode(reason,"forbidden")}}if(reply.status===404)return{kind:"gap",reason:reasonCode(reason,"not-found")};if(reply.status===400&&reason==="invalidPageToken"&&walk.token!==null)return{kind:"restart"};return{kind:"err",err:status()}}async function pullInner(grant,cursor){const invalid=checkGrant(grant);if(invalid)return invalid;if(closed)return inactive();const notes=[],nowMs=Date.parse(now()),nowIso=new Date(nowMs).toISOString();let walk=cursor===null?null:codec.decode(cursor);if(cursor!==null&&walk===null)notes.push("youtube: cursor-unreadable \u2014 the walk starts again from the first list");if(walk&&walk.account!==grant.account){notes.push("youtube: account-changed \u2014 the walk starts again for the connected account");walk=null}if(walk?.quotaUntil!==void 0){if(nowMs<Date.parse(walk.quotaUntil)){latest=walk;return quotaWait(walk.quotaUntil)}const{quotaUntil:_q,...resumed}=walk;walk=resumed;notes.push("youtube: quota-reset \u2014 the walk resumes where the daily quota stopped it")}if(!walk){walk=begin(grant.account,"full",{},void 0,nowIso);notes.push("youtube: full-pass \u2014 every list is read")}else if(walk.phase==="done"){const due=Date.parse(walk.completedAt)+incrementalEveryMs;if(nowMs<due&&cursor!==null){latest=walk;return Original.ok({items:[],next:cursor,exhausted:true,notes:[...notes,"youtube: pass-not-due \u2014 the next pass starts after "+new Date(due).toISOString()+" (quota pacing)"]})}const full=walk.fullAt===void 0||nowMs-Date.parse(walk.fullAt)>=fullEveryMs;walk=begin(grant.account,full?"full":"incremental",walk.prior,walk.fullAt,nowIso);notes.push(full?"youtube: full-pass \u2014 every list is read again (periodic re-walk)":"youtube: incremental-pass \u2014 cheap lists re-listed, unchanged playlists skipped, newest-first lists stop at the remembered head")}settle(walk);if(walk.phase==="done")return page([],complete(walk,nowIso),true,notes);if(walk.pages>=MAX_WALK_PAGES)return fail("resource_exhausted","YouTube walk exceeded "+MAX_WALK_PAGES+" provider pages; the cursor is kept.");const current=listing(walk),reply=await call(grant,current,walk.token);if(!("ok"in reply))return"err"in reply?reply:fail("data_loss","YouTube request result was unconfirmed.");walk.pages++;const outcome=classify(walk,reply.ok),stream=current.stream,items=[];if(outcome.kind==="err")return{err:outcome.err};if(outcome.kind==="quota"){walk.quotaUntil=new Date(nextPacificMidnight(nowMs)+QUOTA_SLACK_MS).toISOString();notes.push("youtube: youtube-daily-quota-exhausted \u2014 no request until "+walk.quotaUntil+"; the walk resumes at this list");return page([],walk,false,notes)}if(outcome.kind==="restart"){walk.token=null;notes.push("youtube: page-token-expired \u2014 this list is read again from its first page");return page([],walk,false,notes)}if(outcome.kind==="gap"){const reason=walk.phase==="channels"&&outcome.reason==="youtube-signup-required"?"no-youtube-channel":outcome.reason;gap(walk,stream,reason);notes.push("youtube: "+stream+" not read \u2014 "+reason+" (HTTP "+reply.ok.status+")");finish(walk,false);settle(walk);return respond(items,walk,nowIso,notes)}const data=outcome.data,rows=Array.isArray(data.items)?data.items:[],nextToken=typeof data.nextPageToken==="string"?data.nextPageToken:null;const ids=[];let missing=0,unavailable=0;for(const item of rows){const id=typeof item.id==="string"&&item.id?item.id:"";if(!id){missing++;continue}ids.push(id);const s=snippet(item);const owner=walk.phase==="channels"?id:current.via==="subscription"||current.via==="playlist"?text(s.channelId)||current.owner:current.owner;const raw={account:walk.account,channelId:owner,via:current.via,...current.playlistId?{playlistId:current.playlistId}:{},item};items.push({streamRef:stream,raw:json(raw)});if(stream==="playlistItems"&&(s.title==="Private video"||s.title==="Deleted video"))unavailable++}if(missing){gap(walk,stream,"item-without-id",missing);notes.push("youtube: "+stream+" item-without-id \u2014 "+missing+" item(s) without a provider id were not stored")}if(unavailable){gap(walk,"playlistItems","video-unavailable",unavailable);notes.push("youtube: video-unavailable \u2014 "+unavailable+" playlist item(s) point to a private or deleted video; only the placeholder is stored")}if(walk.phase==="channels"){for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)&&object(item.contentDetails.relatedPlaylists)?item.contentDetails.relatedPlaylists:{};walk.channels.push(item.id);walk.uploads.push(text(details.uploads))}if(!nextToken&&!walk.channels.length){gap(walk,"channels","no-youtube-channel");notes.push("youtube: channels not read \u2014 no-youtube-channel (this identity has no channel; a Brand Account channel needs its own grant)")}}if(walk.phase==="playlists"){const queue=[];for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)?item.contentDetails:{};const tag=shortHash(typeof item.etag==="string"?item.etag:Original.jcsCanonicalize(json(item)));if(details.itemCount===0||walk.mode==="incremental"&&walk.prior.tags?.[item.id]===tag){walk.next.tags={...walk.next.tags,[item.id]:tag};continue}queue.push([item.id,tag])}finish(walk,true);walk.queue=queue;walk.more=nextToken}else{if(current.head&&walk.token===null)walk.next.heads={...walk.next.heads,[current.head]:ids.slice(0,HEAD_IDS)};const known=current.head?walk.prior.heads?.[current.head]:void 0;const reachedHead=walk.mode==="incremental"&&!!known?.length&&ids.some(id=>known.includes(id));const since=walk.prior.since===void 0?NaN:Date.parse(walk.prior.since)-COMMENT_SLACK_MS;const reachedOld=walk.mode==="incremental"&&current.byTime===true&&Number.isFinite(since)&&rows.some(item=>{const top=snippet(item).topLevelComment,published=object(top)&&object(top.snippet)?Date.parse(String(top.snippet.publishedAt)):NaN;return Number.isFinite(published)&&published<since});if(nextToken&&nextToken===walk.token){gap(walk,stream,"repeated-page-token");notes.push("youtube: "+stream+" repeated-page-token \u2014 the provider repeated a page token; the rest of this list is not read");finish(walk,false)}else if(nextToken&&!reachedHead&&!reachedOld)walk.token=nextToken;else finish(walk,true)}settle(walk);return respond(items,walk,nowIso,notes)}const connector={manifest:youtubeSyncManifest,discover:()=>parts.gateRefusal("YouTube synchronous census","The production YouTube provider is async; use discoverAsync"),pull:()=>parts.gateRefusal("YouTube synchronous pull","The production YouTube provider is async; use pullAsync"),discoverAsync:grant=>owned((async()=>{const invalid=checkGrant(grant);if(invalid)return invalid;const fenced=await fence(grant);if(!Original.isOk(fenced))return fenced;const gaps=latest&&latest.account===grant.account?latest.gaps:{};const streams={};for(const stream of[...READ_STREAMS,...LISTED_ONLY]){const reasons=[...(STATIC_REASONS[stream]??[]).map(reason=>({reason})),...Object.entries(gaps).filter(([key])=>key.startsWith(stream+":")).map(([key,count])=>({reason:key.slice(stream.length+1),count}))];streams[stream]={method:"pagination-exhaustion",...reasons.length?{partialReasons:reasons}:{}}}return Original.ok({asOf:new Date(Date.parse(now())).toISOString(),streams})})()),pullAsync:(grant,cursor)=>owned(pullInner(grant,cursor)),normalize(item){const decl=declared.get(item.streamRef);if(!decl||!READ_STREAMS.includes(item.streamRef))throw Error("YouTube full sync does not emit stream "+item.streamRef+".");if(!object(item.raw)||!object(item.raw.item)||typeof item.raw.account!=="string"||typeof item.raw.via!=="string")throw Error("YouTube normalization requires the wrapped provider resource.");const raw=item.raw,id=typeof raw.item.id==="string"?raw.item.id:"";if(!id)throw Error("YouTube resource has no provider id.");const{title,body,ts}=describe(item.streamRef,raw);const payload={title,account:raw.account,channelId:typeof raw.channelId==="string"?raw.channelId:null,via:raw.via,...typeof raw.playlistId==="string"?{playlistId:raw.playlistId}:{},item:stable(raw.item,item.streamRef)};return{nk:{source:"youtube",stream:item.streamRef,sourceId:item.streamRef==="videos"?raw.via+":"+id:id},ts,kind:decl.kinds[0],tier:"api",schemaVersion:1,mentions:[],body,payload:json(payload)}}};return{info,connector,resolveGrant:()=>owned(resolveGrant()),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}}}
1
+ import{createHash}from"node:crypto";import{Original}from"@zortexhq/plugin-connector-framework/api";import{manifest as sourceManifest}from"./discovery-data.js";import{object}from"./schema.js";const READONLY="https://www.googleapis.com/auth/youtube.readonly";export const YOUTUBE_READ_SCOPES=Object.freeze([READONLY,"https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]);const API="https://www.googleapis.com/youtube/v3/";const HOUR=36e5,DAY=24*HOUR;const UNKNOWN_TS="1970-01-01T00:00:00.000Z";const MAX_WALK_PAGES=2e5,HEAD_IDS=3,COMMENT_SLACK_MS=DAY,QUOTA_SLACK_MS=6e4;export const YOUTUBE_INCREMENTAL_EVERY_MS=6*HOUR,YOUTUBE_FULL_EVERY_MS=7*DAY;const READ_STREAMS=["channels","subscriptions","playlists","playlistItems","videos","commentThreads"];const LISTED_ONLY=["comments","search","captions","members"];const STATIC_REASONS={channels:["brand-channels-need-own-grant"],playlistItems:["watch-history-not-in-api","watch-later-not-in-api"],comments:["authored-comments-not-in-api"],search:["search-history-not-in-api"],captions:["captions-sync-not-implemented"],members:["members-sync-not-implemented"]};export const youtubeSyncManifest=(()=>{const wanted=new Set([...READ_STREAMS,...LISTED_ONLY]),copy=structuredClone(sourceManifest);delete copy.actionScopes;return{...copy,streams:copy.streams.filter(stream=>wanted.has(stream.stream)),actions:[]}})();const PHASES=["channels","subscriptions","playlists","playlistItems","uploads","likes","dislikes","comments","done"];const text=value=>typeof value==="string"?value.trim():"";const json=value=>JSON.parse(JSON.stringify(value));const instant=(...values)=>{for(const value of values)if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return UNKNOWN_TS};const reasonCode=(reason,fallback)=>(reason??"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||fallback;const shortHash=value=>createHash("sha256").update(value).digest("hex").slice(0,10);export function nextPacificMidnight(nowMs){const at=Math.floor(nowMs/1e3)*1e3;try{const parts=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}).formatToParts(new Date(at)).map(part=>[part.type,part.value]));const[y,m,d]=[Number(parts.year),Number(parts.month),Number(parts.day)];const offset=Date.UTC(y,m-1,d,Number(parts.hour),Number(parts.minute),Number(parts.second))-at;const next=Date.UTC(y,m-1,d+1)-offset;if(Number.isFinite(next)&&next>at)return next}catch{}return Math.floor((at-8*HOUR)/DAY+1)*DAY+8*HOUR}function stringRecord(value){return object(value)&&Object.values(value).every(item=>typeof item==="string")}function parseMarks(value){if(!object(value))return null;const marks={};if(value.since!==void 0){if(typeof value.since!=="string"||!Number.isFinite(Date.parse(value.since)))return null;marks.since=value.since}if(value.heads!==void 0){if(!object(value.heads)||!Object.values(value.heads).every(ids=>Array.isArray(ids)&&ids.every(id=>typeof id==="string")))return null;marks.heads=value.heads}if(value.tags!==void 0){if(!stringRecord(value.tags))return null;marks.tags=value.tags}return marks}function parseWalk(wire){if(!object(wire))return null;const w=wire;const strings=value=>Array.isArray(value)&&value.every(item=>typeof item==="string");const optionalInstant=value=>value===void 0||typeof value==="string"&&Number.isFinite(Date.parse(value));if(typeof w.account!=="string"||!w.account||w.mode!=="full"&&w.mode!=="incremental"||typeof w.startedAt!=="string"||!Number.isFinite(Date.parse(w.startedAt)))return null;if(!PHASES.includes(w.phase)||w.token!==null&&typeof w.token!=="string"||!Number.isSafeInteger(w.pages)||Number(w.pages)<0)return null;if(!strings(w.channels)||!strings(w.uploads)||w.channels.length!==w.uploads.length||!Number.isSafeInteger(w.at)||Number(w.at)<0)return null;if(!Array.isArray(w.queue)||!w.queue.every(entry=>Array.isArray(entry)&&entry.length===2&&entry.every(part=>typeof part==="string"))||w.more!==null&&typeof w.more!=="string")return null;const prior=parseMarks(w.prior),next=parseMarks(w.next);if(!prior||!next||!object(w.gaps)||!Object.values(w.gaps).every(n=>Number.isSafeInteger(n)&&Number(n)>=0))return null;if(!optionalInstant(w.completedAt)||!optionalInstant(w.fullAt)||!optionalInstant(w.quotaUntil)||w.phase==="done"&&w.completedAt===void 0)return null;return{account:w.account,mode:w.mode,startedAt:w.startedAt,phase:w.phase,token:w.token,pages:Number(w.pages),channels:[...w.channels],uploads:[...w.uploads],at:Number(w.at),queue:w.queue.map(([id,tag])=>[id,tag]),more:w.more,prior,next,gaps:{...w.gaps},...w.completedAt===void 0?{}:{completedAt:w.completedAt},...w.fullAt===void 0?{}:{fullAt:w.fullAt},...w.quotaUntil===void 0?{}:{quotaUntil:w.quotaUntil}}}function stable(value,stream,depth=0){if(Array.isArray(value))return value.map(item=>stable(item,stream,depth+1));if(!object(value))return value;const out={};for(const[key,item]of Object.entries(value)){if(key==="etag"||depth===0&&key==="statistics")continue;if(stream==="commentThreads"&&(key==="likeCount"||key==="viewerRating"||key==="canRate"))continue;out[key]=stable(item,stream,depth+1)}return out}function snippet(item){return object(item.snippet)?item.snippet:{}}function commentLine(comment){const s=object(comment)&&object(comment.snippet)?comment.snippet:{};const said=text(s.textOriginal)||text(s.textDisplay);return said?[text(s.authorDisplayName),said].filter(Boolean).join(": "):""}function describe(stream,raw){const item=raw.item,s=snippet(item),title=text(s.title);const lines=(...parts)=>parts.filter(Boolean).join("\n");switch(stream){case"channels":return{title,ts:instant(s.publishedAt),body:lines("YouTube channel: "+title,text(s.customUrl),text(s.description))};case"subscriptions":return{title,ts:instant(s.publishedAt),body:lines("Subscribed to: "+title,text(s.description))};case"playlists":return{title,ts:instant(s.publishedAt),body:lines("Playlist: "+title,text(s.description))};case"playlistItems":{const details=object(item.contentDetails)?item.contentDetails:{};const owner=text(s.videoOwnerChannelTitle);return{title,ts:instant(s.publishedAt,details.videoPublishedAt),body:lines((raw.via==="uploads"?"Uploaded: ":"In playlist: ")+title,owner?"by "+owner:"",text(s.description))}}case"videos":{const tags=Array.isArray(s.tags)?s.tags.filter(tag=>typeof tag==="string"):[];const channel=text(s.channelTitle);return{title,ts:instant(s.publishedAt),body:lines((raw.via==="dislike"?"Disliked video: ":"Liked video: ")+title,channel?"by "+channel:"",text(s.description),tags.join(", "))}}case"commentThreads":{const top=s.topLevelComment,first=commentLine(top),replies=object(item.replies)&&Array.isArray(item.replies.comments)?item.replies.comments.map(commentLine).filter(Boolean):[];const topSnippet=object(top)&&object(top.snippet)?top.snippet:{};return{title:first.slice(0,120),ts:instant(topSnippet.updatedAt,topSnippet.publishedAt),body:lines(first,...replies)}}default:throw Error("YouTube full sync does not normalize stream "+stream+".")}}export function createYouTubeProvider({parts,auth,vault,now=()=>new Date().toISOString(),incrementalEveryMs=YOUTUBE_INCREMENTAL_EVERY_MS,fullEveryMs=YOUTUBE_FULL_EVERY_MS}){if(!Number.isFinite(incrementalEveryMs)||incrementalEveryMs<0||!Number.isFinite(fullEveryMs)||fullEveryMs<0)throw Error("YouTube sync pacing must be non-negative milliseconds.");const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser"};const stop=new AbortController,pending=new Set;let closed=false;let latest=null;const codec=parts.cursorCodecV1({source:"youtube",version:2,versionKey:"v",validate:parseWalk});const fail=(code,message,retryability="non-retryable",cause)=>parts.connectorError(code,message,retryability,cause);const inactive=()=>fail("aborted","YouTube source is inactive.");const owned=task=>{const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled};const declared=new Map(youtubeSyncManifest.streams.map(stream=>[stream.stream,stream]));async function resolveGrant(){if(closed)return inactive();const connection=await vault.connection("youtube");if(!("ok"in connection))return"err"in connection?connection:fail("data_loss","YouTube connection metadata was unconfirmed.");const row=connection.ok;if(!row||row.state!=="connected")return fail("unauthenticated","Connect YouTube before syncing it.");if(typeof row.accountId!=="string"||!row.accountId.trim())return fail("failed_precondition","YouTube sync needs the verified Google subject; an email or grant id is never the account identity.");const scope=YOUTUBE_READ_SCOPES.find(candidate=>row.scopes.includes(candidate));if(!scope)return fail("permission_denied","The YouTube connection has no read scope; reconnect YouTube.");if(closed)return inactive();return Original.ok({id:"0"+createHash("sha256").update(row.accountId).digest("hex").slice(0,25).toUpperCase(),source:"youtube",account:row.accountId,scopes:[scope],expiresAt:new Date(Date.parse(now())+HOUR).toISOString()})}function checkGrant(grant){if(grant.source!=="youtube"||!grant.account?.trim())return fail("permission_denied","YouTube grant is not bound to a verified account.");if(!grant.scopes.some(scope=>YOUTUBE_READ_SCOPES.includes(scope)))return fail("permission_denied","YouTube grant has no read scope.");return void 0}async function fence(grant){if(closed||stop.signal.aborted)return inactive();const current=await vault.connection("youtube");if(!("ok"in current))return"err"in current?current:fail("data_loss","YouTube account fence was unconfirmed.");if(closed||stop.signal.aborted)return inactive();const row=current.ok;if(!row||row.state!=="connected")return fail("unauthenticated","YouTube was disconnected during the sync.");if(row.accountId!==grant.account)return fail("permission_denied","The YouTube account changed during the sync; nothing from the old grant is attributed to the new account.");if(!grant.scopes.every(scope=>row.scopes.includes(scope)))return fail("permission_denied","YouTube read consent was withdrawn.");return Original.ok(void 0)}async function call(grant,listing2,token){const url=new URL(listing2.resource,API);for(const[key,value]of Object.entries(listing2.params))url.searchParams.set(key,value);if(token)url.searchParams.set("pageToken",token);const before=await fence(grant);if(!Original.isOk(before))return before;const reply=await auth.requestRaw("youtube",url.href,{signal:stop.signal});if(closed||stop.signal.aborted)return inactive();if(!("ok"in reply)){const err="err"in reply?reply.err:void 0;if(!err||err.code==="unavailable"||err.code==="aborted")return fail("unavailable","A YouTube list request did not complete (network or request timeout); the page is retried from the same cursor.","transient",err);return reply}const after=await fence(grant);if(!Original.isOk(after))return after;return reply}function soleChannel(walk){return walk.channels.length===1?walk.channels[0]:null}function listing(walk){const page2=(resource,params)=>({resource,params:{...params,maxResults:"50"}});switch(walk.phase){case"channels":return{...page2("channels",{part:"snippet,contentDetails,brandingSettings,status,topicDetails,localizations",mine:"true"}),stream:"channels",via:"mine",owner:null};case"subscriptions":return{...page2("subscriptions",{part:"snippet",mine:"true"}),stream:"subscriptions",via:"subscription",owner:soleChannel(walk)};case"playlists":return{...page2("playlists",{part:"snippet,contentDetails,status,localizations",mine:"true"}),stream:"playlists",via:"playlist",owner:soleChannel(walk)};case"playlistItems":{const id=walk.queue[0][0];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"playlist",owner:soleChannel(walk),playlistId:id}}case"uploads":{const id=walk.uploads[walk.at];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"uploads",owner:walk.channels[walk.at],playlistId:id,head:"uploads:"+id}}case"likes":case"dislikes":{const rating=walk.phase==="likes"?"like":"dislike";return{...page2("videos",{part:"snippet,contentDetails,status,topicDetails",myRating:rating}),stream:"videos",via:rating,owner:soleChannel(walk),head:rating}}case"comments":return{resource:"commentThreads",params:{part:"snippet,replies",allThreadsRelatedToChannelId:walk.channels[walk.at],maxResults:"100",order:"time",textFormat:"plainText"},stream:"commentThreads",via:"channel-comments",owner:walk.channels[walk.at],byTime:true};case"done":throw Error("A completed YouTube walk has no listing.")}}function settle(walk){for(;;){if(walk.phase==="playlistItems"&&!walk.queue.length){if(walk.more!==null){walk.phase="playlists";walk.token=walk.more;walk.more=null}else{walk.phase="uploads";walk.at=0;walk.token=null}continue}if(walk.phase==="uploads"){while(walk.at<walk.channels.length&&!walk.uploads[walk.at])walk.at++;if(walk.at>=walk.channels.length){walk.phase="likes";walk.at=0;walk.token=null;continue}}if(walk.phase==="comments"&&walk.at>=walk.channels.length){walk.phase="done";walk.token=null;continue}return}}function finish(walk,read){switch(walk.phase){case"channels":walk.phase="subscriptions";break;case"subscriptions":walk.phase="playlists";walk.more=null;break;case"playlists":walk.phase="playlistItems";walk.queue=[];walk.more=null;break;case"playlistItems":{const[id,tag]=walk.queue.shift();if(read)walk.next.tags={...walk.next.tags,[id]:tag};break}case"uploads":walk.at++;break;case"likes":walk.phase="dislikes";break;case"dislikes":walk.phase="comments";walk.at=0;break;case"comments":walk.at++;break;case"done":break}walk.token=null}function gap(walk,stream,reason,count=1){const key=stream+":"+reason;walk.gaps[key]=(walk.gaps[key]??0)+count}function begin(account,mode,prior,fullAt,at){return{account,mode,startedAt:at,phase:"channels",token:null,pages:0,channels:[],uploads:[],at:0,queue:[],more:null,prior:mode==="full"?{}:prior,next:{},gaps:{},...fullAt===void 0?{}:{fullAt}}}function complete(walk,at){return{...walk,phase:"done",token:null,at:0,queue:[],more:null,prior:{...walk.next,since:walk.startedAt},next:{},completedAt:at,...walk.mode==="full"?{fullAt:at}:{}}}function encode(walk,notes){let attempt=codec.encode(walk);if("ok"in attempt)return attempt;if(walk.prior.tags||walk.next.tags){const{tags:_p,...prior}=walk.prior,{tags:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: playlist-marks-dropped \u2014 remembered playlist versions were dropped to keep the cursor within "+Original.SYNC_CURSOR_MAX_CHARS+" chars; those playlists are read in full");attempt=codec.encode(walk);if("ok"in attempt)return attempt}if(walk.prior.heads||walk.next.heads){const{heads:_p,...prior}=walk.prior,{heads:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: head-marks-dropped \u2014 remembered list heads were dropped to keep the cursor bounded; those lists are read in full");attempt=codec.encode(walk)}return attempt}function page(items,walk,exhausted,notes){latest=walk;const next=encode(walk,notes);if(!("ok"in next))return next;return Original.ok({items,next:next.ok,exhausted,...notes.length?{notes}:{}})}function respond(items,walk,at,notes){return walk.phase==="done"?page(items,complete(walk,at),true,notes):page(items,walk,false,notes)}function quotaWait(until){return fail("resource_exhausted","YouTube daily quota is exhausted (youtube-daily-quota-exhausted): the project's YouTube Data API units for today are used up. Quota backoff not due until "+until+", when Google resets the quota at midnight Pacific Time; the walk then resumes from its saved cursor and nothing is skipped.","retry-at-higher-level")}const RATE_LIMIT=new Set(["rateLimitExceeded","userRateLimitExceeded","RATE_LIMIT_EXCEEDED"]),DAILY=new Set(["quotaExceeded","dailyLimitExceeded"]),GRANT=new Set(["insufficientPermissions","authError","unauthorized","PERMISSION_DENIED","UNAUTHENTICATED"]);function classify(walk,reply){const what=walk.phase==="uploads"||walk.phase==="playlistItems"?"playlistItems.list":walk.phase==="likes"||walk.phase==="dislikes"?"videos.list":walk.phase==="comments"?"commentThreads.list":walk.phase+".list";if(reply.status===200){let data;try{data=JSON.parse(reply.body)}catch{return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a body that is not JSON; the page is asked again.","transient").err}}if(!object(data)||data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item)))||data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a malformed list; the page is asked again.","transient").err};return{kind:"ok",data}}const reason=parts.googleErrorReasonV1(reply.body);if((reply.status===403||reply.status===429)&&reason!==void 0&&DAILY.has(reason))return{kind:"quota"};const status=()=>parts.webStatusErrorV1(reply.status,{provider:"YouTube",what,headers:reply.headers,...reason?{detail:reason}:{},bodyOverride:code=>code===403&&reason!==void 0&&RATE_LIMIT.has(reason)?{code:"resource_exhausted",retryability:"throttling",meaning:"the provider throttled the call ("+reason+")"}:void 0})??fail("internal","YouTube "+what+" returned HTTP "+reply.status+".").err;if(reply.status===429||reply.status===403&&reason!==void 0&&RATE_LIMIT.has(reason))return{kind:"err",err:status()};if(reason==="youtubeSignupRequired"&&(reply.status===401||reply.status===403))return{kind:"gap",reason:"youtube-signup-required"};if(reply.status===401)return{kind:"err",err:status()};if(reply.status===403){if(walk.phase==="channels"||reason===void 0||GRANT.has(reason))return{kind:"err",err:status()};return{kind:"gap",reason:reasonCode(reason,"forbidden")}}if(reply.status===404)return{kind:"gap",reason:reasonCode(reason,"not-found")};if(reply.status===400&&reason==="invalidPageToken"&&walk.token!==null)return{kind:"restart"};return{kind:"err",err:status()}}async function pullInner(grant,cursor){const invalid=checkGrant(grant);if(invalid)return invalid;if(closed)return inactive();const notes=[],nowMs=Date.parse(now()),nowIso=new Date(nowMs).toISOString();let walk=cursor===null?null:codec.decode(cursor);if(cursor!==null&&walk===null)notes.push("youtube: cursor-unreadable \u2014 the walk starts again from the first list");if(walk&&walk.account!==grant.account){notes.push("youtube: account-changed \u2014 the walk starts again for the connected account");walk=null}if(walk?.quotaUntil!==void 0){if(nowMs<Date.parse(walk.quotaUntil)){latest=walk;return quotaWait(walk.quotaUntil)}const{quotaUntil:_q,...resumed}=walk;walk=resumed;notes.push("youtube: quota-reset \u2014 the walk resumes where the daily quota stopped it")}if(!walk){walk=begin(grant.account,"full",{},void 0,nowIso);notes.push("youtube: full-pass \u2014 every list is read")}else if(walk.phase==="done"){const due=Date.parse(walk.completedAt)+incrementalEveryMs;if(nowMs<due&&cursor!==null){latest=walk;return Original.ok({items:[],next:cursor,exhausted:true,notes:[...notes,"youtube: pass-not-due \u2014 the next pass starts after "+new Date(due).toISOString()+" (quota pacing)"]})}const full=walk.fullAt===void 0||nowMs-Date.parse(walk.fullAt)>=fullEveryMs;walk=begin(grant.account,full?"full":"incremental",walk.prior,walk.fullAt,nowIso);notes.push(full?"youtube: full-pass \u2014 every list is read again (periodic re-walk)":"youtube: incremental-pass \u2014 cheap lists re-listed, unchanged playlists skipped, newest-first lists stop at the remembered head")}settle(walk);if(walk.phase==="done")return page([],complete(walk,nowIso),true,notes);if(walk.pages>=MAX_WALK_PAGES)return fail("resource_exhausted","YouTube walk exceeded "+MAX_WALK_PAGES+" provider pages; the cursor is kept.");const current=listing(walk),reply=await call(grant,current,walk.token);if(!("ok"in reply))return"err"in reply?reply:fail("data_loss","YouTube request result was unconfirmed.");walk.pages++;const outcome=classify(walk,reply.ok),stream=current.stream,items=[];if(outcome.kind==="err")return{err:outcome.err};if(outcome.kind==="quota"){walk.quotaUntil=new Date(nextPacificMidnight(nowMs)+QUOTA_SLACK_MS).toISOString();notes.push("youtube: youtube-daily-quota-exhausted \u2014 no request until "+walk.quotaUntil+"; the walk resumes at this list");return page([],walk,false,notes)}if(outcome.kind==="restart"){walk.token=null;notes.push("youtube: page-token-expired \u2014 this list is read again from its first page");return page([],walk,false,notes)}if(outcome.kind==="gap"){const reason=walk.phase==="channels"&&outcome.reason==="youtube-signup-required"?"no-youtube-channel":outcome.reason;gap(walk,stream,reason);notes.push("youtube: "+stream+" not read \u2014 "+reason+" (HTTP "+reply.ok.status+")");finish(walk,false);settle(walk);return respond(items,walk,nowIso,notes)}const data=outcome.data,rows=Array.isArray(data.items)?data.items:[],nextToken=typeof data.nextPageToken==="string"?data.nextPageToken:null;const ids=[];let missing=0,unavailable=0;for(const item of rows){const id=typeof item.id==="string"&&item.id?item.id:"";if(!id){missing++;continue}ids.push(id);const s=snippet(item);const owner=walk.phase==="channels"?id:current.via==="subscription"||current.via==="playlist"?text(s.channelId)||current.owner:current.owner;const raw={account:walk.account,channelId:owner,via:current.via,...current.playlistId?{playlistId:current.playlistId}:{},item};items.push({streamRef:stream,raw:json(raw)});if(stream==="playlistItems"&&(s.title==="Private video"||s.title==="Deleted video"))unavailable++}if(missing){gap(walk,stream,"item-without-id",missing);notes.push("youtube: "+stream+" item-without-id \u2014 "+missing+" item(s) without a provider id were not stored")}if(unavailable){gap(walk,"playlistItems","video-unavailable",unavailable);notes.push("youtube: video-unavailable \u2014 "+unavailable+" playlist item(s) point to a private or deleted video; only the placeholder is stored")}if(walk.phase==="channels"){for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)&&object(item.contentDetails.relatedPlaylists)?item.contentDetails.relatedPlaylists:{};walk.channels.push(item.id);walk.uploads.push(text(details.uploads))}if(!nextToken&&!walk.channels.length){gap(walk,"channels","no-youtube-channel");notes.push("youtube: channels not read \u2014 no-youtube-channel (this identity has no channel; a Brand Account channel needs its own grant)")}}if(walk.phase==="playlists"){const queue=[];for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)?item.contentDetails:{};const tag=shortHash(typeof item.etag==="string"?item.etag:Original.jcsCanonicalize(json(item)));if(details.itemCount===0||walk.mode==="incremental"&&walk.prior.tags?.[item.id]===tag){walk.next.tags={...walk.next.tags,[item.id]:tag};continue}queue.push([item.id,tag])}finish(walk,true);walk.queue=queue;walk.more=nextToken}else{if(current.head&&walk.token===null)walk.next.heads={...walk.next.heads,[current.head]:ids.slice(0,HEAD_IDS)};const known=current.head?walk.prior.heads?.[current.head]:void 0;const reachedHead=walk.mode==="incremental"&&!!known?.length&&ids.some(id=>known.includes(id));const since=walk.prior.since===void 0?NaN:Date.parse(walk.prior.since)-COMMENT_SLACK_MS;const reachedOld=walk.mode==="incremental"&&current.byTime===true&&Number.isFinite(since)&&rows.some(item=>{const top=snippet(item).topLevelComment,published=object(top)&&object(top.snippet)?Date.parse(String(top.snippet.publishedAt)):NaN;return Number.isFinite(published)&&published<since});if(nextToken&&nextToken===walk.token){gap(walk,stream,"repeated-page-token");notes.push("youtube: "+stream+" repeated-page-token \u2014 the provider repeated a page token; the rest of this list is not read");finish(walk,false)}else if(nextToken&&!reachedHead&&!reachedOld)walk.token=nextToken;else finish(walk,true)}settle(walk);return respond(items,walk,nowIso,notes)}const connector={manifest:youtubeSyncManifest,discover:()=>parts.gateRefusal("YouTube synchronous census","The production YouTube provider is async; use discoverAsync"),pull:()=>parts.gateRefusal("YouTube synchronous pull","The production YouTube provider is async; use pullAsync"),discoverAsync:grant=>owned((async()=>{const invalid=checkGrant(grant);if(invalid)return invalid;const fenced=await fence(grant);if(!Original.isOk(fenced))return fenced;const gaps=latest&&latest.account===grant.account?latest.gaps:{};const streams={};for(const stream of[...READ_STREAMS,...LISTED_ONLY]){const reasons=[...(STATIC_REASONS[stream]??[]).map(reason=>({reason})),...Object.entries(gaps).filter(([key])=>key.startsWith(stream+":")).map(([key,count])=>({reason:key.slice(stream.length+1),count}))];streams[stream]={method:"pagination-exhaustion",...reasons.length?{partialReasons:reasons}:{}}}return Original.ok({asOf:new Date(Date.parse(now())).toISOString(),streams})})()),pullAsync:(grant,cursor)=>owned(pullInner(grant,cursor)),normalize(item){const decl=declared.get(item.streamRef);if(!decl||!READ_STREAMS.includes(item.streamRef))throw Error("YouTube full sync does not emit stream "+item.streamRef+".");if(!object(item.raw)||!object(item.raw.item)||typeof item.raw.account!=="string"||typeof item.raw.via!=="string")throw Error("YouTube normalization requires the wrapped provider resource.");const raw=item.raw,id=typeof raw.item.id==="string"?raw.item.id:"";if(!id)throw Error("YouTube resource has no provider id.");const{title,body,ts}=describe(item.streamRef,raw);const payload={title,account:raw.account,channelId:typeof raw.channelId==="string"?raw.channelId:null,via:raw.via,...typeof raw.playlistId==="string"?{playlistId:raw.playlistId}:{},item:stable(raw.item,item.streamRef)};return{nk:{source:"youtube",stream:item.streamRef,sourceId:item.streamRef==="videos"?raw.via+":"+id:id},ts,kind:decl.kinds[0],tier:"api",schemaVersion:1,mentions:[],body,payload:json(payload)}}};return{info,connector,resolveGrant:()=>owned(resolveGrant()),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}}}
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{pinnedMethods,discoveryPin}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";import{object,invalidSchema}from"./schema.js";import{createYouTubeConnector}from"./connector.js";import{readTakeout}from"./takeout.js";const methodMap=new Map([...pinnedMethods,...creatorMethods].flatMap(method=>[[method.id,method],[method.contractName,method]]));const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["authorized_collections"],limitations:["provider_history_limits"]},readById:true};export function createYouTubeSource({parts,auth,vault,transport,takeoutRoot}){const stop=new AbortController,pending=new Set;let closed=false;const track=work=>{pending.add(work);return work.finally(()=>pending.delete(work))};const unavailable=()=>businessError("unavailable","YouTube source is inactive.","connector");const aborted=()=>businessError("aborted","YouTube read was cancelled.","connector");function catalog(options={}){const{query="",resource,limit=20,cursor=0,profile="data"}=options;if(typeof query!=="string"||query.length>500||resource!==void 0&&typeof resource!=="string"||!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return businessError("invalid_argument","Catalog query/limit/cursor is invalid.","connector");if(!["data","analytics","reporting","all"].includes(profile))return businessError("invalid_argument","Unknown YouTube capability profile.","connector");const selected=[...pinnedMethods,...creatorMethods].filter(m=>(profile==="all"||(m.profile??"data")===profile)&&(!resource||m.resource===resource)&&(!query||[m.id,m.description??""].join(" ").toLowerCase().includes(query.toLowerCase())));return Original.ok({total:selected.length,methods:selected.slice(cursor,cursor+limit).map(m=>({id:m.id,contract:m.contractName,resource:m.resource,method:m.httpMethod,scopes:m.scopes??[],body:!!m.request?.$ref,media:!!m.supportsMediaUpload})),...cursor+limit<selected.length?{next:cursor+limit}:{},pin:discoveryPin,gaps:["watchHistory/watchLater require explicit read-only Takeout","creator Analytics/Reporting need separate admitted profile and scopes","audio/video bytes require provider permission","write effects require original action rail verification; HTTP success is not EFFECTED"]})}function method(id){const found=methodMap.get(id);return found?Original.ok(structuredClone(found)):businessError("not_found","Unknown pinned YouTube method.","connector")}async function invokeInner(id,input,options={},level1=false){if(closed)return unavailable();const m=methodMap.get(id);if(!m)return businessError("not_found","Unknown pinned YouTube method.","connector");const invalid=invalidSchema(m.params,input);if(invalid)return businessError("invalid_argument",invalid,"connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const conn=await vault.connection("youtube");if(!("ok"in conn))return conn;if(!conn.ok||conn.ok.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(closed||signal.aborted)return aborted();if(!m.scopes?.length)return businessError("failed_precondition","The pinned provider method "+m.id+" publishes no OAuth scope requirement. Scope/admission reconnaissance is required before a dispatch; no permission was guessed.","auth");if(!(m.scopes??[]).some(scope=>conn.ok.scopes.includes(scope)))return businessError("permission_denied","Method "+id+" requires one of the declared scopes: "+(m.scopes??[]).join(", ")+". Reauthorize this source; no API-key fallback.","auth");if(input.params.onBehalfOfContentOwner!==void 0&&!conn.ok.scopes.includes("https://www.googleapis.com/auth/youtubepartner"))return businessError("permission_denied","Content-owner operations require the partner scope and linked CMS admission.","auth");let pathname=m.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(input.params)){if(m.parameters?.[key]?.location==="path"){const text=String(value);if(text.split("/").some(segment=>segment==="."||segment==="..")||/[?#%\\]/.test(text))return businessError("invalid_argument","Path parameters cannot contain traversal or encoded routing material.","connector");const reserved=pathname.includes("{+"+key+"}");if(reserved&&!/^[A-Za-z0-9_./-]+$/.test(text))return businessError("invalid_argument","Reserved resource paths must be canonical provider resource names.","connector");pathname=pathname.replace(reserved?"{+"+key+"}":"{"+key+"}",reserved?text.split("/").map(encodeURIComponent).join("/"):encodeURIComponent(text))}else query.set(key,Array.isArray(value)?value.join(","):String(value))}if(pathname.includes("{"))return businessError("invalid_argument","Provider path parameter is missing.","connector");if(input.media)return businessError("failed_precondition","Media upload needs the separately admitted bounded streaming transport; no effect was dispatched.","connector");if(m.id==="youtube.youtube.v3.liveChat.messages.stream")return businessError("failed_precondition","The pinned server-streaming RPC requires an admitted cancelable stream transport; use liveChatMessages.list with pageToken until that profile is enabled.","connector");if(m.httpMethod!=="GET"&&!transport&&!level1)return businessError("failed_precondition","Write transport and original action admission are required for "+id+"; no effect was dispatched.","connector");const url=new URL(pathname,m.baseUrl??"https://www.googleapis.com/");url.search=query.toString();const raw=transport?await transport("youtube",url.href,{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"},signal}):await auth.requestRaw("youtube",url.href,{signal,...level1?{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"}}:{}});if(closed||signal.aborted)return aborted();if(!("ok"in raw))return raw;if(Buffer.byteLength(raw.ok.body,"utf8")>2*1024*1024)return businessError("resource_exhausted","YouTube response exceeds the bounded broker body budget. Use an admitted streaming path; no body was truncated.","connector");const reason=parts.googleErrorReasonV1(raw.ok.body),baseOverride=parts.googleStatusOverrideV1(raw.ok.body),status=parts.webStatusErrorV1(raw.ok.status,{provider:"YouTube",what:id,headers:raw.ok.headers,bodyOverride:status2=>status2===403&&reason==="quotaExceeded"?{code:"resource_exhausted",retryability:"throttling",meaning:"the YouTube project quota bucket is exhausted (quotaExceeded)"}:baseOverride(status2),...reason?{detail:reason}:{}});if(status)return{err:status};if(m.supportsMediaDownload){return Original.ok({method:id,resource:m.resource,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain",items:[{id:input.params.id??input.params.resourceName,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain"}],warnings:[],effect:"read",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}if(raw.ok.status===204||!raw.ok.body)return Original.ok({method:id,resource:m.resource,items:[],warnings:["Provider response carries no body; upstream effect remains unverified."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}});let data;try{data=JSON.parse(raw.ok.body)}catch{return businessError("data_loss","YouTube returned invalid JSON for "+id+".","connector")}if(!object(data))return businessError("data_loss","YouTube response must be an object.","connector");if(data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item))))return businessError("data_loss","YouTube response items are malformed.","connector");if(data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return businessError("data_loss","YouTube nextPageToken is malformed.","connector");const items=Array.isArray(data.items)?data.items:typeof data.id==="string"?[data]:[];return Original.ok({method:id,resource:m.resource,data,items,...typeof data.nextPageToken==="string"?{nextPageToken:data.nextPageToken}:{},warnings:m.httpMethod==="GET"?[]:["HTTP response accepted. Only original action read-after-write/event-confirm can mark EFFECTED."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}function invoke(id,input,options={},level1=false){return track(invokeInner(id,input,options,level1).catch(error=>{if(closed||options.signal?.aborted)return aborted();const cause=object(error)?Original.validateStructuredError(error.structuredError):void 0;return parts.connectorError("unavailable","Trusted YouTube transport failed before a confirmed provider response. Raw custody exception text is not a tool result.","transient",cause&&"ok"in cause?cause.ok:void 0)}))}async function*pages(id,params,options={}){const m=methodMap.get(id);if(!m||m.httpMethod!=="GET"){yield businessError("invalid_argument","Only pinned GET methods can be paginated.","connector");return}if(options.maxPages!==void 0&&(!Number.isInteger(options.maxPages)||options.maxPages<1)){yield businessError("invalid_argument","maxPages must be a positive integer.","connector");return}const seen=new Set;let token=typeof params.pageToken==="string"?params.pageToken:void 0,count=0;for(;;){if(token&&seen.has(token)){yield businessError("failed_precondition","YouTube repeated a page token; coverage is incomplete.","connector");return}if(token)seen.add(token);const result=await invoke(id,{params:{...params,...token?{pageToken:token}:{}}},options);yield result;if(!("ok"in result))return;count++;token=result.ok.nextPageToken;if(!token)return;if(options.maxPages!==void 0&&count>=options.maxPages){yield businessError("resource_exhausted","Selected page budget ended with a nonterminal token; coverage is incomplete.","connector");return}}}async function readInner(request,options={}){if(closed)return unavailable();const bad=validateRead(request,["fileId"]);if(bad)return bad;request=structuredClone(request);if(request.fileId!==void 0&&(!/^[A-Za-z0-9_-]{1,200}$/.test(request.fileId)||request.query!==void 0||request.since!==void 0||request.until!==void 0))return businessError("invalid_argument","An exact YouTube video read takes fileId without query or time bounds.","connector");const selected=request.fileId?"youtube.videos.list":request.query?"youtube.search.list":"youtube.activities.list";const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const connection=await vault.connection("youtube");if(!("ok"in connection))return connection;const captured=structuredClone(connection.ok);if(!captured||captured.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(typeof captured.accountId!=="string"||!captured.accountId.trim())return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");const firstScopes=methodMap.get(selected)?.scopes??[],detailScopes=request.query?methodMap.get("youtube.videos.list")?.scopes??[]:firstScopes,scopes=firstScopes.filter(scope=>detailScopes.includes(scope)),readonly="https://www.googleapis.com/auth/youtube.readonly";const requiredScope=scopes.includes(readonly)&&captured.scopes.includes(readonly)?readonly:scopes.find(scope=>captured.scopes.includes(scope));if(!requiredScope)return businessError("permission_denied","The selected YouTube query requires one of its pinned read scopes.","auth");const fence=async()=>{if(closed||signal.aborted)return aborted();const current=await vault.connection("youtube");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==captured.accountId||!current.ok.scopes.includes(requiredScope))return businessError("permission_denied","YouTube selected read connection or scope changed.","auth");return Original.ok(void 0)};const boundInvoke=async(id,input)=>{const before=await fence();if(!("ok"in before))return before;const answer2=await invoke(id,input,{signal});const after=await fence();return"ok"in after?answer2:after};const wanted=request.limit??1,params=request.fileId?{part:["snippet","contentDetails","status","statistics"],id:[request.fileId]}:request.query?{part:["snippet"],q:request.query,type:["video"],maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}}:{part:["snippet","contentDetails"],mine:true,maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}};let answer=await boundInvoke(selected,{params});if("err"in answer&&selected==="youtube.activities.list"&&answer.err.code==="permission_denied"){const channels=await boundInvoke("youtube.channels.list",{params:{part:["id"],mine:true,maxResults:1}});if("ok"in channels&&!channels.ok.items.length)return readResult("youtube",[],["This Google account has no YouTube channel, so it has no own activity to read; full sync records it as no-youtube-channel."])}if(!("ok"in answer))return answer;const items=[...answer.ok.items],seen=new Set;let steps=1;while(items.length<wanted&&answer.ok.nextPageToken){const token=answer.ok.nextPageToken;if(seen.has(token))return businessError("failed_precondition","Selected YouTube read repeated a token; no complete result was asserted.","connector");seen.add(token);if(++steps>100)return businessError("resource_exhausted","Selected YouTube read exceeded the page budget before satisfying its limit; no complete result was asserted.","connector");answer=await boundInvoke(selected,{params:{...params,pageToken:token}});if(!("ok"in answer))return answer;items.push(...answer.ok.items)}let retained=items.slice(0,wanted),resource=answer.ok.resource;if(request.query&&retained.length){const selectedItems=retained,details=[];for(let index=0;index<selectedItems.length;index+=50){const block=selectedItems.slice(index,index+50),ids=block.map(item=>object(item.id)?item.id.videoId:void 0).filter(id=>typeof id==="string");if(ids.length!==block.length)return businessError("data_loss","A selected YouTube video search result lacks its native video id.","connector");const hydrated=await boundInvoke("youtube.videos.list",{params:{part:["snippet","contentDetails","status","statistics","topicDetails","recordingDetails","localizations"],id:ids}});if(!("ok"in hydrated))return hydrated;for(const item of hydrated.ok.items)details.push({...item,_selection:block.find(selected2=>object(selected2.id)&&selected2.id.videoId===item.id)??null})}retained=details;resource="videos"}const records=retained.map(item=>({source:"youtube",sourceId:captured.accountId+":"+resource+":"+itemId(item),stream:resource,kind:"youtube."+resource.toLowerCase()+".changed",ts:itemTime(item),body:JSON.stringify(item),fields:{...item}}));const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;if(closed||signal.aborted)return aborted();return readResult("youtube",records,[...answer.ok.warnings,...answer.ok.nextPageToken||items.length>wanted?["More provider results exist beyond this selected batch."]:[],...retained.length<Math.min(items.length,wanted)?["Some selected videos are currently inaccessible/deleted; search metadata is retained only as an attributed missing detail, never a fabricated video body."]:[],"This selected API query does not establish complete YouTube account or archive coverage."])}function read(request,options={}){return track(readInner(request,options))}async function importTakeout(root=takeoutRoot??"",options={}){if(closed)return unavailable();if(!root)return businessError("failed_precondition","Supply an explicit extracted read-only Takeout copy; API success cannot substitute for history.","connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;const result=await readTakeout(root,signal);if(!("ok"in result))return result;if(closed||signal.aborted)return aborted();const saved=await cache(vault,"youtube",result.ok.records);if(!("ok"in saved))return saved;return result}const account=async()=>{const row=await vault.connection("youtube");if(!("ok"in row))return row;if(!row.ok||row.ok.state!=="connected")return businessError("unauthenticated","YouTube identity needs a connected account.","auth");if(!row.ok.accountId)return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");return Original.ok(row.ok.accountId)};function actionSchema(schema){const{id:_discoveryType,...result}=schema;if(result.properties)result.properties=Object.fromEntries(Object.entries(result.properties).map(([key,value])=>[key,actionSchema(value)]));if(result.items)result.items=actionSchema(result.items);if(object(result.additionalProperties))result.additionalProperties=actionSchema(result.additionalProperties);return result}const actions={catalog,method:id=>{const result=method(id);if(!("ok"in result))return result;const m=result.ok;return Original.ok({...m,params:actionSchema(m.params),...!m.supportsMediaUpload&&m.id!=="youtube.youtube.v3.liveChat.messages.stream"&&(!m.profile||m.httpMethod==="GET")?{level:1,effect:m.httpMethod==="GET"?"read":"write"}:{}})},invoke:(id,input,options={})=>invoke(id,input,options,true)};const source={info,actions,catalog,method,invoke,pages,read,status:()=>closed?Promise.resolve(Original.ok({...info,state:"unavailable",message:"YouTube source is inactive."})):connectionState(vault,info),connect:options=>closed?Promise.resolve(unavailable()):track(auth.connect("youtube",options)),job:id=>closed?unavailable():auth.job(id),cancelJob:id=>auth.cancelJob(id),importTakeout:(root,options)=>track(importTakeout(root,options)),createConnector:(plan,options={})=>createYouTubeConnector({parts,invoke,method,account,isClosed:()=>closed},plan,options),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}};return source}export function itemId(item){if(typeof item.id==="string")return item.id;if(typeof item.videoId==="string")return item.videoId;if(object(item.id)){for(const key of["videoId","channelId","playlistId"])if(typeof item.id[key]==="string")return key+":"+item.id[key]}const value=JSON.parse(JSON.stringify(item.id??item));return createHash("sha256").update(Original.jcsCanonicalize(value)).digest("hex")}export function itemTime(item){const snippet=object(item.snippet)?item.snippet:{};for(const value of[item.time,item.updated,item.updatedAt,snippet.updatedAt,snippet.publishedAt])if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return"1970-01-01T00:00:00.000Z"}
1
+ import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{pinnedMethods,discoveryPin}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";import{object,invalidSchema}from"./schema.js";import{createYouTubeConnector}from"./connector.js";import{readTakeout}from"./takeout.js";import{youtubeContent}from"./content.js";const methodMap=new Map([...pinnedMethods,...creatorMethods].flatMap(method=>[[method.id,method],[method.contractName,method]]));const info={content:youtubeContent,source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["authorized_collections"],limitations:["provider_history_limits"]},readById:true};export function createYouTubeSource({parts,auth,vault,transport,takeoutRoot}){const stop=new AbortController,pending=new Set;let closed=false;const track=work=>{pending.add(work);return work.finally(()=>pending.delete(work))};const unavailable=()=>businessError("unavailable","YouTube source is inactive.","connector");const aborted=()=>businessError("aborted","YouTube read was cancelled.","connector");function catalog(options={}){const{query="",resource,limit=20,cursor=0,profile="data"}=options;if(typeof query!=="string"||query.length>500||resource!==void 0&&typeof resource!=="string"||!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return businessError("invalid_argument","Catalog query/limit/cursor is invalid.","connector");if(!["data","analytics","reporting","all"].includes(profile))return businessError("invalid_argument","Unknown YouTube capability profile.","connector");const selected=[...pinnedMethods,...creatorMethods].filter(m=>(profile==="all"||(m.profile??"data")===profile)&&(!resource||m.resource===resource)&&(!query||[m.id,m.description??""].join(" ").toLowerCase().includes(query.toLowerCase())));return Original.ok({total:selected.length,methods:selected.slice(cursor,cursor+limit).map(m=>({id:m.id,contract:m.contractName,resource:m.resource,method:m.httpMethod,scopes:m.scopes??[],body:!!m.request?.$ref,media:!!m.supportsMediaUpload})),...cursor+limit<selected.length?{next:cursor+limit}:{},pin:discoveryPin,gaps:["watchHistory/watchLater require explicit read-only Takeout","creator Analytics/Reporting need separate admitted profile and scopes","audio/video bytes require provider permission","write effects require original action rail verification; HTTP success is not EFFECTED"]})}function method(id){const found=methodMap.get(id);return found?Original.ok(structuredClone(found)):businessError("not_found","Unknown pinned YouTube method.","connector")}async function invokeInner(id,input,options={},level1=false){if(closed)return unavailable();const m=methodMap.get(id);if(!m)return businessError("not_found","Unknown pinned YouTube method.","connector");const invalid=invalidSchema(m.params,input);if(invalid)return businessError("invalid_argument",invalid,"connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const conn=await vault.connection("youtube");if(!("ok"in conn))return conn;if(!conn.ok||conn.ok.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(closed||signal.aborted)return aborted();if(!m.scopes?.length)return businessError("failed_precondition","The pinned provider method "+m.id+" publishes no OAuth scope requirement. Scope/admission reconnaissance is required before a dispatch; no permission was guessed.","auth");if(!(m.scopes??[]).some(scope=>conn.ok.scopes.includes(scope)))return businessError("permission_denied","Method "+id+" requires one of the declared scopes: "+(m.scopes??[]).join(", ")+". Reauthorize this source; no API-key fallback.","auth");if(input.params.onBehalfOfContentOwner!==void 0&&!conn.ok.scopes.includes("https://www.googleapis.com/auth/youtubepartner"))return businessError("permission_denied","Content-owner operations require the partner scope and linked CMS admission.","auth");let pathname=m.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(input.params)){if(m.parameters?.[key]?.location==="path"){const text=String(value);if(text.split("/").some(segment=>segment==="."||segment==="..")||/[?#%\\]/.test(text))return businessError("invalid_argument","Path parameters cannot contain traversal or encoded routing material.","connector");const reserved=pathname.includes("{+"+key+"}");if(reserved&&!/^[A-Za-z0-9_./-]+$/.test(text))return businessError("invalid_argument","Reserved resource paths must be canonical provider resource names.","connector");pathname=pathname.replace(reserved?"{+"+key+"}":"{"+key+"}",reserved?text.split("/").map(encodeURIComponent).join("/"):encodeURIComponent(text))}else query.set(key,Array.isArray(value)?value.join(","):String(value))}if(pathname.includes("{"))return businessError("invalid_argument","Provider path parameter is missing.","connector");if(input.media)return businessError("failed_precondition","Media upload needs the separately admitted bounded streaming transport; no effect was dispatched.","connector");if(m.id==="youtube.youtube.v3.liveChat.messages.stream")return businessError("failed_precondition","The pinned server-streaming RPC requires an admitted cancelable stream transport; use liveChatMessages.list with pageToken until that profile is enabled.","connector");if(m.httpMethod!=="GET"&&!transport&&!level1)return businessError("failed_precondition","Write transport and original action admission are required for "+id+"; no effect was dispatched.","connector");const url=new URL(pathname,m.baseUrl??"https://www.googleapis.com/");url.search=query.toString();const raw=transport?await transport("youtube",url.href,{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"},signal}):await auth.requestRaw("youtube",url.href,{signal,...level1?{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"}}:{}});if(closed||signal.aborted)return aborted();if(!("ok"in raw))return raw;if(Buffer.byteLength(raw.ok.body,"utf8")>2*1024*1024)return businessError("resource_exhausted","YouTube response exceeds the bounded broker body budget. Use an admitted streaming path; no body was truncated.","connector");const reason=parts.googleErrorReasonV1(raw.ok.body),baseOverride=parts.googleStatusOverrideV1(raw.ok.body),status=parts.webStatusErrorV1(raw.ok.status,{provider:"YouTube",what:id,headers:raw.ok.headers,bodyOverride:status2=>status2===403&&reason==="quotaExceeded"?{code:"resource_exhausted",retryability:"throttling",meaning:"the YouTube project quota bucket is exhausted (quotaExceeded)"}:baseOverride(status2),...reason?{detail:reason}:{}});if(status)return{err:status};if(m.supportsMediaDownload){return Original.ok({method:id,resource:m.resource,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain",items:[{id:input.params.id??input.params.resourceName,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain"}],warnings:[],effect:"read",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}if(raw.ok.status===204||!raw.ok.body)return Original.ok({method:id,resource:m.resource,items:[],warnings:["Provider response carries no body; upstream effect remains unverified."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}});let data;try{data=JSON.parse(raw.ok.body)}catch{return businessError("data_loss","YouTube returned invalid JSON for "+id+".","connector")}if(!object(data))return businessError("data_loss","YouTube response must be an object.","connector");if(data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item))))return businessError("data_loss","YouTube response items are malformed.","connector");if(data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return businessError("data_loss","YouTube nextPageToken is malformed.","connector");const items=Array.isArray(data.items)?data.items:typeof data.id==="string"?[data]:[];return Original.ok({method:id,resource:m.resource,data,items,...typeof data.nextPageToken==="string"?{nextPageToken:data.nextPageToken}:{},warnings:m.httpMethod==="GET"?[]:["HTTP response accepted. Only original action read-after-write/event-confirm can mark EFFECTED."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}function invoke(id,input,options={},level1=false){return track(invokeInner(id,input,options,level1).catch(error=>{if(closed||options.signal?.aborted)return aborted();const cause=object(error)?Original.validateStructuredError(error.structuredError):void 0;return parts.connectorError("unavailable","Trusted YouTube transport failed before a confirmed provider response. Raw custody exception text is not a tool result.","transient",cause&&"ok"in cause?cause.ok:void 0)}))}async function*pages(id,params,options={}){const m=methodMap.get(id);if(!m||m.httpMethod!=="GET"){yield businessError("invalid_argument","Only pinned GET methods can be paginated.","connector");return}if(options.maxPages!==void 0&&(!Number.isInteger(options.maxPages)||options.maxPages<1)){yield businessError("invalid_argument","maxPages must be a positive integer.","connector");return}const seen=new Set;let token=typeof params.pageToken==="string"?params.pageToken:void 0,count=0;for(;;){if(token&&seen.has(token)){yield businessError("failed_precondition","YouTube repeated a page token; coverage is incomplete.","connector");return}if(token)seen.add(token);const result=await invoke(id,{params:{...params,...token?{pageToken:token}:{}}},options);yield result;if(!("ok"in result))return;count++;token=result.ok.nextPageToken;if(!token)return;if(options.maxPages!==void 0&&count>=options.maxPages){yield businessError("resource_exhausted","Selected page budget ended with a nonterminal token; coverage is incomplete.","connector");return}}}async function readInner(request,options={}){if(closed)return unavailable();const bad=validateRead(request,["fileId"]);if(bad)return bad;request=structuredClone(request);if(request.fileId!==void 0&&(!/^[A-Za-z0-9_-]{1,200}$/.test(request.fileId)||request.query!==void 0||request.since!==void 0||request.until!==void 0))return businessError("invalid_argument","An exact YouTube video read takes fileId without query or time bounds.","connector");const selected=request.fileId?"youtube.videos.list":request.query?"youtube.search.list":"youtube.activities.list";const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const connection=await vault.connection("youtube");if(!("ok"in connection))return connection;const captured=structuredClone(connection.ok);if(!captured||captured.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(typeof captured.accountId!=="string"||!captured.accountId.trim())return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");const firstScopes=methodMap.get(selected)?.scopes??[],detailScopes=request.query?methodMap.get("youtube.videos.list")?.scopes??[]:firstScopes,scopes=firstScopes.filter(scope=>detailScopes.includes(scope)),readonly="https://www.googleapis.com/auth/youtube.readonly";const requiredScope=scopes.includes(readonly)&&captured.scopes.includes(readonly)?readonly:scopes.find(scope=>captured.scopes.includes(scope));if(!requiredScope)return businessError("permission_denied","The selected YouTube query requires one of its pinned read scopes.","auth");const fence=async()=>{if(closed||signal.aborted)return aborted();const current=await vault.connection("youtube");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==captured.accountId||!current.ok.scopes.includes(requiredScope))return businessError("permission_denied","YouTube selected read connection or scope changed.","auth");return Original.ok(void 0)};const boundInvoke=async(id,input)=>{const before=await fence();if(!("ok"in before))return before;const answer2=await invoke(id,input,{signal});const after=await fence();return"ok"in after?answer2:after};const wanted=request.limit??1,params=request.fileId?{part:["snippet","contentDetails","status","statistics"],id:[request.fileId]}:request.query?{part:["snippet"],q:request.query,type:["video"],maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}}:{part:["snippet","contentDetails"],mine:true,maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}};let answer=await boundInvoke(selected,{params});if("err"in answer&&selected==="youtube.activities.list"&&answer.err.code==="permission_denied"){const channels=await boundInvoke("youtube.channels.list",{params:{part:["id"],mine:true,maxResults:1}});if("ok"in channels&&!channels.ok.items.length)return readResult("youtube",[],["This Google account has no YouTube channel, so it has no own activity to read; full sync records it as no-youtube-channel."])}if(!("ok"in answer))return answer;const items=[...answer.ok.items],seen=new Set;let steps=1;while(items.length<wanted&&answer.ok.nextPageToken){const token=answer.ok.nextPageToken;if(seen.has(token))return businessError("failed_precondition","Selected YouTube read repeated a token; no complete result was asserted.","connector");seen.add(token);if(++steps>100)return businessError("resource_exhausted","Selected YouTube read exceeded the page budget before satisfying its limit; no complete result was asserted.","connector");answer=await boundInvoke(selected,{params:{...params,pageToken:token}});if(!("ok"in answer))return answer;items.push(...answer.ok.items)}let retained=items.slice(0,wanted),resource=answer.ok.resource;if(request.query&&retained.length){const selectedItems=retained,details=[];for(let index=0;index<selectedItems.length;index+=50){const block=selectedItems.slice(index,index+50),ids=block.map(item=>object(item.id)?item.id.videoId:void 0).filter(id=>typeof id==="string");if(ids.length!==block.length)return businessError("data_loss","A selected YouTube video search result lacks its native video id.","connector");const hydrated=await boundInvoke("youtube.videos.list",{params:{part:["snippet","contentDetails","status","statistics","topicDetails","recordingDetails","localizations"],id:ids}});if(!("ok"in hydrated))return hydrated;for(const item of hydrated.ok.items)details.push({...item,_selection:block.find(selected2=>object(selected2.id)&&selected2.id.videoId===item.id)??null})}retained=details;resource="videos"}const records=retained.map(item=>({source:"youtube",sourceId:captured.accountId+":"+resource+":"+itemId(item),stream:resource,kind:"youtube."+resource.toLowerCase()+".changed",ts:itemTime(item),body:JSON.stringify(item),fields:{...item}}));const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;if(closed||signal.aborted)return aborted();return readResult("youtube",records,[...answer.ok.warnings,...answer.ok.nextPageToken||items.length>wanted?["More provider results exist beyond this selected batch."]:[],...retained.length<Math.min(items.length,wanted)?["Some selected videos are currently inaccessible/deleted; search metadata is retained only as an attributed missing detail, never a fabricated video body."]:[],"This selected API query does not establish complete YouTube account or archive coverage."])}function read(request,options={}){return track(readInner(request,options))}async function importTakeout(root=takeoutRoot??"",options={}){if(closed)return unavailable();if(!root)return businessError("failed_precondition","Supply an explicit extracted read-only Takeout copy; API success cannot substitute for history.","connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;const result=await readTakeout(root,signal);if(!("ok"in result))return result;if(closed||signal.aborted)return aborted();const saved=await cache(vault,"youtube",result.ok.records);if(!("ok"in saved))return saved;return result}const account=async()=>{const row=await vault.connection("youtube");if(!("ok"in row))return row;if(!row.ok||row.ok.state!=="connected")return businessError("unauthenticated","YouTube identity needs a connected account.","auth");if(!row.ok.accountId)return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");return Original.ok(row.ok.accountId)};function actionSchema(schema){const{id:_discoveryType,...result}=schema;if(result.properties)result.properties=Object.fromEntries(Object.entries(result.properties).map(([key,value])=>[key,actionSchema(value)]));if(result.items)result.items=actionSchema(result.items);if(object(result.additionalProperties))result.additionalProperties=actionSchema(result.additionalProperties);return result}const actions={catalog,method:id=>{const result=method(id);if(!("ok"in result))return result;const m=result.ok;return Original.ok({...m,params:actionSchema(m.params),...!m.supportsMediaUpload&&m.id!=="youtube.youtube.v3.liveChat.messages.stream"&&(!m.profile||m.httpMethod==="GET")?{level:1,effect:m.httpMethod==="GET"?"read":"write"}:{}})},invoke:(id,input,options={})=>invoke(id,input,options,true)};const source={info,actions,catalog,method,invoke,pages,read,status:()=>closed?Promise.resolve(Original.ok({...info,state:"unavailable",message:"YouTube source is inactive."})):connectionState(vault,info),connect:options=>closed?Promise.resolve(unavailable()):track(auth.connect("youtube",options)),job:id=>closed?unavailable():auth.job(id),cancelJob:id=>auth.cancelJob(id),importTakeout:(root,options)=>track(importTakeout(root,options)),createConnector:(plan,options={})=>createYouTubeConnector({parts,invoke,method,account,isClosed:()=>closed},plan,options),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}};return source}export function itemId(item){if(typeof item.id==="string")return item.id;if(typeof item.videoId==="string")return item.videoId;if(object(item.id)){for(const key of["videoId","channelId","playlistId"])if(typeof item.id[key]==="string")return key+":"+item.id[key]}const value=JSON.parse(JSON.stringify(item.id??item));return createHash("sha256").update(Original.jcsCanonicalize(value)).digest("hex")}export function itemTime(item){const snippet=object(item.snippet)?item.snippet:{};for(const value of[item.time,item.updated,item.updatedAt,snippet.updatedAt,snippet.publishedAt])if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return"1970-01-01T00:00:00.000Z"}
@@ -1 +1 @@
1
- export*from"./blob-store.js";export*from"./custody.js";export*from"./binding-custody.js";export*from"./connector-supervisor.js";export*from"./local-source.js";export*from"./sqlite-vault.js";export*from"./vault-backup.js";export*from"./vault-sql.js";export*from"./checkpoint-erasure-proof.js";export*from"./metadata.js";export*from"./storage-metadata.js";export*from"./source-sync.js";export*from"./search-text.js";
1
+ export*from"./blob-store.js";export*from"./custody.js";export*from"./binding-custody.js";export*from"./connector-supervisor.js";export*from"./local-source.js";export*from"./sqlite-vault.js";export*from"./vault-backup.js";export*from"./vault-sql.js";export*from"./checkpoint-erasure-proof.js";export*from"./metadata.js";export*from"./storage-metadata.js";export*from"./source-sync.js";export*from"./search-text.js";export*from"./content-acquisition.js";
@@ -0,0 +1 @@
1
+ import{createHash}from"node:crypto";import{Original,canonicalJson,businessError,ok}from"@zortexhq/plugin-connector-framework/api";const hash=value=>createHash("sha256").update(value).digest("hex");const fail=message=>businessError("failed_precondition",message,"auth");const nextId=Original.makeUlidFactory();function scope(db,source){try{const selection=db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const bindings=selection?db.query("SELECT id,metadata FROM account_bindings WHERE source=? AND id=?").all(source,selection.binding_id):db.query("SELECT id,metadata FROM account_bindings WHERE source=?").all(source);if(bindings.length!==1)return fail("Select one verified account before acquiring content.");const row=bindings[0],binding=JSON.parse(row.metadata);if(binding.state!=="connected"||binding.identity?.source!==source||!Number.isFinite(Date.parse(binding.verifiedAt))||!binding.identity.subject&&!binding.authority)return fail("Content acquisition requires a verified account or explicit session authority.");const pin=db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==binding.identity.subject)return fail("Content belongs to a different isolated account.");const grants=db.query("SELECT metadata FROM authorization_grants WHERE binding_id=? AND json_extract(metadata,'$.purpose')='L1' ORDER BY id").all(row.id);if(!grants.some(row2=>{const g=JSON.parse(row2.metadata);return g.purpose==="L1"&&g.state==="active"}))return fail("Content acquisition requires active L1 authorization.");const resources=db.query("SELECT id,revision FROM credential_resources WHERE binding_id=? ORDER BY id").all(row.id);return ok({fingerprint:hash(canonicalJson({selection:selection??null,binding,grants,resources})),identity:hash(canonicalJson(binding.identity.subject?{...binding.identity}:{source,authority:binding.authority}))})}catch{return fail("Content acquisition custody is unavailable; reconnect through the product.")}}export function beginContentAcquisition(deps,source,resource){if(!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof resource!=="string"||!resource.trim()||resource.length>256)return businessError("invalid_argument","A bounded source and resource are required.","storage");if(deps.closed())return fail("Vault is closed.");const captured=scope(deps.db,source);if(!("ok"in captured))return captured;const declared=deps.declare(source);if(!("ok"in declared))return declared;const expires=Date.now()+3e5;let used=false;return ok({append(records,signal){const check=()=>{if(deps.closed()||used||Date.now()>expires)return fail("Acquisition expired or was already committed.");if(signal?.aborted)return businessError("aborted","Content acquisition cancelled.","storage");const current=scope(deps.db,source);return"ok"in current&&current.ok.fingerprint===captured.ok.fingerprint?ok(true):businessError("permission_denied","Account or authorization changed before content commit.","auth")};const admitted=check();if(!("ok"in admitted))return admitted;if(!Array.isArray(records)||records.length>100)return businessError("invalid_argument","Acquire at most 100 reviewed records per page.","storage");const observedAt=new Date().toISOString(),id=nextId(),origin={kind:"connector",source,grant:id};let drafts;try{const ids=new Set;drafts=records.map(row=>{if(!row||typeof row.id!=="string"||!row.id||row.id.length>4096||ids.has(row.id)||typeof row.body!=="string"||!row.fields||typeof row.fields!=="object"||Array.isArray(row.fields)||Object.hasOwn(row.fields,"acquisition")||row.ts!==void 0&&(!Number.isFinite(Date.parse(row.ts))||new Date(row.ts).toISOString()!==row.ts))throw Error();ids.add(row.id);const payload=JSON.parse(canonicalJson({...row.fields,acquisition:{resource,nativeId:row.id,scope:"acquired",identity:captured.ok.identity}}));return{nk:{source,stream:"acquired-content",sourceId:hash(canonicalJson({identity:captured.ok.identity,resource,id:row.id})),rev:""},ts:row.ts??observedAt,tier:"api",kind:"content.acquired",schemaVersion:1,mentions:[],body:row.body,payload}});if(Buffer.byteLength(canonicalJson(drafts))>4*1024*1024)return businessError("resource_exhausted","Acquisition page exceeds the complete-content budget.","storage")}catch{return businessError("invalid_argument","Acquisition requires unique IDs and complete JSON content.","storage")}let receipt;const save=results=>{if(results.some(row=>!["appended","duplicate","head-noop"].includes(row.outcome)))return businessError("data_loss","Content was not durably accepted.","storage");receipt={id,source,resource,scope:"acquired",returned:records.length,persisted:results.length,observedAt};deps.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,1,?)").run("content-acquisition",id,canonicalJson(receipt));return ok(true)};if(drafts.length){const result=deps.append(drafts,origin,check,save);if(!("ok"in result))return result}else{try{deps.db.exec("BEGIN IMMEDIATE");const checked=check();if(!("ok"in checked)){deps.db.exec("ROLLBACK");return checked}save([]);deps.db.exec("COMMIT")}catch{try{deps.db.exec("ROLLBACK")}catch{}return businessError("unavailable","Empty acquisition receipt could not commit.","storage")}}used=true;return ok(receipt)}})}export function contentAcquisitionScopes(db){const sources=db.query("SELECT DISTINCT source FROM events WHERE stream='acquired-content'").all();return sources.flatMap(({source})=>{const current=scope(db,source);return"ok"in current?[{source,identity:current.ok.identity}]:[]})}
@@ -1 +1 @@
1
- import{Original,businessError,ok,canonicalJson}from"@zortexhq/plugin-connector-framework/api";import{mkdirSync}from"node:fs";import{dirname,isAbsolute}from"node:path";import{randomUUID}from"node:crypto";import{Database}from"./sqlite.js";import{assertNotRecovery}from"./recovery-guard.js";import{rebuildCurrentRecords,updateCurrentRecords}from"./current-records.js";import{rebuildSearchRecords}from"./search-records.js";import{SCHEMA}from"./schema.js";import{LiftedRecordRules}from"./record-rules.js";import{createSqliteAppendPort}from"./append-port.js";import{createIdReader}from"./id-read.js";import{createProcessJournal,PROCESS_JOURNAL_SCHEMA}from"./process-journal.js";import{createLocalSourceRegistry,LOCAL_SOURCE_SCHEMA}from"./local-source-registry.js";import{createSqlReader,sqlLimits,DEFAULT_SQL_LIMITS}from"./sql.js";import{createBlobPort}from"./blob-port.js";import{createSourcePrincipalPort}from"./source-principal-port.js";import{createSnapshotReader}from"./snapshot.js";import{createCheckpointErasureProof}from"./checkpoint-erasure-proof.js";import{createStorageMetadataReader}from"./storage-metadata.js";import{createSourceSyncStore}from"./source-sync.js";export const name="zortex-sqlite-vault";export{createVaultMcp,startVaultMcp,vaultTools}from"./mcp.js";const inactive=()=>Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"SQLite Vault is closed."});export class SqliteVault{identity;db;records;facts;closed=false;declarations=new Map;authorities=new Map;requiredAuthorities=new Set;readPageRows;reader;snapshots;storageMetadata;constructor(config){if(!config||typeof config.file!=="string"||!isAbsolute(config.file)||!Array.isArray(config.streams))throw Error("SQLite Vault requires an absolute file and declared streams.");const backupNamespaces=config.backupPrivateNamespaces??[];if(!Array.isArray(backupNamespaces)||backupNamespaces.length>64||backupNamespaces.some(n=>typeof n!=="string"||!/^[a-z][a-z0-9.-]{0,63}$/.test(n)))throw Error("Invalid trusted backup namespace policy.");const busy=config.busyTimeoutMs??3e3;if(!Number.isSafeInteger(busy)||busy<1||busy>6e4)throw Error("SQLite busy timeout must be 1\u201360000 ms.");const pageRows=config.readPageRows??128;if(!Number.isSafeInteger(pageRows)||pageRows<1||pageRows>4096)throw Error("SQLite read page must be 1\u20134096 rows.");this.readPageRows=pageRows;const readLimits=sqlLimits(config.sql??DEFAULT_SQL_LIMITS);if(config.execution&&(!config.execution.runId||!config.execution.codeVersion))throw Error("Execution binding requires run identity and code version.");assertNotRecovery(config.file,busy);mkdirSync(dirname(config.file),{recursive:true});this.db=new Database(config.file);try{this.db.exec(`PRAGMA busy_timeout=${busy};`);const version=this.db.query("PRAGMA user_version").get().user_version;if(version!==0&&version!==1)throw Error("Unsupported SQLite Vault schema version.");const populated=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get()!==null;if(populated){const hasMeta=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").get()!==null;if(!hasMeta||this.db.query("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error("Different SQLite format; select a new Vault file.")}this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;");this.db.exec("BEGIN IMMEDIATE");try{this.db.exec(SCHEMA+PROCESS_JOURNAL_SCHEMA+LOCAL_SOURCE_SCHEMA);this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('zortex-sqlite-vault-format','1')").run();this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('vault-identity',?)").run(randomUUID());this.db.exec("PRAGMA user_version=1; COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}this.identity=this.db.query("SELECT value FROM meta WHERE key='vault-identity'").get().value;this.snapshots=createSnapshotReader(config.file,this.identity,[...backupNamespaces]);this.storageMetadata=createStorageMetadataReader(this.db,config.file,()=>this.closed);const now=config.now??(()=>new Date().toISOString());const saved=this.db.query("SELECT definition FROM source_streams ORDER BY source,stream").all().map(row=>JSON.parse(row.definition));for(const row of this.db.query("SELECT source FROM source_authority_required").all())this.requiredAuthorities.add(row.source);this.records=new LiftedRecordRules(this.db,saved,now,"events",config.execution,origin=>{const binding=this.authorities.get(origin.source);return!binding&&!this.requiredAuthorities.has(origin.source)&&!this.db.query("SELECT 1 FROM source_authority_required WHERE source=?").get(origin.source)?Original.ok(true):binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Required source append authority is inactive."})},event=>updateCurrentRecords(this.db,this.records,event));this.facts=new LiftedRecordRules(this.db,saved,now,"system_events",void 0,void 0,event=>updateCurrentRecords(this.db,this.records,event));for(const row of saved)this.declarations.set(row.source+"\0"+row.stream,row);const admitted=this.registerStreams(config.streams);if(!Original.isOk(admitted))throw Error("Source stream declaration changed or is invalid.");rebuildCurrentRecords(this.db,this.records);rebuildSearchRecords(this.db);this.reader=createSqlReader(config.file,readLimits)}catch(error){this.db.close();throw error}}createAppendPort(){return createSqliteAppendPort(this.db,this,()=>this.closed,this.readPageRows)}storageSnapshot(){return this.storageMetadata()}createSourceSyncStore(){return createSourceSyncStore(this.createPrivateStore("source-sync"))}createBlobPort(){return createBlobPort(this.db,()=>this.closed,origin=>{const binding=this.authorities.get(origin.source);return binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Connector blob bytes require a current trusted source authority binding."})})}createSourcePrincipalPort(){return createSourcePrincipalPort(this.db,()=>this.closed)}registerConnectorAuthority(source,authorize){return this.registerAuthority(source,authorize,false)}registerAuthority(source,authorize,bindingAuthority){if(this.closed||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof authorize!=="function")throw Error("Invalid trusted source authority binding.");if(this.authorities.get(source)?.active)throw Error("Source authority is already bound.");if(!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source))throw Error("Isolated source requires binding authority.");this.db.query("INSERT OR IGNORE INTO source_authority_required(source) VALUES(?)").run(source);this.requiredAuthorities.add(source);const binding={authorize:origin=>!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source)?Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Isolated source requires binding authority."}):authorize(origin),active:true};this.authorities.set(source,binding);return()=>{binding.active=false}}registerConnectedSourceAuthority(source,expected){if(!Original.isUlid(expected?.grant)||typeof expected.account!=="string"||!expected.account||typeof expected.updatedAt!=="string"||!Number.isFinite(Date.parse(expected.updatedAt))||!Array.isArray(expected.scopes)||!expected.scopes.length||expected.scopes.some(scope=>typeof scope!=="string"||!scope))throw Error("Invalid connected source authority epoch.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Source identity or consent changed before append."});return this.registerConnectorAuthority(source,origin=>{if(origin.grant!==expected.grant)return denied();const row=this.db.query("SELECT metadata FROM connections WHERE source=?").get(source);if(!row)return denied();let current;try{current=JSON.parse(row.metadata)}catch{return denied()}if(!current||typeof current!=="object"||Array.isArray(current))return denied();const info=current;const scopes=info.scopes;if(info.source!==source||info.provider!=="google"||info.state!=="connected"||info.updatedAt!==expected.updatedAt||(info.accountId??info.account)!==expected.account||!Array.isArray(scopes)||expected.scopes.some(scope=>!scopes.includes(scope)))return denied();return Original.ok(true)})}registerBindingSourceAuthority(source,expected){const positive=value=>Number.isSafeInteger(value)&&Number(value)>0;const text=value=>typeof value==="string"&&value.length>0&&value.length<=2048;if(!expected||!Original.isUlid(expected.grant)||![expected.bindingId,expected.subject,expected.custodyGrantId,expected.audience].every(text)||![expected.bindingRevision,expected.custodyGrantRevision,expected.selectionRevision].every(positive)||!Number.isSafeInteger(expected.scopeEpoch)||expected.scopeEpoch<0||!Array.isArray(expected.scopes)||!expected.scopes.length||!expected.scopes.every(text))throw Error("Invalid binding source authority epoch.");if((expected.credentialResourceId!==void 0||expected.credentialResourceRevision!==void 0)&&(!text(expected.credentialResourceId)||!positive(expected.credentialResourceRevision)))throw Error("Invalid credential resource epoch.");const epoch={...expected,scopes:[...new Set(expected.scopes)].sort()};const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==epoch.subject)throw Error("Isolated source is pinned to a different subject.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Selected source identity or consent changed before append."});const withdraw=this.registerAuthority(source,origin=>{if(origin.grant!==epoch.grant)return denied();try{const pin2=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin2&&pin2.subject!==epoch.subject)return denied();const selection=this.db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const binding=this.db.query("SELECT source,subject,revision,metadata FROM account_bindings WHERE id=?").get(epoch.bindingId);const grant=this.db.query("SELECT binding_id,revision,metadata FROM authorization_grants WHERE id=?").get(epoch.custodyGrantId);if(!selection||selection.binding_id!==epoch.bindingId||selection.revision!==epoch.selectionRevision||!binding||binding.source!==source||binding.subject!==epoch.subject||binding.revision!==epoch.bindingRevision||!grant||grant.binding_id!==epoch.bindingId||grant.revision!==epoch.custodyGrantRevision)return denied();if(epoch.credentialResourceId!==void 0){const resource=this.db.query("SELECT binding_id,kind,owner_key,revision FROM credential_resources WHERE id=?").get(epoch.credentialResourceId);if(!resource||resource.binding_id!==epoch.bindingId||resource.kind!=="oauth"||resource.owner_key!=="resident"||resource.revision!==epoch.credentialResourceRevision)return denied()}const b=JSON.parse(binding.metadata),g=JSON.parse(grant.metadata);if(b.id!==epoch.bindingId||b.revision!==epoch.bindingRevision||b.state!=="connected"||b.identity?.source!==source||b.identity?.subject!==epoch.subject||!Number.isFinite(Date.parse(b.verifiedAt))||g.id!==epoch.custodyGrantId||g.revision!==epoch.custodyGrantRevision||g.bindingId!==epoch.bindingId||g.state!=="active"||g.purpose!=="L1"||g.audience!==epoch.audience||g.scopeEpoch!==epoch.scopeEpoch||!Array.isArray(g.scopes)||JSON.stringify([...new Set(g.scopes)].sort())!==JSON.stringify(epoch.scopes))return denied();return Original.ok(true)}catch{return denied()}},true);return withdraw}createOriginalLogPort(){const port=this.createAppendPort();return{append:(batch,origin)=>origin.kind==="kernel"||origin.kind==="derivation"?this.appendSystem(batch,origin):this.append(batch,origin),readGeneration:port.readGeneration,scan:port.scan,scanMetadata:port.scanMetadata,headById:createIdReader(this.db,()=>this.closed),beginCooperativePageDrain:port.beginCooperativePageDrain,finishCooperativePageDrain:port.finishCooperativePageDrain,cancelCooperativePageDrain:port.cancelCooperativePageDrain}}createCheckpointErasureProof(){return createCheckpointErasureProof(this)}registerStreams(streams){if(this.closed)return inactive();if(!Array.isArray(streams)||streams.length>1e3)return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Source declaration batch is invalid."});const incoming=new Map;for(const candidate of streams){if(!candidate||Object.keys(candidate).some(key2=>!["source","stream","revOrder","comparator","quality","noneIdentity","deleteKind"].includes(key2))||candidate.deleteKind!==void 0&&(typeof candidate.deleteKind!=="string"||!candidate.deleteKind)||typeof candidate.source!=="string"||!candidate.source||typeof candidate.stream!=="string"||!candidate.stream||!Original.REV_ORDERS.includes(candidate.revOrder)||candidate.comparator!==void 0&&!["numeric","lex"].includes(candidate.comparator)||candidate.quality!==void 0&&!Original.DECLARABLE_IDENTITY_QUALITIES.includes(candidate.quality))return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid source stream declaration."});const key=candidate.source+"\0"+candidate.stream,prior=incoming.get(key)??this.declarations.get(key);const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row))return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Existing source stream authority changed; explicit migration is required."});incoming.set(key,JSON.parse(canonicalJson(row)))}this.db.exec("BEGIN IMMEDIATE");try{for(const[key,candidate]of incoming){const existing=this.db.query("SELECT definition FROM source_streams WHERE source=? AND stream=?").get(candidate.source,candidate.stream);const prior=existing?JSON.parse(existing.definition):void 0;const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row)){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Another owner declared a different stream authority."})}incoming.set(key,row);this.db.query("INSERT INTO source_streams(source,stream,definition) VALUES(?,?,?) ON CONFLICT(source,stream) DO UPDATE SET definition=excluded.definition").run(row.source,row.stream,canonicalJson(row))}this.db.exec("COMMIT")}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Stream binding did not commit."})}for(const[key,row]of incoming){this.declarations.set(key,row);this.records.registerStream(row);this.facts.registerStream(row)}return Original.ok(true)}createProcessJournal(){return createProcessJournal(this.db,()=>this.closed)}createPrivateStore(namespace){if(!/^[a-z][a-z0-9.-]{0,63}$/.test(namespace))throw Error("Private storage namespace must be declared by the trusted host.");const valid=key=>typeof key==="string"&&key.length>0&&key.length<=500,invalid=()=>businessError("invalid_argument","Invalid private key, value or revision.","storage");const unavailable=error=>businessError("unavailable",`Private state is temporarily busy${error instanceof Error&&error.message.includes("locked")?" (locked)":""}.`,"storage");const busy=error=>error instanceof Error&&(/SQLITE_BUSY|database is locked|database is busy/i.test(error.message)||error.code==="SQLITE_BUSY");const read=key=>{const row=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key=?").get(namespace,key);return row?{key:row.key,revision:row.revision,value:JSON.parse(row.value)}:null};const decode=row=>({key:row.key,revision:row.revision,value:JSON.parse(row.value)});const listPage=(options={})=>{if(this.closed)return inactive();const after=options.after??"",limit=options.limit??100;if(options.after!==void 0&&!valid(options.after)||!Number.isSafeInteger(limit)||limit<1||limit>1e3)return invalid();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key>? ORDER BY key LIMIT ?").all(namespace,after,limit+1),more=rows.length>limit,items=rows.slice(0,limit).map(decode);return ok({items,...more&&items.length?{next:items.at(-1).key}:{}})}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state page could not be read.","storage")}};const guardValid=guard=>guard===void 0||!!guard&&typeof guard==="object"&&valid(guard.key)&&Number.isSafeInteger(guard.revision)&&guard.revision>0;const guarded=guard=>guard===void 0||read(guard.key)?.revision===guard.revision;const remove=(key,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before deleting this value.","storage")}this.db.query("DELETE FROM private_state WHERE namespace=? AND key=?").run(namespace,key);this.db.exec("COMMIT");begun=false;return ok(true)}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state deletion did not complete.","storage")}};return{delete:remove,get:key=>{if(this.closed)return inactive();if(!valid(key))return invalid();try{return ok(read(key))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be read.","storage")}},list:()=>{if(this.closed)return inactive();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? ORDER BY key LIMIT 10001").all(namespace);if(rows.length>1e4)return businessError("resource_exhausted","Private namespace exceeds the complete-read budget; use listPage.","storage");return ok(rows.map(decode))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be listed.","storage")}},listPage,put:(key,value,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let encoded;try{encoded=canonicalJson(value);if(Buffer.byteLength(encoded)>4*1024*1024)return businessError("resource_exhausted","Private state exceeds its complete-value budget.","storage")}catch{return invalid()}let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before applying this transition.","storage")}const revision=expected+1;this.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET revision=excluded.revision,value=excluded.value").run(namespace,key,revision,encoded);this.db.exec("COMMIT");begun=false;return ok({key,revision,value:JSON.parse(encoded)})}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state transaction did not complete.","storage")}}}}createLocalSourceRegistry(){return createLocalSourceRegistry(this.db,()=>this.closed)}sql(request,signal){return this.closed?Promise.resolve(inactive()):this.reader.sql(request,signal)}exportDataSnapshot(...args){return this.snapshots.exportDataSnapshot(...args)}append(batch,origin){return this.closed?inactive():this.records.appendCore(batch,origin)}appendFacts(batch){return this.closed?inactive():this.facts.appendCore(batch,{kind:"kernel"},true)}appendSystem(batch,origin){if(this.closed)return inactive();if(origin?.kind==="connector")return Original.errResult({code:"permission_denied",layer:"storage",retryability:"non-retryable",message:"Connector authority cannot write system facts."});return this.facts.appendCore(batch,origin)}importErasureDecisions(decisions){if(this.closed)throw Error("SQLite Vault is closed.");for(const row of decisions)if(!row||typeof row.source!=="string"||typeof row.stream!=="string"||typeof row.source_id!=="string"||typeof row.rev!=="string"||typeof row.kind!=="string"||!/^[0-9a-f]{64}$/.test(row.content_hash)||!Original.isUlid(row.tomb_id)||row.future_too!==0&&row.future_too!==1||Number.isNaN(Date.parse(row.ts)))throw Error("Invalid erasure decision.");this.db.exec("BEGIN IMMEDIATE");try{if(this.db.query("SELECT 1 FROM events LIMIT 1").get()!==null)throw Error("Erasure decisions must be imported before user records.");const put=this.db.query("INSERT OR REPLACE INTO tombstones(source,stream,source_id,rev,content_hash,tomb_id,future_too,ts,kind) VALUES (?,?,?,?,?,?,?,?,?)");for(const row of decisions)put.run(row.source,row.stream,row.source_id,row.rev,row.content_hash,row.tomb_id,row.future_too,row.ts,row.kind);this.db.exec("COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}}close(){if(!this.closed){this.closed=true;void this.reader.close();void this.snapshots.close();this.db.close()}}async closeAsync(){this.close();await Promise.all([this.reader.close(),this.snapshots.close()])}}export async function apply(ctx,config){const vault=new SqliteVault(config);ctx.reflect.provide("zortexSqliteVault",vault);ctx.reflect.provide("zortexConnectorStorage",{identity:vault.identity,appendPort:vault.createAppendPort(),declareStreams:streams=>vault.registerStreams(streams)});ctx.reflect.provide("zortexConnectorProcessJournal",vault.createProcessJournal());ctx.reflect.provide("zortexLocalSourceRegistry",vault.createLocalSourceRegistry());return()=>vault.closeAsync()}
1
+ import{Original,businessError,ok,canonicalJson}from"@zortexhq/plugin-connector-framework/api";import{mkdirSync}from"node:fs";import{dirname,isAbsolute}from"node:path";import{beginContentAcquisition,contentAcquisitionScopes}from"./content-acquisition.js";import{randomUUID}from"node:crypto";import{Database}from"./sqlite.js";import{assertNotRecovery}from"./recovery-guard.js";import{rebuildCurrentRecords,updateCurrentRecords}from"./current-records.js";import{rebuildSearchRecords}from"./search-records.js";import{SCHEMA}from"./schema.js";import{LiftedRecordRules}from"./record-rules.js";import{createSqliteAppendPort}from"./append-port.js";import{createIdReader}from"./id-read.js";import{createProcessJournal,PROCESS_JOURNAL_SCHEMA}from"./process-journal.js";import{createLocalSourceRegistry,LOCAL_SOURCE_SCHEMA}from"./local-source-registry.js";import{createSqlReader,sqlLimits,DEFAULT_SQL_LIMITS}from"./sql.js";import{createBlobPort}from"./blob-port.js";import{createSourcePrincipalPort}from"./source-principal-port.js";import{createSnapshotReader}from"./snapshot.js";import{createCheckpointErasureProof}from"./checkpoint-erasure-proof.js";import{createStorageMetadataReader}from"./storage-metadata.js";import{createSourceSyncStore}from"./source-sync.js";export const name="zortex-sqlite-vault";export{createVaultMcp,startVaultMcp,vaultTools}from"./mcp.js";const inactive=()=>Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"SQLite Vault is closed."});export class SqliteVault{identity;db;records;facts;closed=false;declarations=new Map;authorities=new Map;acquisitionAuthorities=new Map;requiredAuthorities=new Set;readPageRows;reader;snapshots;storageMetadata;constructor(config){if(!config||typeof config.file!=="string"||!isAbsolute(config.file)||!Array.isArray(config.streams))throw Error("SQLite Vault requires an absolute file and declared streams.");const backupNamespaces=config.backupPrivateNamespaces??[];if(!Array.isArray(backupNamespaces)||backupNamespaces.length>64||backupNamespaces.some(n=>typeof n!=="string"||!/^[a-z][a-z0-9.-]{0,63}$/.test(n)))throw Error("Invalid trusted backup namespace policy.");const busy=config.busyTimeoutMs??3e3;if(!Number.isSafeInteger(busy)||busy<1||busy>6e4)throw Error("SQLite busy timeout must be 1\u201360000 ms.");const pageRows=config.readPageRows??128;if(!Number.isSafeInteger(pageRows)||pageRows<1||pageRows>4096)throw Error("SQLite read page must be 1\u20134096 rows.");this.readPageRows=pageRows;const readLimits=sqlLimits(config.sql??DEFAULT_SQL_LIMITS);if(config.execution&&(!config.execution.runId||!config.execution.codeVersion))throw Error("Execution binding requires run identity and code version.");assertNotRecovery(config.file,busy);mkdirSync(dirname(config.file),{recursive:true});this.db=new Database(config.file);try{this.db.exec(`PRAGMA busy_timeout=${busy};`);const version=this.db.query("PRAGMA user_version").get().user_version;if(version!==0&&version!==1)throw Error("Unsupported SQLite Vault schema version.");const populated=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get()!==null;if(populated){const hasMeta=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").get()!==null;if(!hasMeta||this.db.query("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error("Different SQLite format; select a new Vault file.")}this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;");this.db.exec("BEGIN IMMEDIATE");try{this.db.exec(SCHEMA+PROCESS_JOURNAL_SCHEMA+LOCAL_SOURCE_SCHEMA);this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('zortex-sqlite-vault-format','1')").run();this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('vault-identity',?)").run(randomUUID());this.db.exec("PRAGMA user_version=1; COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}this.identity=this.db.query("SELECT value FROM meta WHERE key='vault-identity'").get().value;this.snapshots=createSnapshotReader(config.file,this.identity,[...backupNamespaces]);this.storageMetadata=createStorageMetadataReader(this.db,config.file,()=>this.closed);const now=config.now??(()=>new Date().toISOString());const saved=this.db.query("SELECT definition FROM source_streams ORDER BY source,stream").all().map(row=>JSON.parse(row.definition));for(const row of this.db.query("SELECT source FROM source_authority_required").all())this.requiredAuthorities.add(row.source);this.records=new LiftedRecordRules(this.db,saved,now,"events",config.execution,origin=>{const acquisition=this.acquisitionAuthorities.get(origin.source+"\0"+origin.grant);if(acquisition)return acquisition();const binding=this.authorities.get(origin.source);return!binding&&!this.requiredAuthorities.has(origin.source)&&!this.db.query("SELECT 1 FROM source_authority_required WHERE source=?").get(origin.source)?Original.ok(true):binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Required source append authority is inactive."})},event=>updateCurrentRecords(this.db,this.records,event));this.facts=new LiftedRecordRules(this.db,saved,now,"system_events",void 0,void 0,event=>updateCurrentRecords(this.db,this.records,event));for(const row of saved)this.declarations.set(row.source+"\0"+row.stream,row);const admitted=this.registerStreams(config.streams);if(!Original.isOk(admitted))throw Error("Source stream declaration changed or is invalid.");rebuildCurrentRecords(this.db,this.records);rebuildSearchRecords(this.db);this.reader=createSqlReader(config.file,readLimits)}catch(error){this.db.close();throw error}}createAppendPort(){return createSqliteAppendPort(this.db,this,()=>this.closed,this.readPageRows)}storageSnapshot(){return this.storageMetadata()}createSourceSyncStore(){return createSourceSyncStore(this.createPrivateStore("source-sync"))}createBlobPort(){return createBlobPort(this.db,()=>this.closed,origin=>{const binding=this.authorities.get(origin.source);return binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Connector blob bytes require a current trusted source authority binding."})})}createSourcePrincipalPort(){return createSourcePrincipalPort(this.db,()=>this.closed)}registerConnectorAuthority(source,authorize){return this.registerAuthority(source,authorize,false)}registerAuthority(source,authorize,bindingAuthority){if(this.closed||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof authorize!=="function")throw Error("Invalid trusted source authority binding.");if(this.authorities.get(source)?.active)throw Error("Source authority is already bound.");if(!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source))throw Error("Isolated source requires binding authority.");this.db.query("INSERT OR IGNORE INTO source_authority_required(source) VALUES(?)").run(source);this.requiredAuthorities.add(source);const binding={authorize:origin=>!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source)?Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Isolated source requires binding authority."}):authorize(origin),active:true};this.authorities.set(source,binding);return()=>{binding.active=false}}registerConnectedSourceAuthority(source,expected){if(!Original.isUlid(expected?.grant)||typeof expected.account!=="string"||!expected.account||typeof expected.updatedAt!=="string"||!Number.isFinite(Date.parse(expected.updatedAt))||!Array.isArray(expected.scopes)||!expected.scopes.length||expected.scopes.some(scope=>typeof scope!=="string"||!scope))throw Error("Invalid connected source authority epoch.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Source identity or consent changed before append."});return this.registerConnectorAuthority(source,origin=>{if(origin.grant!==expected.grant)return denied();const row=this.db.query("SELECT metadata FROM connections WHERE source=?").get(source);if(!row)return denied();let current;try{current=JSON.parse(row.metadata)}catch{return denied()}if(!current||typeof current!=="object"||Array.isArray(current))return denied();const info=current;const scopes=info.scopes;if(info.source!==source||info.provider!=="google"||info.state!=="connected"||info.updatedAt!==expected.updatedAt||(info.accountId??info.account)!==expected.account||!Array.isArray(scopes)||expected.scopes.some(scope=>!scopes.includes(scope)))return denied();return Original.ok(true)})}registerBindingSourceAuthority(source,expected){const positive=value=>Number.isSafeInteger(value)&&Number(value)>0;const text=value=>typeof value==="string"&&value.length>0&&value.length<=2048;if(!expected||!Original.isUlid(expected.grant)||![expected.bindingId,expected.subject,expected.custodyGrantId,expected.audience].every(text)||![expected.bindingRevision,expected.custodyGrantRevision,expected.selectionRevision].every(positive)||!Number.isSafeInteger(expected.scopeEpoch)||expected.scopeEpoch<0||!Array.isArray(expected.scopes)||!expected.scopes.length||!expected.scopes.every(text))throw Error("Invalid binding source authority epoch.");if((expected.credentialResourceId!==void 0||expected.credentialResourceRevision!==void 0)&&(!text(expected.credentialResourceId)||!positive(expected.credentialResourceRevision)))throw Error("Invalid credential resource epoch.");const epoch={...expected,scopes:[...new Set(expected.scopes)].sort()};const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==epoch.subject)throw Error("Isolated source is pinned to a different subject.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Selected source identity or consent changed before append."});const withdraw=this.registerAuthority(source,origin=>{if(origin.grant!==epoch.grant)return denied();try{const pin2=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin2&&pin2.subject!==epoch.subject)return denied();const selection=this.db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const binding=this.db.query("SELECT source,subject,revision,metadata FROM account_bindings WHERE id=?").get(epoch.bindingId);const grant=this.db.query("SELECT binding_id,revision,metadata FROM authorization_grants WHERE id=?").get(epoch.custodyGrantId);if(!selection||selection.binding_id!==epoch.bindingId||selection.revision!==epoch.selectionRevision||!binding||binding.source!==source||binding.subject!==epoch.subject||binding.revision!==epoch.bindingRevision||!grant||grant.binding_id!==epoch.bindingId||grant.revision!==epoch.custodyGrantRevision)return denied();if(epoch.credentialResourceId!==void 0){const resource=this.db.query("SELECT binding_id,kind,owner_key,revision FROM credential_resources WHERE id=?").get(epoch.credentialResourceId);if(!resource||resource.binding_id!==epoch.bindingId||resource.kind!=="oauth"||resource.owner_key!=="resident"||resource.revision!==epoch.credentialResourceRevision)return denied()}const b=JSON.parse(binding.metadata),g=JSON.parse(grant.metadata);if(b.id!==epoch.bindingId||b.revision!==epoch.bindingRevision||b.state!=="connected"||b.identity?.source!==source||b.identity?.subject!==epoch.subject||!Number.isFinite(Date.parse(b.verifiedAt))||g.id!==epoch.custodyGrantId||g.revision!==epoch.custodyGrantRevision||g.bindingId!==epoch.bindingId||g.state!=="active"||g.purpose!=="L1"||g.audience!==epoch.audience||g.scopeEpoch!==epoch.scopeEpoch||!Array.isArray(g.scopes)||JSON.stringify([...new Set(g.scopes)].sort())!==JSON.stringify(epoch.scopes))return denied();return Original.ok(true)}catch{return denied()}},true);return withdraw}contentAcquisitionScopes(){return this.closed?[]:contentAcquisitionScopes(this.db)}beginContentAcquisition(source,resource){return beginContentAcquisition({db:this.db,closed:()=>this.closed,declare:source2=>this.registerStreams([{source:source2,stream:"acquired-content",revOrder:"head-compare",quality:"durable"}]),append:(drafts,origin,check,after)=>{const key=origin.source+"\0"+origin.grant;this.acquisitionAuthorities.set(key,check);try{return this.records.appendCore(drafts,origin,false,{before:check,after})}finally{this.acquisitionAuthorities.delete(key)}}},source,resource)}createOriginalLogPort(){const port=this.createAppendPort();return{append:(batch,origin)=>origin.kind==="kernel"||origin.kind==="derivation"?this.appendSystem(batch,origin):this.append(batch,origin),readGeneration:port.readGeneration,scan:port.scan,scanMetadata:port.scanMetadata,headById:createIdReader(this.db,()=>this.closed),beginCooperativePageDrain:port.beginCooperativePageDrain,finishCooperativePageDrain:port.finishCooperativePageDrain,cancelCooperativePageDrain:port.cancelCooperativePageDrain}}createCheckpointErasureProof(){return createCheckpointErasureProof(this)}registerStreams(streams){if(this.closed)return inactive();if(!Array.isArray(streams)||streams.length>1e3)return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Source declaration batch is invalid."});const incoming=new Map;for(const candidate of streams){if(!candidate||Object.keys(candidate).some(key2=>!["source","stream","revOrder","comparator","quality","noneIdentity","deleteKind"].includes(key2))||candidate.deleteKind!==void 0&&(typeof candidate.deleteKind!=="string"||!candidate.deleteKind)||typeof candidate.source!=="string"||!candidate.source||typeof candidate.stream!=="string"||!candidate.stream||!Original.REV_ORDERS.includes(candidate.revOrder)||candidate.comparator!==void 0&&!["numeric","lex"].includes(candidate.comparator)||candidate.quality!==void 0&&!Original.DECLARABLE_IDENTITY_QUALITIES.includes(candidate.quality))return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid source stream declaration."});const key=candidate.source+"\0"+candidate.stream,prior=incoming.get(key)??this.declarations.get(key);const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row))return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Existing source stream authority changed; explicit migration is required."});incoming.set(key,JSON.parse(canonicalJson(row)))}this.db.exec("BEGIN IMMEDIATE");try{for(const[key,candidate]of incoming){const existing=this.db.query("SELECT definition FROM source_streams WHERE source=? AND stream=?").get(candidate.source,candidate.stream);const prior=existing?JSON.parse(existing.definition):void 0;const row={...candidate,...candidate.deleteKind===void 0&&prior?.deleteKind!==void 0?{deleteKind:prior.deleteKind}:{}};if(prior&&canonicalJson({...prior,...prior.deleteKind===void 0&&row.deleteKind!==void 0?{deleteKind:row.deleteKind}:{}})!==canonicalJson(row)){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Another owner declared a different stream authority."})}incoming.set(key,row);this.db.query("INSERT INTO source_streams(source,stream,definition) VALUES(?,?,?) ON CONFLICT(source,stream) DO UPDATE SET definition=excluded.definition").run(row.source,row.stream,canonicalJson(row))}this.db.exec("COMMIT")}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Stream binding did not commit."})}for(const[key,row]of incoming){this.declarations.set(key,row);this.records.registerStream(row);this.facts.registerStream(row)}return Original.ok(true)}createProcessJournal(){return createProcessJournal(this.db,()=>this.closed)}createPrivateStore(namespace){if(!/^[a-z][a-z0-9.-]{0,63}$/.test(namespace))throw Error("Private storage namespace must be declared by the trusted host.");const valid=key=>typeof key==="string"&&key.length>0&&key.length<=500,invalid=()=>businessError("invalid_argument","Invalid private key, value or revision.","storage");const unavailable=error=>businessError("unavailable",`Private state is temporarily busy${error instanceof Error&&error.message.includes("locked")?" (locked)":""}.`,"storage");const busy=error=>error instanceof Error&&(/SQLITE_BUSY|database is locked|database is busy/i.test(error.message)||error.code==="SQLITE_BUSY");const read=key=>{const row=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key=?").get(namespace,key);return row?{key:row.key,revision:row.revision,value:JSON.parse(row.value)}:null};const decode=row=>({key:row.key,revision:row.revision,value:JSON.parse(row.value)});const listPage=(options={})=>{if(this.closed)return inactive();const after=options.after??"",limit=options.limit??100;if(options.after!==void 0&&!valid(options.after)||!Number.isSafeInteger(limit)||limit<1||limit>1e3)return invalid();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key>? ORDER BY key LIMIT ?").all(namespace,after,limit+1),more=rows.length>limit,items=rows.slice(0,limit).map(decode);return ok({items,...more&&items.length?{next:items.at(-1).key}:{}})}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state page could not be read.","storage")}};const guardValid=guard=>guard===void 0||!!guard&&typeof guard==="object"&&valid(guard.key)&&Number.isSafeInteger(guard.revision)&&guard.revision>0;const guarded=guard=>guard===void 0||read(guard.key)?.revision===guard.revision;const remove=(key,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before deleting this value.","storage")}this.db.query("DELETE FROM private_state WHERE namespace=? AND key=?").run(namespace,key);this.db.exec("COMMIT");begun=false;return ok(true)}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state deletion did not complete.","storage")}};return{delete:remove,get:key=>{if(this.closed)return inactive();if(!valid(key))return invalid();try{return ok(read(key))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be read.","storage")}},list:()=>{if(this.closed)return inactive();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? ORDER BY key LIMIT 10001").all(namespace);if(rows.length>1e4)return businessError("resource_exhausted","Private namespace exceeds the complete-read budget; use listPage.","storage");return ok(rows.map(decode))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be listed.","storage")}},listPage,put:(key,value,expected,guard)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0||!guardValid(guard))return invalid();let encoded;try{encoded=canonicalJson(value);if(Buffer.byteLength(encoded)>4*1024*1024)return businessError("resource_exhausted","Private state exceeds its complete-value budget.","storage")}catch{return invalid()}let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;if(!guarded(guard)){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state lease changed before the write.","storage")}const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before applying this transition.","storage")}const revision=expected+1;this.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET revision=excluded.revision,value=excluded.value").run(namespace,key,revision,encoded);this.db.exec("COMMIT");begun=false;return ok({key,revision,value:JSON.parse(encoded)})}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state transaction did not complete.","storage")}}}}createLocalSourceRegistry(){return createLocalSourceRegistry(this.db,()=>this.closed)}sql(request,signal){return this.closed?Promise.resolve(inactive()):this.reader.sql(request,signal)}exportDataSnapshot(...args){return this.snapshots.exportDataSnapshot(...args)}append(batch,origin){return this.closed?inactive():this.records.appendCore(batch,origin)}appendFacts(batch){return this.closed?inactive():this.facts.appendCore(batch,{kind:"kernel"},true)}appendSystem(batch,origin){if(this.closed)return inactive();if(origin?.kind==="connector")return Original.errResult({code:"permission_denied",layer:"storage",retryability:"non-retryable",message:"Connector authority cannot write system facts."});return this.facts.appendCore(batch,origin)}importErasureDecisions(decisions){if(this.closed)throw Error("SQLite Vault is closed.");for(const row of decisions)if(!row||typeof row.source!=="string"||typeof row.stream!=="string"||typeof row.source_id!=="string"||typeof row.rev!=="string"||typeof row.kind!=="string"||!/^[0-9a-f]{64}$/.test(row.content_hash)||!Original.isUlid(row.tomb_id)||row.future_too!==0&&row.future_too!==1||Number.isNaN(Date.parse(row.ts)))throw Error("Invalid erasure decision.");this.db.exec("BEGIN IMMEDIATE");try{if(this.db.query("SELECT 1 FROM events LIMIT 1").get()!==null)throw Error("Erasure decisions must be imported before user records.");const put=this.db.query("INSERT OR REPLACE INTO tombstones(source,stream,source_id,rev,content_hash,tomb_id,future_too,ts,kind) VALUES (?,?,?,?,?,?,?,?,?)");for(const row of decisions)put.run(row.source,row.stream,row.source_id,row.rev,row.content_hash,row.tomb_id,row.future_too,row.ts,row.kind);this.db.exec("COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}}close(){if(!this.closed){this.closed=true;void this.reader.close();void this.snapshots.close();this.db.close()}}async closeAsync(){this.close();await Promise.all([this.reader.close(),this.snapshots.close()])}}export async function apply(ctx,config){const vault=new SqliteVault(config);ctx.reflect.provide("zortexSqliteVault",vault);ctx.reflect.provide("zortexConnectorStorage",{identity:vault.identity,appendPort:vault.createAppendPort(),declareStreams:streams=>vault.registerStreams(streams)});ctx.reflect.provide("zortexConnectorProcessJournal",vault.createProcessJournal());ctx.reflect.provide("zortexLocalSourceRegistry",vault.createLocalSourceRegistry());return()=>vault.closeAsync()}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zortexhq/indra-v2.5",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "private": false,
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
@@ -9,7 +9,7 @@
9
9
  "tag": "next"
10
10
  },
11
11
  "type": "module",
12
- "description": "Zortex daily 2026-11-27 (source 0.4.0)",
12
+ "description": "Zortex daily 2026-11-28 (source 0.4.0)",
13
13
  "repository": {
14
14
  "type": "git",
15
15
  "url": "https://github.com/ZortexHQ/indra-v2.git",
@@ -1017,9 +1017,9 @@
1017
1017
  "zortexRelease": {
1018
1018
  "schemaVersion": 1,
1019
1019
  "sourceVersion": "0.4.0",
1020
- "sourceSha": "def3661ef822e79f344bcc8f7ac497e8f398a267",
1021
- "sourceDate": "2026-11-27T05:32:40.000Z",
1022
- "version": "0.4.0"
1020
+ "sourceSha": "34b9b3c6efd10d8120e2f4c0a34a1c5f47913cdf",
1021
+ "sourceDate": "2026-11-28T16:47:29.000Z",
1022
+ "version": "0.4.1"
1023
1023
  },
1024
1024
  "zortex": {
1025
1025
  "role": "app"
@@ -1030,6 +1030,6 @@
1030
1030
  "zortexUpdate": {
1031
1031
  "schemaVersion": 1,
1032
1032
  "manifest": "update-manifest.json",
1033
- "sha256": "9e060ecb8704808b61f2fb633285fb57888d1af0b5fdf3ce1e187cb09062161d"
1033
+ "sha256": "7bd7ef76087acb6dd84d13a04e51626d45f1612337cb28b838d2e7287ebf15c5"
1034
1034
  }
1035
1035
  }