@vite-hub/realtime 0.3.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.
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # @vite-hub/realtime
2
2
 
3
3
  <p>
4
- <a href="https://vitehub.dev"><img alt="ViteHub" src="https://comark-ui.onmax.me/badge.svg?label=ViteHub&amp;value=vitehub.dev"></a>
5
- <img alt="TypeScript" src="https://comark-ui.onmax.me/badge.svg?label=TypeScript&amp;value=ready">
6
- <img alt="Yjs" src="https://comark-ui.onmax.me/badge.svg?label=Yjs&amp;value=collaboration">
7
- <img alt="Vite" src="https://comark-ui.onmax.me/badge.svg?label=Vite&amp;value=discovery">
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/static/v1?label=ViteHub&amp;message=vitehub.dev&amp;color=blue"></a>
5
+ <img alt="TypeScript" src="https://img.shields.io/static/v1?label=TypeScript&amp;message=ready&amp;color=blue">
6
+ <img alt="Yjs" src="https://img.shields.io/static/v1?label=Yjs&amp;message=collaboration&amp;color=blue">
7
+ <img alt="Vite" src="https://img.shields.io/static/v1?label=Vite&amp;message=discovery&amp;color=blue">
8
8
  </p>
9
9
 
10
10
  `@vite-hub/realtime` synchronizes TipTap editors through Yjs while a ViteHub Workspace owns the canonical Markdown files. Use the package directly when you compose ViteHub's modular Vite integrations. Use [`vite-hub`](https://www.npmjs.com/package/vite-hub) when you want the combined distribution.
@@ -17,7 +17,7 @@ Realtime is for collaborative documents, presence, explicit Workspace checkpoint
17
17
  pnpm add @vite-hub/realtime @vite-hub/workspace @tiptap/vue-3 drizzle-orm@1.0.0-rc.5 h3 nitro vite vue
18
18
  ```
19
19
 
20
- ViteHub Realtime requires Node.js 22.18 or newer. The published client adapter is for Vue. The package declares `vite` and `vue` as optional peers so server-only integrations do not install unused framework tooling; this walkthrough uses both. It also declares `drizzle-orm` as a peer: Realtime depends on Auth, and Auth uses the app's copy of Drizzle.
20
+ ViteHub Realtime requires Node.js 24.15 or newer. The published client adapter is for Vue. The package declares `vite` and `vue` as optional peers so server-only integrations do not install unused framework tooling; this walkthrough uses both. It also declares `drizzle-orm` as a peer: Realtime depends on Auth, and Auth uses the app's copy of Drizzle.
21
21
 
22
22
  ## Connect one document
23
23
 
@@ -56,7 +56,7 @@ export default defineWorkspace({
56
56
  import { defineRealtime } from "@vite-hub/realtime"
57
57
 
58
58
  export default defineRealtime({
59
- auth: true,
59
+ authorize: true,
60
60
  document: { workspace: "docs" },
61
61
  history: { checkpoint: true },
62
62
  })
@@ -110,6 +110,8 @@ console.log(checkpoint.document.body)
110
110
  console.log(checkpoint.snapshot.id)
111
111
  ```
112
112
 
113
+ Checkpoints use the Workspace Store's author by default. Set `document.checkpointAuthor` only to look up a Git identity approved for publication for the identified requester. Leave it unset for GitHub branches that require signed commits.
114
+
113
115
  ## Share presence without a document
114
116
 
115
117
  Set `document: false` when a room only shows who is there and what each person shares, such as a cursor. Nothing loads or saves, `authorize()` is asked only for `read`, and the rooms work with every Realtime driver.
@@ -119,7 +121,7 @@ Set `document: false` when a room only shows who is there and what each person s
119
121
  import { defineRealtime } from "@vite-hub/realtime"
120
122
 
121
123
  export default defineRealtime({
122
- auth: true,
124
+ authorize: true,
123
125
  document: false,
124
126
  })
125
127
  ```
@@ -162,18 +164,18 @@ const [error, answer] = await requestRealtimeRoom("tabs", tabId, { want: "title"
162
164
 
163
165
  ## Deployment and security boundaries
164
166
 
165
- - The Vue adapter connects to the generated same-origin `/api/_vitehub/realtime/**` WebSocket route. The Vite integration registers that route and discovers `server/realtime` definitions. In a component it prepares the editor extensions during setup and connects when the component mounts, so the server render and the first browser render both have `status` `disconnected`.
167
+ - The Vue adapter connects to the generated same-origin `/_vitehub/realtime/**` WebSocket route. The Vite integration registers that route and discovers `server/realtime` definitions. In a component it prepares the editor extensions during setup and connects when the component mounts, so the server render and the first browser render both have `status` `disconnected`.
166
168
  - `driver: "memory"` is single-process and loses room state when the process stops. ViteHub rejects it for known distributed hosts. It retains at most 128 active rooms.
167
169
  - `driver: "cloudflare"` uses a SQLite-backed Cloudflare Durable Object. `driver: "auto"` selects it when a Cloudflare host or hosting environment can be resolved.
168
170
  - On a Node build, `driver: "auto"` picks when the server starts: `redis` with `REDIS_URL`, else `postgres` on the postgres.js client of the Default Database when it is on Postgres (`REALTIME_POSTGRES_URL` overrides it; `DATABASE_URL` is not read), else `memory`. A borrowed Database client is never closed. It prints the choice at boot. With `redis` or `postgres`, each instance holds its rooms in memory and shares Yjs updates and awareness with the other instances through Redis pub/sub or Postgres `LISTEN`/`NOTIFY`. The instances start each room from one shared record (`vitehub_realtime_rooms` on Postgres), and saves of one room run one at a time under a lock, so `ifDigest` stays correct across instances. `NOTIFY` payloads over 8,000 bytes go through the `vitehub_realtime_messages` table. Each app has its own namespace on the bus (`realtime.namespace`, else the app name; `REALTIME_NAMESPACE` replaces it at runtime), so two apps on one Redis or Postgres never share a room. Presence of a stopped instance leaves at once, and that of a crashed instance after the 30 second Yjs awareness timeout. Other production builds fail with `REALTIME_MISSING_DRIVER`.
169
171
  - Durable rooms do not make Workspace files durable. Production checkpoints need a durable Workspace Store with conditional writes; memory Workspace Stores are rejected for durable checkpoints.
170
- - Each Realtime Definition must set `auth: true`, `authorize()`, or `access: "public"`. Otherwise the server rejects it with `REALTIME_MISSING_ACCESS`. `authorize()` allows only when it returns `true`; `undefined` and `false` deny. `auth: true` needs ViteHub Auth or `identify()`; it verifies the user and replaces client-supplied presence identity. `access: "public"` lets each person read and write each Realtime. Presence in a public definition is untrusted and must not authorize application actions.
172
+ - Each Realtime Definition must set `authorize: true`, `authorize()`, or `access: "public"`. Otherwise the server rejects it with `REALTIME_MISSING_ACCESS`. `authorize()` allows only when it returns `true`; `undefined` and `false` deny. It also runs for signed-out callers, with `user: null`. `authorize: true` needs ViteHub Auth or `identify()`; it verifies the user and replaces client-supplied presence identity. `access: "public"` lets each person read and write each Realtime. Presence in a public definition is untrusted and must not authorize application actions.
171
173
  - Requests with an `Origin` other than the app's get 403 on each definition, unless `origins()` accepts the origin.
172
174
  - Other packages can contribute definitions through `hubRealtime({ contribute })`, such as Content live editing. Realtime adds them only when the build has a Realtime driver and leaves them out without an error otherwise. A file in `server/realtime` with the same name wins.
173
- - Realtime routes follow the app base, including a Nuxt `app.baseURL`. With Vite `base: "/portal/"`, connections use `/portal/api/_vitehub/realtime/**`; Nitro's own `baseURL` is counted once.
175
+ - Realtime routes follow the app base, including a Nuxt `app.baseURL`. With Vite `base: "/portal/"`, connections use `/portal/_vitehub/realtime/**`; Nitro's own `baseURL` is counted once.
174
176
  - `refreshRealtimeDocument(definition, id)` tells an open room that its stored copy changed outside it. Document adapters may implement `hold()` and `release()` to keep a lease while writers are in a room.
175
177
  - One WebSocket message is limited to 1 MiB. Document state and awareness state are each limited to 8 MiB per room, and one peer can own at most 1,024 awareness clients.
176
- - Changing or disabling the document, or disposing its Vue scope, destroys the document provider. `save()`, `history.checkpoint()`, and `refresh()` return `[error, data]` with a `RealtimeRequestErrorCode`. A checkpoint returns `REALTIME_DISCONNECTED` during a document switch until the Vue watcher creates the new document, and when its original document is disconnected or replaced during a retry. The application still owns editor disposal, checkpoint error handling, and reconnect UX.
178
+ - Changing or disabling the document, or disposing its Vue scope, destroys the document provider. `save()`, `history.checkpoint()`, and `refresh()` return `[error, data]` with a `RealtimeRequestErrorCode`. A `REALTIME_REQUEST_FAILED` error has the HTTP status in `error.data.status`. A refused request returns the code that the server names, such as `REALTIME_SOURCE_CHANGED` when the stored document changed, or `REALTIME_SYNC_PENDING` after 20 retries. A checkpoint returns `REALTIME_DISCONNECTED` during a document switch until the Vue watcher creates the new document, and when its original document is disconnected or replaced during a retry. The application still owns editor disposal, checkpoint error handling, and reconnect UX.
177
179
 
178
180
  ## Public imports
179
181
 
package/dist/agent.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as agentRealtime, t as AgentRealtime } from "./request-BUwa359H.js";
1
+ import { a as agentRealtime, t as AgentRealtime } from "./request-BwaohsJS.js";
2
2
  export { type AgentRealtime, agentRealtime };
package/dist/agent.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as agentRealtime } from "./request-CWaHqW3R.js";
1
+ import { t as agentRealtime } from "./request-C_bQc4NE.js";
2
2
  export { agentRealtime };
@@ -1,4 +1,4 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
2
  import { createHash } from "node:crypto";
3
3
  import * as decoding from "lib0/decoding";
4
4
  import * as encoding from "lib0/encoding";
package/dist/bus.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as logRealtimeNodeDriver, c as resolveRealtimeNamespace, i as createRedisRealtimeBus, l as resolveRealtimeNodeDriver, n as createPostgresRealtimeBus, o as realtimeNamespaceVariable, r as createRealtimeNodeBus, s as realtimePostgresUrlVariable, t as closeRealtimeBuses, u as useRealtimeBus } from "./bus-Bi-Ec414.js";
1
+ import { a as logRealtimeNodeDriver, c as resolveRealtimeNamespace, i as createRedisRealtimeBus, l as resolveRealtimeNodeDriver, n as createPostgresRealtimeBus, o as realtimeNamespaceVariable, r as createRealtimeNodeBus, s as realtimePostgresUrlVariable, t as closeRealtimeBuses, u as useRealtimeBus } from "./bus-CKv8gQZf.js";
2
2
  export { closeRealtimeBuses, createPostgresRealtimeBus, createRealtimeNodeBus, createRedisRealtimeBus, logRealtimeNodeDriver, realtimeNamespaceVariable, realtimePostgresUrlVariable, resolveRealtimeNamespace, resolveRealtimeNodeDriver, useRealtimeBus };
@@ -50,4 +50,4 @@ var Wo=class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.
50
50
  /* c8 ignore stop */
51
51
  /* c8 ignore next */
52
52
  const Go=typeof BroadcastChannel>`u`?Wo:BroadcastChannel,Ko=e=>k(Uo,e,()=>{let t=l(),n=new Go(e);return n.onmessage=e=>t.forEach(t=>t(e.data,`broadcastchannel`)),{bc:n,subs:t}}),qo=(e,t)=>(Ko(e).subs.add(t),t),Jo=(e,t)=>{let n=Ko(e),r=n.subs.delete(t);return r&&n.subs.size===0&&(n.bc.close(),Uo.delete(e)),r},Yo=(e,t,n=null)=>{let r=Ko(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))},Xo=(e,t)=>{b(e,0);let n=pi(t);S(e,n)},Zo=(e,t,n)=>{b(e,1),S(e,si(t,n))},Qo=(e,t,n)=>Zo(t,n,w(e)),$o=(e,t,n,r)=>{try{ii(t,w(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},es=(e,t)=>{b(e,2),S(e,t)},ts=$o,ns=(e,t,n,r,i)=>{let a=T(e);switch(a){case 0:Qo(e,t,n);break;case 1:$o(e,n,r,i);break;case 2:ts(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},rs=(e,t,n)=>{T(e)===0&&n(t,E(e))},is=e=>ct(e,(e,t)=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join(`&`),as=[];as[0]=(e,t,n,r,i)=>{b(e,0);let a=ns(t,e,n.doc,n);r&&a===1&&!n.synced&&(n.synced=!0)},as[3]=(e,t,n,r,i)=>{b(e,1),S(e,Vo(n.awareness,Array.from(n.awareness.getStates().keys())))},as[1]=(e,t,n,r,i)=>{Ho(n.awareness,w(t),n)},as[2]=(e,t,n,r,i)=>{rs(t,n.doc,(e,t)=>ss(n,t))};const os=3e4,ss=(e,t)=>console.warn(`Permission denied to access ${e.url}.\n${t}`),cs=(e,t,n)=>{let r=C(t),i=_(),a=T(r),o=e.messageHandlers[a];return o?o(i,r,e,n,a):console.error(`Unable to compute message`),i},ls=e=>!(e.code>=4400&&e.code<4500),us=(e,t,r)=>{if(t!==null&&t===e.ws){e.emit(`connection-close`,[r,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,Bo(e.awareness,Array.from(e.awareness.getStates().keys()).filter(t=>t!==e.doc.clientID),e),e.emit(`status`,[{status:`disconnected`}])),e.wsUnsuccessfulReconnects++;let a=null;r!=null&&!e.shouldReconnect(r,e)&&(e.shouldConnect=!1,a={code:r.code,reason:r.reason}),setTimeout(ds,n(i(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),a!==null&&e.emit(`closed`,[a,e])}},ds=e=>{if(e.shouldConnect&&e.ws===null){let t=new e._WS(e.url,e.protocols);t.binaryType=`arraybuffer`,e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=D();let r=cs(e,new Uint8Array(n.data),!0);he(r)>1&&t.send(v(r))},t.onerror=n=>{e.ws===t&&e.emit(`connection-error`,[n,e])},t.onclose=n=>{us(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=D(),e.wsconnecting=!1,e.wsconnected=!0,e.emit(`status`,[{status:`connected`}]);let n=_();if(b(n,0),Xo(n,e.doc),t.send(v(n)),e.awareness.getLocalState()!==null){let n=_();b(n,1),S(n,Vo(e.awareness,[e.doc.clientID])),t.send(v(n))}},e.emit(`status`,[{status:`connecting`}])}},fs=(e,t)=>{let n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&Yo(e.bcChannel,t,e)};var ps=class extends et{constructor(e,t,n,{connect:r=!0,awareness:i=new zo(n),params:a={},protocols:o=[],WebSocketPolyfill:s=WebSocket,resyncInterval:c=-1,maxBackoffTime:l=2500,disableBc:u=!1,shouldReconnect:d=ls}={}){for(super();e[e.length-1]===`/`;)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+`/`+t,this.maxBackoffTime=l,this.shouldReconnect=d,this.params=a,this.protocols=o,this.roomname=t,this.doc=n,this._WS=s,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=as.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,c>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let e=_();b(e,0),Xo(e,n),this.ws.send(v(e))}},c)),this._bcSubscriber=(e,t)=>{if(t!==this){let t=cs(this,new Uint8Array(e),!1);he(t)>1&&Yo(this.bcChannel,v(t),this)}},this._updateHandler=(e,t)=>{if(t!==this){let t=_();b(t,0),es(t,e),fs(this,v(t))}},this.doc.on(`update`,this._updateHandler),this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{let a=e.concat(t).concat(n),o=_();b(o,1),S(o,Vo(i,a)),fs(this,v(o))},this._exitHandler=()=>{Bo(this.awareness,[n.clientID],`app closed`)},A&&typeof process<`u`&&process.on(`exit`,this._exitHandler),i.on(`update`,this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&os<D()-this.wsLastMessageReceived&&us(this,this.ws,null)},os/10),r&&this.connect()}get url(){let e=is(this.params);return this.serverUrl+`/`+this.roomname+(e.length===0?``:`?`+e)}get synced(){return this._synced}set synced(e){this._synced!==e&&(this._synced=e,e&&(this.wsUnsuccessfulReconnects=0),this.emit(`synced`,[e]),this.emit(`sync`,[e]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),A&&typeof process<`u`&&process.off(`exit`,this._exitHandler),this.awareness.off(`update`,this._awarenessUpdateHandler),this.doc.off(`update`,this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||=(qo(this.bcChannel,this._bcSubscriber),!0);let e=_();b(e,0),Xo(e,this.doc),Yo(this.bcChannel,v(e),this);let t=_();b(t,0),Zo(t,this.doc),Yo(this.bcChannel,v(t),this);let n=_();b(n,3),Yo(this.bcChannel,v(n),this);let r=_();b(r,1),S(r,Vo(this.awareness,[this.doc.clientID])),Yo(this.bcChannel,v(r),this)}disconnectBc(){let e=_();b(e,1),S(e,Vo(this.awareness,[this.doc.clientID],/* @__PURE__ */ new Map)),fs(this,v(e)),this.bcconnected&&=(Jo(this.bcChannel,this._bcSubscriber),!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&us(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(ds(this),this.connectBc())}};function ms(e,t=typeof __VITEHUB_APP_BASE_URL__>`u`?`/`:__VITEHUB_APP_BASE_URL__){return t===`/`?e:`${t.replace(/\/+$/,``)}${e}`}function hs(e,...t){return typeof e==`function`?e(...t):e}const gs=Error.captureStackTrace;var _s=class e extends Error{get why(){return this.message}constructor(t,n=e){super(t.why,{cause:t.cause}),this.code=this.name=t.code,this.docs=t.docs,this.fix=t.fix,this.sources=t.sources,this.data=t.data,gs?.(this,n)}toJSON(){return{name:this.name,why:this.why,fix:this.fix,docs:this.docs,sources:this.sources,cause:this.cause,data:this.data,stack:this.stack}}};function vs(e,t){return typeof e==`string`?`${e}/${t.toLowerCase()}`:e?.(t)}const ys=e=>t=>t instanceof _s&&e in t;/* @__NO_SIDE_EFFECTS__ */
53
- function bs(e){let t=e.reporters??[],n=Symbol(),r=Object.defineProperty({},"is",{value:ys(n)}),{docsBase:i}=e;for(let a of Object.keys(e.codes)){let o=e.codes[a],s=o.docs===!1?void 0:o.docs||vs(i,a),c=(e={},r={})=>{let i=new _s({code:a,why:hs(o.why,e),fix:hs(o.fix,e),docs:s,cause:e.cause,sources:e.sources,data:hs(o.data,e)},c);i[n]=1;for(let e of t)e(i,r);return i};c.is=e=>r.is(e)&&e.code===a,r[a]=c}return r}const X={why:({message:e})=>e===void 0?``:String(e)},xs=/*#__PURE__*/ bs({docsBase:`https://vitehub.dev/docs/development/diagnostics`,codes:{RUNTIME_R0001:{...X,fix:"Pass `maxDepth` to `normalizeRuntimeDiagnosticError()` as an integer of 0 or more, or remove it to use the default."},RUNTIME_R0002:{...X,fix:"Pass `maxErrors` to `normalizeRuntimeDiagnosticError()` as an integer of 1 or more, or remove it to use the default."},RUNTIME_R0003:{...X,fix:"Pass `maxStringLength` to `normalizeRuntimeDiagnosticError()` as an integer of 64 or more, or remove it to use the default."},RUNTIME_R0004:{...X,fix:"Read the logs of the process that `vitehub drain` waited for to find why its drain failed, then fix that failure and run `vitehub drain` again."},RUNTIME_R0005:{...X,fix:"Read the logs of the process that the message names to find why it stopped, then start it again before you run `vitehub drain`."},RUNTIME_R0006:{...X,fix:"Pass `new ViteHubError()` a nonempty `code` and `message` string within the length limits, and plain JSON `details`."},RUNTIME_R0007:{...X,fix:"Give the execution authority a valid value for each of `credentials`, `environment`, `filesystem.access`, `filesystem.scope`, `isolation`, `network`, and `processes`."},RUNTIME_R0009:{...X,fix:"Set `intervalMs` of the process reconciler to a number of milliseconds from 1 to 2147483647."},RUNTIME_R0010:{...X,fix:"Give the process reconciler a `signal` other than `SIGKILL` or `SIGSTOP`, or set `signal: false`."},RUNTIME_R0011:{...X,fix:"Call `drain()` of the process reconciler after its callback returns, not from inside the callback."},RUNTIME_R0015:{...X,fix:"Pass the `Request` of a Fetchable handler, or the event of an H3 or Nitro route, to `getStandardContext()`."},RUNTIME_R0016:{...X,fix:"Return the body or a `Response` from the handler, in place of setting `~standard.res.body`."},RUNTIME_R0017:X,RUNTIME_R0018:X,RUNTIME_CONSOLE_PATH_INVALID:{why:({value:e})=>`${e} is not a Console path. Use a path that starts with one /, such as /agents/<agent>.`,fix:"Pass `hostedConsoleUrl()` a Console path that starts with one `/`, such as `/kv` or `/agents/<agent>/invocations/<id>`."},RUNTIME_CONSOLE_PROJECT_URL_INVALID:{why:({value:e})=>`${e} is not a project URL. Use the https:// origin of the app, with its base path if it has one.`,fix:"Pass `hostedConsoleUrl()` the `https://` origin of the app, or `http://localhost` in development, with its base path and without a user name or password."},RUNTIME_EXECUTION_BUDGET_AMOUNT_INVALID:{why:({counter:e})=>`[vitehub] Execution budget ${e} amount must be a finite non-negative number.`,fix:"Pass `consume()` and the `record*()` methods of the execution budget a finite number of 0 or more."},RUNTIME_EXECUTION_BUDGET_EXCEEDED:{why:({counter:e})=>`[vitehub] Execution budget exhausted for ${e}.`,fix:"Raise the `executionBudget` limit that `error.counter` names, such as `maxToolCalls`, `maxRetries`, `maxInputBytes`, or `maxOutputBytes`, or give the run less work."},RUNTIME_EXECUTION_BUDGET_LIMIT_INVALID:{why:()=>`[vitehub] Execution budget limits must be finite non-negative numbers.`,fix:"Set each limit of `executionBudget`, such as `maxToolCalls` or `maxOutputBytes`, to a finite number of 0 or more, or remove it."},RUNTIME_SERIALIZED_RESPONSE_INVALID:{why:()=>`Invalid serialized Response`,fix:"Pass `deserializeResponse()` the record that `serializeResponse()` returned, unchanged. Check it first with `isSerializedResponse()`."}}});function Ss(e){return e!==null&&Object(e)===e}const Cs=/* @__PURE__ */ new WeakMap;function Z(){throw xs.RUNTIME_R0006({message:`[vitehub] ViteHubError requires a valid public error contract.`})}function ws(e){try{return Array.isArray(e)}catch{Z()}}function Q(e,t,n=!1){try{let r=Object.getOwnPropertyDescriptor(e,t);return r===void 0?void 0:((!(`value`in r)||n&&!r.enumerable)&&Z(),r.value)}catch{Z()}}function Ts(e,t,n,r){if(t.nodes+=1,t.nodes>1024&&Z(),e===void 0&&r)return;if(e===null||typeof e==`boolean`||typeof e==`string`&&e.length<=16384||typeof e==`number`&&Number.isFinite(e))return e;(typeof e!=`object`||n>8||t.ancestors.has(e))&&Z();let i,a;try{i=Object.getPrototypeOf(e),a=Reflect.ownKeys(e)}catch{Z()}t.ancestors.add(e);try{if(ws(e)){let r=Q(e,`length`);(!Number.isSafeInteger(r)||r<0||r>128||a.length!==r+1||!a.includes(`length`))&&Z();let i=[];for(let o=0;o<r;o+=1){let r=String(o);a.includes(r)||Z(),i.push(Ts(Q(e,r,!0),t,n+1,!1))}return Object.freeze(i)}i!==Object.prototype&&i!==null&&Z(),(a.length>128||a.some(e=>typeof e!=`string`))&&Z();let r={};for(let i of a)(i.length===0||i.length>128)&&Z(),Object.defineProperty(r,i,{enumerable:!0,value:Ts(Q(e,i,!0),t,n+1,!0),writable:!0});return Object.freeze(r)}finally{t.ancestors.delete(e)}}function Es(e){if(e!==void 0)return(typeof e!=`object`||!e||ws(e))&&Z(),Ts(e,{ancestors:/* @__PURE__ */ new Set,nodes:0},0,!1)}function Ds(e,t,n){(typeof e!=`string`||e.length===0||e.length>128)&&Z(),(typeof t!=`string`||t.length===0||t.length>16384)&&Z(),(typeof n!=`object`||!n||ws(n))&&Z();let r=Q(n,`cause`),i=Es(Q(n,`details`)),a=Q(n,`requestId`);return a!==void 0&&(typeof a!=`string`||a.length===0||a.length>256)&&Z(),{cause:r,code:e,details:i,message:t,name:`ViteHubError`,requestId:a,shape:Object.freeze({code:e,...i===void 0?{}:{details:i},message:t,name:`ViteHubError`,...a===void 0?{}:{requestId:a}})}}var Os=class extends Error{code;details;requestId;constructor(e,t,n={}){let r=Ds(e,t,n);super(r.message,r.cause===void 0?void 0:{cause:r.cause}),this.name=`ViteHubError`,this.code=r.code,this.details=r.details,this.requestId=r.requestId;let i=this.toJSON.bind(this);Object.defineProperties(this,{code:{configurable:!0,enumerable:!0,value:r.code,writable:!1},details:{configurable:!0,enumerable:!0,value:r.details,writable:!1},message:{configurable:!0,enumerable:!1,value:r.message,writable:!1},name:{configurable:!1,enumerable:!1,value:r.name,writable:!1},requestId:{configurable:!0,enumerable:!0,value:r.requestId,writable:!1},toJSON:{configurable:!1,enumerable:!1,value:i,writable:!1}}),Cs.set(this,r.shape)}toJSON(){let e=Cs.get(this);if(e)return e;let t=Ds(Q(this,`code`),Q(this,`message`),{details:Q(this,`details`),requestId:Q(this,`requestId`)});return Cs.set(this,t.shape),t.shape}};function ks(e){if(!Ss(e))return!1;try{let t=Reflect.get(Error,`isError`);if(!(typeof t==`function`?t(e)===!0:e instanceof Error||!(Symbol.toStringTag in e)&&Object.prototype.toString.call(e)===`[object Error]`))return!1;let n=Reflect.get(e,`message`),r=Reflect.get(e,`code`),i=Reflect.get(e,`name`),a=Reflect.get(e,`why`),o=Reflect.get(e,`fix`),s=Reflect.get(e,`docs`),c=Reflect.get(e,`sources`);return typeof r==`string`&&r.length>0&&typeof i==`string`&&typeof n==`string`&&a===n&&(o===void 0||typeof o==`string`)&&(s===void 0||typeof s==`string`)&&(c===void 0||Array.isArray(c)&&c.every(e=>typeof e==`string`))&&typeof Reflect.get(e,`toJSON`)==`function`}catch{return!1}}function As(e){let t=t=>{let n=Object.getOwnPropertyDescriptor(e,t);return n?n.configurable===!0:Object.isExtensible(e)},n=t(`name`)&&t(`toJSON`)?e:new _s({code:e.code,why:e.why,fix:e.fix,docs:e.docs,cause:e.cause,data:e.data,sources:e.sources});return n!==e&&(n.stack=e.stack),Object.defineProperty(n,"name",{configurable:!0,value:n.code,writable:!0}),Object.defineProperty(n,"toJSON",{configurable:!0,value:()=>({code:n.code,docs:n.docs,fix:n.fix,name:n.name,why:n.why})}),n}function js(e){let t=/* @__PURE__ */ bs({codes:e.codes,docsBase:e.docs}),n=new Set(Object.keys(e.codes)),r=Object.defineProperty({},"is",{value:e=>ks(e)&&n.has(e.code)});for(let e of n){let n=t[e];r[e]=Object.assign(e=>As(n(e)),{is:t=>ks(t)&&t.code===e})}return r}function Ms(e){let t=e.slice(0,4096);return new Os(`WORKSPACE_PATH_INVALID`,`[vitehub] Workspace path escapes the workspace root: ${JSON.stringify(t)}.`,{details:{path:t}})}function Ns(e){let t=e.toLowerCase().split(`:`,1)[0];return{normalized:t.replace(/[ .]+$/,``),isTraversal:/^(?:\.(?: +[. ]*)?|\.\.(?: +[. ]*)?)$/.test(t)}}function Ps(e=``,t={}){let n=e.replace(/\\/g,`/`),r=n.replace(/^\/+/,``).replace(/\/+$/,``),i=r.split(`/`).filter(Boolean);if(!t.allowEmpty&&!r||n.startsWith(`/`)||/^[a-z]:/i.test(n)||n.includes(`\0`)||i.some((e,n)=>{let r=e.toLowerCase(),i=Ns(e),a=i.normalized===`.git`||/^git~\d+$/.test(i.normalized)||n===0&&i.normalized===`.vitehub`||n===0&&/^vitehu~\d+$/.test(i.normalized),o=(i.normalized===`.git`||n===0&&i.normalized===`.vitehub`)&&r===i.normalized;return i.isTraversal||a&&(!t.allowReserved||!o)}))throw Ms(e);return r}const Fs=/*#__PURE__*/ js({docs:`https://vitehub.dev/docs/realtime/diagnostics`,codes:{REALTIME_DISABLED:{why:({action:e})=>`Realtime is disabled, so \`${e}()\` cannot run.`,fix:"Set `enabled` to `true` on `useRealtimeTiptap()` before you call the method."},REALTIME_DISCONNECTED:{why:({action:e})=>`The realtime document disconnected or changed during \`${e}()\`.`,fix:"Call the method again after the new document connects. Read `synced` to know when it is ready."},REALTIME_INVALID_RESPONSE:{why:({action:e})=>`The realtime server answered \`${e}()\` with a response that the client cannot use.`,fix:"Use the same `@vite-hub/realtime` version on the client and the server, and build again."},REALTIME_MISSING_DOCUMENT:{why:({action:e})=>`\`${e}()\` needs a document, and \`documentId\` is empty.`,fix:"Pass a document path to `useRealtimeTiptap(definition, documentId)` before you call the method."},REALTIME_REQUEST_FAILED:{why:({action:e,message:t,status:n})=>`The realtime \`${e}()\` request failed${n===void 0?``:` with HTTP ${n}`}${t?`: ${t}`:`.`}`,fix:"Read `error.why` for the server message, and `error.cause` for a network error. Retry when the server is available again."},REALTIME_ROOM_ABORTED:{why:`The request to the room stopped because its signal aborted.`,fix:`Nothing to fix when the caller stopped on purpose, such as a cancelled Agent run. Call again to ask once more.`},REALTIME_ROOM_CROWDED:{why:({count:e})=>`${e} browsers are in the room, and a request goes to one browser only.`,fix:`Give each browser its own room, such as a random id for each tab, so that one browser answers.`},REALTIME_ROOM_ELSEWHERE:{why:`No browser in this instance is in the room. With Redis or Postgres, the browser can be connected to another instance, and requests reach only the browsers of the same instance.`,fix:`Route the browser and the caller to the same instance, such as with sticky sessions, or run one Node instance.`},REALTIME_ROOM_EMPTY:{why:`No browser is in the room. The page is closed, or it has not joined yet.`,fix:`Open the page again. The request waits a few seconds for a browser to join before it gives up.`},REALTIME_ROOM_REFUSED:{why:({reason:e})=>`The browser could not answer: ${e}`,fix:"Read the reason. Add `room.onRequest(handler)` on the page, and keep each answer under 1 MiB."},REALTIME_ROOM_REQUESTS_OFF:{why:({definition:e})=>`The Realtime Definition "${e}" does not take requests.`,fix:'Define it with `defineRealtime({ access: "public", document: false, requests: true })`.'},REALTIME_ROOM_TIMEOUT:{why:({timeout:e})=>`The browser did not answer in ${e/1e3} seconds.`,fix:"Make the page answer sooner, or pass a longer `timeout` to `requestRealtimeRoom()`."},REALTIME_AWARENESS_OWNERSHIP_CONFLICT:{why:`A realtime awareness client id belongs to another peer.`,fix:`Let each editor tab use its own Yjs awareness client. Do not reuse a client id on two connections.`},REALTIME_AWARENESS_TOO_LARGE:{why:`Realtime awareness state exceeds the 8 MiB room quota.`,fix:`Keep less data in awareness state. Store large values in the document or in Workspace.`},REALTIME_DOCUMENT_TOO_LARGE:{why:`The realtime document exceeds the 8 MiB room quota.`,fix:`Split the document into smaller documents, or keep large assets in Workspace or Blob.`},REALTIME_INVALID_AWARENESS:{why:`A realtime awareness update has a state that is not a plain object.`,fix:"Set awareness state to a plain object, for example `awareness.setLocalStateField('user', { name })`."},REALTIME_TOO_MANY_AWARENESS_CLIENTS:{why:`One realtime peer sent more than 1,024 awareness clients.`,fix:`Use one awareness client for each editor tab.`},REALTIME_ROOM_WRITE_CONFLICT:{why:`Realtime room record compare-and-set failed.`,fix:`Connect again. Another Realtime instance changed the room at the same time. If it keeps failing, check that every instance uses the same Realtime bus.`},REALTIME_WRITE_REJECTED:{why:({problem:e,readOnly:t})=>e===`missing-state`?`Realtime update depends on state this room does not have.`:e===`status`?`Realtime document status is written by the server.`:t??`This realtime connection is read-only.`,fix:"Write only through a writable connection, and do not change the `status` map, which the server writes. A client that misses room state connects again to sync it."},REALTIME_DOCUMENT_CONFLICT:{why:({problem:e})=>e??`The stored document changed since the realtime room loaded it.`,fix:"Realtime re-seeds the room from the stored document. Listen to `onReset()` to recover text that the room did not save."},REALTIME_BLOB_ETAG_MISSING:{why:({pathname:e})=>`The Blob store returned no \`httpEtag\` for ${e}, so \`blobDocument()\` cannot save the file only if it is unchanged.`,fix:"Pass a ViteHub Blob store, such as `blob` from `vite-hub/blob`, whose `head()` returns `httpEtag` on every driver. A store of your own must return `httpEtag` from `head()` and accept `ifMatch` in `put()`."},REALTIME_INVALID_PERSISTENCE:{why:({name:e,reason:t})=>t===`below-debounce`?"Realtime `persistence.maxWait` must be at least `persistence.debounce`.":`Realtime \`persistence.${e}\` must be a non-negative number of milliseconds.`,fix:"Set `persistence: { debounce: 2_000, maxWait: 10_000 }`, or remove the option to use these defaults."},REALTIME_MISSING_ACCESS:{why:`The Realtime definition sets no access rule, so it does not say who can read and write its rooms.`,fix:'Set `auth: true` to require a signed-in user, add `authorize()` to decide each request, or set `access: "public"` to let anyone read and write.'},REALTIME_INVALID_ACCESS:{why:({reason:e})=>e===`public-with-rule`?'The Realtime definition sets `access: "public"` together with `auth` or `authorize()`, so its access rule is not clear.':e===`not-public`?'The Realtime definition sets `access` to a value other than "public".':"The Realtime definition sets `origins()` with `auth: true` and no `identify()`. The ViteHub Auth session is a cookie, so ViteHub accepts it only from the app's own origin.",fix:({reason:e})=>e===`origins-without-identify`?"Remove `origins()`, or add `identify()` that reads a credential the page sends on purpose, such as a ticket in `params`.":'Use `access: "public"` alone for open rooms. To limit access, remove `access` and set `auth: true` or `authorize()`.'},REALTIME_CHECKPOINT_UNSUPPORTED:{why:"The Realtime definition sets `history.checkpoint`, but its document adapter has no `checkpoint()` method, so `history.checkpoint()` could never run.",fix:"Add `checkpoint(context, { digest, message, user })` to the document adapter, use `document: { workspace }`, or remove `history`."},REALTIME_INVALID_USER:{why:"The realtime identity needs a user `id` that is a non-empty string of at most 256 characters.",fix:"Return a user with an `id` from the Auth session or from `authorize()`."},REALTIME_MISSING_DIGEST:{why:({operation:e})=>e===`save`?`Realtime saves need Workspace file digests, and the Workspace Store did not return one.`:`Realtime checkpoints need a stored document, and the save returned no digest.`,fix:"Use a Workspace Store that returns file digests, or return `digest` from the document adapter `save()`."},REALTIME_INVALID_POSTGRES_URL:{why:"REALTIME_POSTGRES_URL is set, and it is not a `postgres://` or `postgresql://` URL.",fix:`Set REALTIME_POSTGRES_URL to a Postgres URL, or remove it so that Realtime uses the connection of the Default Database.`},REALTIME_MISSING_BUS_CONNECTION:{why:({driver:e})=>e===`redis`?`Realtime driver "redis" shares rooms through Redis, and REDIS_URL is not set.`:`Realtime driver "postgres" shares rooms through Postgres, and the app has no Postgres Default Database and no REALTIME_POSTGRES_URL.`,fix:'Set REDIS_URL for Redis. For Postgres, define the Default Database with `dialect: "postgresql"`, or set REALTIME_POSTGRES_URL. Or set `realtime.driver` to "auto".'},REALTIME_ROOM_LOCK_TIMEOUT:{why:`Realtime waited 30 seconds for the save lock of a room, and another instance still holds it.`,fix:"Make the document adapter `save()` finish in less than 30 seconds. Realtime tries the save again."},REALTIME_DRIVER_CONFLICT:{why:({driver:e,host:t})=>e===`memory`?`Realtime driver "memory" is single-process only, and the ${t} host runs more than one process.`:e===`cloudflare`?`Realtime driver "cloudflare" does not work with the ${t} host.`:`Realtime driver "${e}" needs a Node.js server, and the ${t} host does not run one.`,fix:'Set `realtime.driver` to "cloudflare" with a Cloudflare host. With the Node host, use "auto", "postgres", "redis", or "memory".'},REALTIME_MISSING_DRIVER:{why:`Realtime production builds need one room driver, and ViteHub cannot select one for this deployment.`,fix:`Deploy with a Cloudflare host to use Durable Objects, or with the Node host to share rooms through Postgres or Redis.`},REALTIME_RENAMED_AUTHORITY_KEY:{why:({value:e})=>`\`realtime.authority\` is ${e}. ViteHub renamed this key to \`driver\`, and it does not read \`authority\`, so Realtime would not use the driver you chose.`,fix:({value:e})=>`Set \`realtime: { driver: ${e} }\`, or run \`npx @vite-hub/codemods driver-key\` to rename it in every config file.`}}});function Is(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`epoch`in t)||!(`type`in t)||typeof t.epoch!=`string`||!t.epoch)return;if(t.type===`session`&&`access`in t&&(t.access===`read`||t.access===`write`))return t.access===`read`&&`reason`in t&&(t.reason===`access`||t.reason===`document`||t.reason===`version`)?{type:`session`,access:t.access,epoch:t.epoch,reason:t.reason}:{type:`session`,access:t.access,epoch:t.epoch};if(t.type===`reset`&&`reason`in t&&(t.reason===`source-changed`||t.reason===`stale`))return{type:`reset`,epoch:t.epoch,reason:t.reason}}catch{}}function Ls(e){if(typeof e!=`string`||e.length===0||e.length>4096||e.includes(`\0`)||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`\\`)||e.includes(`//`)||/^[a-z]:/i.test(e))return!1;try{return Ps(e)===e}catch{return!1}}function Rs(e){try{let t=JSON.parse(E(e));if((t.operation===`create`||t.operation===`delete`||t.operation===`update`)&&Ls(t.path))return{operation:t.operation,path:t.path};if(t.operation===`move`&&Ls(t.from)&&Ls(t.to))return{operation:t.operation,from:t.from,to:t.to}}catch{}}function zs(e){let t=_();return b(t,4),x(t,JSON.stringify(e)),v(t)}function Bs(e){let t=_();return b(t,6),x(t,JSON.stringify(e)),v(t)}function Vs(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`id`in t)||typeof t.id!=`string`||!t.id||t.id.length>128||!(`kind`in t))return;if(t.kind===`request`)return{kind:`request`,id:t.id,body:`body`in t?t.body:void 0};if(t.kind!==`answer`||!(`ok`in t))return;if(t.ok===!0)return{kind:`answer`,id:t.id,ok:!0,body:`body`in t?t.body:void 0};if(t.ok===!1&&`why`in t&&typeof t.why==`string`)return{kind:`answer`,id:t.id,ok:!1,why:t.why}}catch{}}function Hs(e){let t;e.on(`status`,({status:n})=>{clearInterval(t),t=void 0;let r=e.ws;if(n!==`connected`||!r)return;let i=r.onmessage;r.onmessage=function(t){if(t.data!==`pong`)return i?.call(this,t);e.ws===r&&(e.wsLastMessageReceived=D())},t=setInterval(()=>{e.ws===r&&r.readyState===r.OPEN&&r.send(`ping`)},15e3)})}const Us=Object.freeze({body:`body`,fields:`fields`,status:`status`});function Ws(e){return typeof e==`string`?e:null}function Gs(e){let t=e.getMap(Us.status),n=t.get(`issues`),r=t.get(`savedBy`),i={issues:Array.isArray(n)?n:[],savedBy:r&&!Array.isArray(r)&&r instanceof Object?r:null};return{digest:Ws(t.get(`digest`)),error:Ws(t.get(`error`)),issues:i.issues,savedAt:Ws(t.get(`savedAt`)),savedBy:i.savedBy}}function Ks(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const qs=[`#E11D48`,`#D97706`,`#059669`,`#0891B2`,`#2563EB`,`#7C3AED`,`#C026D3`];function $(e){try{return String(e)===e}catch{return!1}}function Js(e){if(!$(e.id)||!e.id||e.id.length>256)throw Fs.REALTIME_INVALID_USER();let t=0;for(let n=0;n<e.id.length;n++)t=Math.imul(31,t)+e.id.charCodeAt(n)|0;let n=($(e.name)&&e.name||$(e.email)&&e.email||`Anonymous`).slice(0,256),r={color:qs[Math.abs(t)%qs.length],id:e.id,name:n};return $(e.image)&&e.image&&e.image.length<=2048&&(r.image=e.image),r}function Ys(e){return Ks(e)?$(e.id)&&e.id.length>0&&e.id.length<=256&&$(e.name)&&e.name.length>0&&e.name.length<=256&&$(e.color)&&/^#[\da-f]{6}$/i.test(e.color)&&(e.image===void 0||$(e.image)&&e.image.length<=2048):!1}function Xs(e){let t=[];for(let[n,r]of e)if(Ys(r.user)){let{color:e,id:i,image:a,name:o}=r.user,s={color:e,id:i,name:o,clientId:n};a!==void 0&&(s.image=a),t.push(s)}return t}function Zs(e,t,n={}){let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=[],o,s=`connecting`,c=!1,l=!1,u,d,f=()=>{for(let e of r)e()},ee=()=>{let t=n.origin?new URL(n.origin):window.location;return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${ms(`/api/_vitehub/realtime/${encodeURIComponent(e)}`,n.baseURL)}`},te=t.split(`/`).map(encodeURIComponent).join(`/`),ne={};function re(){c=!1,u=new Hr,d=new ps(ee(),te,u,{disableBc:!0,params:{...n.params,clientId:String(u.clientID)}});let e=d;Hs(e),e.messageHandlers[5]=(t,n)=>{let r=Is(n);if(r){if(r.type===`session`){e.params.epoch=r.epoch;return}e.destroy(),u.destroy(),!l&&(re(),f())}},e.messageHandlers[6]=(t,n)=>{let r=Vs(n);r?.kind===`request`&&ie(e,r.id,r.body)},e.awareness.off(`update`,e._awarenessUpdateHandler),e.awareness.on(`update`,({added:t,removed:n,updated:r})=>{let i=[...t,...r,...n].filter(t=>t===e.doc.clientID),a=e.ws;if(!i.length||!e.wsconnected||!a||a.readyState!==a.OPEN)return;let o=_();b(o,1),S(o,Vo(e.awareness,i)),a.send(v(o))});let t=n.identity??{id:`guest:${u.clientID}`};e.awareness.setLocalState({...ne,user:Js({...t,id:t.id||`guest:${u.clientID}`})}),e.awareness.on(`change`,f),u.getMap(Us.status).observe(f),e.on(`sync`,t=>{d===e&&(c=t,f())}),e.on(`status`,e=>{s=e.status,f()})}re();let p;n.changes&&(p=new ps(ee(),`%40workspace`,new Hr,{disableBc:!0,params:{...n.params,workspace:`events`}}),p.awareness.setLocalState(null),Hs(p),p.messageHandlers[4]=(e,t)=>{let n=Rs(t);if(n)for(let e of i)e(n)},p.on(`status`,e=>{e.status===`connected`&&ae()}));async function ie(e,t,n){let r=e=>Bs({kind:`answer`,id:t,ok:!1,why:e}),i;try{i=o?Bs({kind:`answer`,id:t,ok:!0,body:await o(n)}):r(`This page does not answer requests.`),i.byteLength>1047552&&(i=r(`The answer has ${i.byteLength} bytes, over the 1 MiB limit.`))}catch(e){i=r(e instanceof Error?e.message:String(e))}let a=e.ws;e.wsconnected&&a&&a.readyState===a.OPEN&&a.send(Uint8Array.from(i))}function ae(){let e=p?.ws;if(p?.wsconnected&&e&&e.readyState===e.OPEN)for(;a.length;)e.send(Uint8Array.from(zs(a.shift())))}return{get awareness(){return d.awareness},get clientId(){return u.clientID},people:()=>Xs(d.awareness.getStates()),states:()=>{let e=new Map(d.awareness.getStates());return e.delete(u.clientID),e},status:()=>s,saveStatus:()=>c?Gs(u):void 0,setLocal(e,t){t===null?delete ne[e]:ne[e]=t,d.awareness.setLocalStateField(e,t)},notify(e){p&&(a.push(e),ae())},onUpdate(e){return r.add(e),()=>r.delete(e)},onChange(e){return i.add(e),()=>i.delete(e)},onRequest(e){return o=e,()=>{o===e&&(o=void 0)}},destroy(){l=!0,d.destroy(),u.destroy(),p?.destroy(),p?.doc.destroy(),r.clear(),i.clear(),o=void 0}}}export{Zs as connectRealtimeRoom};
53
+ function bs(e){let t=e.reporters??[],n=Symbol(),r=Object.defineProperty({},"is",{value:ys(n)}),{docsBase:i}=e;for(let a of Object.keys(e.codes)){let o=e.codes[a],s=o.docs===!1?void 0:o.docs||vs(i,a),c=(e={},r={})=>{let i=new _s({code:a,why:hs(o.why,e),fix:hs(o.fix,e),docs:s,cause:e.cause,sources:e.sources,data:hs(o.data,e)},c);i[n]=1;for(let e of t)e(i,r);return i};c.is=e=>r.is(e)&&e.code===a,r[a]=c}return r}const X={why:({message:e})=>e===void 0?``:String(e)},xs=/*#__PURE__*/ bs({docsBase:`https://vitehub.dev/docs/runtime/diagnostics`,codes:{RUNTIME_R0001:{...X,fix:"Pass `maxDepth` to `normalizeRuntimeDiagnosticError()` as an integer of 0 or more, or remove it to use the default."},RUNTIME_R0002:{...X,fix:"Pass `maxErrors` to `normalizeRuntimeDiagnosticError()` as an integer of 1 or more, or remove it to use the default."},RUNTIME_R0003:{...X,fix:"Pass `maxStringLength` to `normalizeRuntimeDiagnosticError()` as an integer of 64 or more, or remove it to use the default."},RUNTIME_R0004:{...X,fix:"Read the logs of the process that `vitehub drain` waited for to find why its drain failed, then fix that failure and run `vitehub drain` again."},RUNTIME_R0005:{...X,fix:"Read the logs of the process that the message names to find why it stopped, then start it again before you run `vitehub drain`."},RUNTIME_R0006:{...X,fix:"Pass `new ViteHubError()` a nonempty `code` and `message` string within the length limits, and plain JSON `details`."},RUNTIME_R0007:{...X,fix:"Give the execution authority a valid value for each of `credentials`, `environment`, `filesystem.access`, `filesystem.scope`, `isolation`, `network`, and `processes`."},RUNTIME_R0009:{...X,fix:"Set `intervalMs` of the process reconciler to a number of milliseconds from 1 to 2147483647."},RUNTIME_R0010:{...X,fix:"Give the process reconciler a `signal` other than `SIGKILL` or `SIGSTOP`, or set `signal: false`."},RUNTIME_R0011:{...X,fix:"Call `drain()` of the process reconciler after its callback returns, not from inside the callback."},RUNTIME_R0015:{...X,fix:"Pass the `Request` of a Fetchable handler, or the event of an H3 or Nitro route, to `getStandardContext()`."},RUNTIME_R0016:{...X,fix:"Return the body or a `Response` from the handler, in place of setting `~standard.res.body`."},RUNTIME_R0017:X,RUNTIME_R0018:X,RUNTIME_CONSOLE_PATH_INVALID:{why:({value:e})=>`${e} is not a Console path. Use a path that starts with one /, such as /agents/<agent>.`,fix:"Pass `hostedConsoleUrl()` a Console path that starts with one `/`, such as `/kv` or `/agents/<agent>/invocations/<id>`."},RUNTIME_CONSOLE_PROJECT_URL_INVALID:{why:({value:e})=>`${e} is not a project URL. Use the https:// origin of the app, with its base path if it has one.`,fix:"Pass `hostedConsoleUrl()` the `https://` origin of the app, or `http://localhost` in development, with its base path and without a user name or password."},RUNTIME_DURATION_INVALID:{why:({option:e,value:t})=>`${e?`\`${e}\``:`The value`} is ${t}, which is not a duration. A duration is a string with a number of 0 or more and a unit, such as "30s", "5m", or "1 day".`,fix:({suggestion:e,unit:t=`milliseconds`,value:n})=>e?`Write the time as a string with a unit: ${n} ${t} is ${e}.`:'Write a number of 0 or more and one unit: `ms`, `s`, `m`, `h`, `d`, or `w`, or a long name such as `minutes` or `days`. For example `"30s"`, `"5m"`, or `"1 day"`.'},RUNTIME_EXECUTION_BUDGET_AMOUNT_INVALID:{why:({counter:e})=>`[vitehub] Execution budget ${e} amount must be a finite non-negative number.`,fix:"Pass `consume()` and the `record*()` methods of the execution budget a finite number of 0 or more."},RUNTIME_EXECUTION_BUDGET_EXCEEDED:{why:({counter:e})=>`[vitehub] Execution budget exhausted for ${e}.`,fix:"Raise the `executionBudget` limit that `error.counter` names, such as `maxToolCalls`, `maxRetries`, `maxInputBytes`, or `maxOutputBytes`, or give the run less work."},RUNTIME_EXECUTION_BUDGET_LIMIT_INVALID:{why:()=>`[vitehub] Execution budget limits must be finite non-negative numbers.`,fix:"Set each limit of `executionBudget`, such as `maxToolCalls` or `maxOutputBytes`, to a finite number of 0 or more, or remove it."},RUNTIME_HIDDEN_ERROR:{why:()=>`The server failed. The error is not a ViteHub error, so its message and stack stay on the server.`,fix:"Read the server logs for the error. To send a code, a why, and a fix to the client, return a `ResultError` from `defineErrors()` and pass it to `toResponse()`."},RUNTIME_SERIALIZED_RESPONSE_INVALID:{why:()=>`Invalid serialized Response`,fix:"Pass `deserializeResponse()` the record that `serializeResponse()` returned, unchanged. Check it first with `isSerializedResponse()`."}}});function Ss(e){return e!==null&&Object(e)===e}const Cs=/* @__PURE__ */ new WeakMap;function Z(){throw xs.RUNTIME_R0006({message:`[vitehub] ViteHubError requires a valid public error contract.`})}function ws(e){try{return Array.isArray(e)}catch{Z()}}function Q(e,t,n=!1){try{let r=Object.getOwnPropertyDescriptor(e,t);return r===void 0?void 0:((!(`value`in r)||n&&!r.enumerable)&&Z(),r.value)}catch{Z()}}function Ts(e,t,n,r){if(t.nodes+=1,t.nodes>1024&&Z(),e===void 0&&r)return;if(e===null||typeof e==`boolean`||typeof e==`string`&&e.length<=16384||typeof e==`number`&&Number.isFinite(e))return e;(typeof e!=`object`||n>8||t.ancestors.has(e))&&Z();let i,a;try{i=Object.getPrototypeOf(e),a=Reflect.ownKeys(e)}catch{Z()}t.ancestors.add(e);try{if(ws(e)){let r=Q(e,`length`);(!Number.isSafeInteger(r)||r<0||r>128||a.length!==r+1||!a.includes(`length`))&&Z();let i=[];for(let o=0;o<r;o+=1){let r=String(o);a.includes(r)||Z(),i.push(Ts(Q(e,r,!0),t,n+1,!1))}return Object.freeze(i)}i!==Object.prototype&&i!==null&&Z(),(a.length>128||a.some(e=>typeof e!=`string`))&&Z();let r={};for(let i of a)(i.length===0||i.length>128)&&Z(),Object.defineProperty(r,i,{enumerable:!0,value:Ts(Q(e,i,!0),t,n+1,!0),writable:!0});return Object.freeze(r)}finally{t.ancestors.delete(e)}}function Es(e){if(e!==void 0)return(typeof e!=`object`||!e||ws(e))&&Z(),Ts(e,{ancestors:/* @__PURE__ */ new Set,nodes:0},0,!1)}function Ds(e,t,n){(typeof e!=`string`||e.length===0||e.length>128)&&Z(),(typeof t!=`string`||t.length===0||t.length>16384)&&Z(),(typeof n!=`object`||!n||ws(n))&&Z();let r=Q(n,`cause`),i=Es(Q(n,`details`)),a=Q(n,`requestId`);return a!==void 0&&(typeof a!=`string`||a.length===0||a.length>256)&&Z(),{cause:r,code:e,details:i,message:t,name:`ViteHubError`,requestId:a,shape:Object.freeze({code:e,...i===void 0?{}:{details:i},message:t,name:`ViteHubError`,...a===void 0?{}:{requestId:a}})}}var Os=class extends Error{code;details;requestId;constructor(e,t,n={}){let r=Ds(e,t,n);super(r.message,r.cause===void 0?void 0:{cause:r.cause}),this.name=`ViteHubError`,this.code=r.code,this.details=r.details,this.requestId=r.requestId;let i=this.toJSON.bind(this);Object.defineProperties(this,{code:{configurable:!0,enumerable:!0,value:r.code,writable:!1},details:{configurable:!0,enumerable:!0,value:r.details,writable:!1},message:{configurable:!0,enumerable:!1,value:r.message,writable:!1},name:{configurable:!1,enumerable:!1,value:r.name,writable:!1},requestId:{configurable:!0,enumerable:!0,value:r.requestId,writable:!1},toJSON:{configurable:!1,enumerable:!1,value:i,writable:!1}}),Cs.set(this,r.shape)}toJSON(){let e=Cs.get(this);if(e)return e;let t=Ds(Q(this,`code`),Q(this,`message`),{details:Q(this,`details`),requestId:Q(this,`requestId`)});return Cs.set(this,t.shape),t.shape}};function ks(e){if(!Ss(e))return!1;try{let t=Reflect.get(Error,`isError`);return typeof t==`function`?t(e)===!0:e instanceof Error||!(Symbol.toStringTag in e)&&Object.prototype.toString.call(e)===`[object Error]`}catch{return!1}}function As(e){if(!ks(e))return!1;try{let t=Reflect.get(e,`message`),n=Reflect.get(e,`code`),r=Reflect.get(e,`name`),i=Reflect.get(e,`why`),a=Reflect.get(e,`fix`),o=Reflect.get(e,`docs`),s=Reflect.get(e,`sources`);return typeof n==`string`&&n.length>0&&typeof r==`string`&&typeof t==`string`&&i===t&&(a===void 0||typeof a==`string`)&&(o===void 0||typeof o==`string`)&&(s===void 0||Array.isArray(s)&&s.every(e=>typeof e==`string`))&&typeof Reflect.get(e,`toJSON`)==`function`}catch{return!1}}const js=Symbol.for(`vitehub.runtime.resultError`);function Ms(e){let t=t=>{let n=Object.getOwnPropertyDescriptor(e,t);return n?n.configurable===!0:Object.isExtensible(e)},n=t(`name`)&&t(`toJSON`)&&(Object.hasOwn(e,js)||Object.isExtensible(e))?e:new _s({code:e.code,why:e.why,fix:e.fix,docs:e.docs,cause:e.cause,data:e.data,sources:e.sources});if(n!==e){n.stack=e.stack;let t=Reflect.get(e,`status`);typeof t==`number`&&Object.defineProperty(n,"status",{configurable:!0,value:t})}return Object.defineProperty(n,"name",{configurable:!0,value:n.code,writable:!0}),Object.defineProperty(n,js,{value:!0}),Object.defineProperty(n,"toJSON",{configurable:!0,value:()=>({code:n.code,docs:n.docs,fix:n.fix,name:n.name,why:n.why})}),n}function Ns(e){let t=/* @__PURE__ */ bs({codes:e.codes,docsBase:e.docs}),n=new Set(Object.keys(e.codes)),r=Object.defineProperty({},"is",{value:e=>As(e)&&n.has(e.code)});for(let i of n){let n=t[i],a=e.codes[i]?.status;r[i]=Object.assign(e=>{let t=Ms(n(e));return a!==void 0&&Object.defineProperty(t,"status",{configurable:!0,enumerable:!1,value:a}),t},{is:e=>As(e)&&e.code===i})}return r}function Ps(e){let t=e.slice(0,4096);return new Os(`WORKSPACE_PATH_INVALID`,`[vitehub] Workspace path escapes the workspace root: ${JSON.stringify(t)}.`,{details:{path:t}})}function Fs(e){let t=e.toLowerCase().split(`:`,1)[0];return{normalized:t.replace(/[ .]+$/,``),isTraversal:/^(?:\.(?: +[. ]*)?|\.\.(?: +[. ]*)?)$/.test(t)}}function Is(e=``,t={}){let n=e.replace(/\\/g,`/`),r=n.replace(/^\/+/,``).replace(/\/+$/,``),i=r.split(`/`).filter(Boolean);if(!t.allowEmpty&&!r||n.startsWith(`/`)||/^[a-z]:/i.test(n)||n.includes(`\0`)||i.some((e,n)=>{let r=e.toLowerCase(),i=Fs(e),a=i.normalized===`.git`||/^git~\d+$/.test(i.normalized)||n===0&&i.normalized===`.vitehub`||n===0&&/^vitehu~\d+$/.test(i.normalized),o=(i.normalized===`.git`||n===0&&i.normalized===`.vitehub`)&&r===i.normalized;return i.isTraversal||a&&(!t.allowReserved||!o)}))throw Ps(e);return r}const Ls=/*#__PURE__*/ Ns({docs:`https://vitehub.dev/docs/realtime/diagnostics`,codes:{REALTIME_DISABLED:{why:({action:e})=>`Realtime is disabled, so \`${e}()\` cannot run.`,fix:"Set `enabled` to `true` on `useRealtimeTiptap()` before you call the method."},REALTIME_DISCONNECTED:{why:({action:e})=>`The realtime document disconnected or changed during \`${e}()\`.`,fix:"Call the method again after the new document connects. Read `synced` to know when it is ready."},REALTIME_INVALID_DOCUMENT:{why:({action:e})=>`The room body does not fit the editor schema, so \`${e}()\` did not write it. Writing it would lose content.`,fix:`Keep editing until the document fits the editor extensions of the Realtime Definition, then call the method again. The room keeps the edits.`},REALTIME_INVALID_RESPONSE:{why:({action:e})=>`The realtime server answered \`${e}()\` with a response that the client cannot use.`,fix:"Use the same `@vite-hub/realtime` version on the client and the server, and build again."},REALTIME_MISSING_DOCUMENT:{why:({action:e})=>`\`${e}()\` needs a document, and \`documentId\` is empty.`,fix:"Pass a document path to `useRealtimeTiptap(definition, documentId)` before you call the method."},REALTIME_READ_ONLY:{why:({action:e})=>`The room is read-only, so \`${e}()\` cannot write the document.`,fix:"Read `readOnlyReason` of `useRealtimeTiptap()` for the reason. Do not offer save or publish while it is set."},REALTIME_REQUEST_FAILED:{why:({action:e,message:t,status:n})=>`The realtime \`${e}()\` request failed${n===void 0?``:` with HTTP ${n}`}${t?`: ${t}`:`.`}`,fix:"Read `error.why` for the server message, `error.data.status` for the HTTP status, and `error.cause` for a network error. Retry when the server is available again.",data:({status:e})=>({status:e})},REALTIME_SOURCE_CHANGED:{why:({action:e})=>`The server refused \`${e}()\` because the stored document changed outside the room.`,fix:"Tell the person that the stored document changed. Use `onReset()` to detect a room reset and read unsaved edits from the event's `previous` document."},REALTIME_SYNC_PENDING:{why:({action:e})=>`The room did not receive every edit of this client in time, so \`${e}()\` did not run. The composable tried 20 times.`,fix:"Call the method again when `synced` is true. When it keeps failing, check that the WebSocket stays connected."},REALTIME_ROOM_ABORTED:{why:`The request to the room stopped because its signal aborted.`,fix:`Nothing to fix when the caller stopped on purpose, such as a cancelled Agent run. Call again to ask once more.`},REALTIME_ROOM_CROWDED:{why:({count:e})=>`${e} browsers are in the room, and a request goes to one browser only.`,fix:`Give each browser its own room, such as a random id for each tab, so that one browser answers.`},REALTIME_ROOM_ELSEWHERE:{why:`No browser in this instance is in the room. With Redis or Postgres, the browser can be connected to another instance, and requests reach only the browsers of the same instance.`,fix:`Route the browser and the caller to the same instance, such as with sticky sessions, or run one Node instance.`},REALTIME_ROOM_EMPTY:{why:`No browser is in the room. The page is closed, or it has not joined yet.`,fix:`Open the page again. The request waits a few seconds for a browser to join before it gives up.`},REALTIME_ROOM_REFUSED:{why:({reason:e})=>`The browser could not answer: ${e}`,fix:"Read the reason. Add `room.onRequest(handler)` on the page, and keep each answer under 1 MiB."},REALTIME_ROOM_REQUESTS_OFF:{why:({definition:e})=>`The Realtime Definition "${e}" does not take requests.`,fix:'Define it with `defineRealtime({ access: "public", document: false, requests: true })`.'},REALTIME_ROOM_TIMEOUT:{why:({timeout:e})=>`The browser did not answer in ${e/1e3} seconds.`,fix:"Make the page answer sooner, or pass a longer `timeout` to `requestRealtimeRoom()`."},REALTIME_AWARENESS_OWNERSHIP_CONFLICT:{why:`A realtime awareness client id belongs to another peer.`,fix:`Let each editor tab use its own Yjs awareness client. Do not reuse a client id on two connections.`},REALTIME_AWARENESS_TOO_LARGE:{why:`Realtime awareness state exceeds the 8 MiB room quota.`,fix:`Keep less data in awareness state. Store large values in the document or in Workspace.`},REALTIME_DOCUMENT_TOO_LARGE:{why:`The realtime document exceeds the 8 MiB room quota.`,fix:`Split the document into smaller documents, or keep large assets in Workspace or Blob.`},REALTIME_INVALID_AWARENESS:{why:`A realtime awareness update has a state that is not a plain object.`,fix:"Set awareness state to a plain object, for example `awareness.setLocalStateField('user', { name })`."},REALTIME_TOO_MANY_AWARENESS_CLIENTS:{why:`One realtime peer sent more than 1,024 awareness clients.`,fix:`Use one awareness client for each editor tab.`},REALTIME_ROOM_WRITE_CONFLICT:{why:`Realtime room record compare-and-set failed.`,fix:`Connect again. Another Realtime instance changed the room at the same time. If it keeps failing, check that every instance uses the same Realtime bus.`},REALTIME_WRITE_REJECTED:{why:({problem:e,readOnly:t})=>e===`missing-state`?`Realtime update depends on state this room does not have.`:e===`status`?`Realtime document status is written by the server.`:t??`This realtime connection is read-only.`,fix:"Write only through a writable connection, and do not change the `status` map, which the server writes. A client that misses room state connects again to sync it."},REALTIME_DOCUMENT_CONFLICT:{why:({problem:e})=>e??`The stored document changed since the realtime room loaded it.`,fix:"Realtime re-seeds the room from the stored document. Listen to `onReset()` to recover text that the room did not save."},REALTIME_BLOB_ETAG_MISSING:{why:({pathname:e})=>`The Blob store returned no \`httpEtag\` for ${e}, so \`blobDocument()\` cannot save the file only if it is unchanged.`,fix:"Pass a ViteHub Blob store, such as `blob` from `vite-hub/blob`, whose `head()` returns `httpEtag` on every driver. A store of your own must return `httpEtag` from `head()` and accept `ifMatch` in `put()`."},REALTIME_INVALID_PERSISTENCE:{why:({name:e,reason:t})=>t===`below-debounce`?"Realtime `persistence.maxWait` must be at least `persistence.debounce`.":`Realtime \`persistence.${e}\` must be a non-negative number of milliseconds.`,fix:"Set `persistence: { debounce: 2_000, maxWait: 10_000 }`, or remove the option to use these defaults."},REALTIME_MISSING_ACCESS:{why:`The Realtime definition sets no access rule, so it does not say who can read and write its rooms.`,fix:'Set `authorize: true` to require a signed-in user, set `authorize()` to decide each request, or set `access: "public"` to let anyone read and write.'},REALTIME_INVALID_ACCESS:{why:({reason:e})=>e===`auth`?"The Realtime definition sets `auth`. Realtime replaced it with `authorize: true`, and an `authorize()` callback now also runs for signed-out callers.":e===`public-with-rule`?'The Realtime definition sets `access: "public"` together with `authorize`, so its access rule is not clear.':e===`not-public`?'The Realtime definition sets `access` to a value other than "public".':e===`not-authorize`?"The Realtime definition sets `authorize` to a value that is not `true` or a function.":"The Realtime definition sets `origins()` with `authorize: true` and no `identify()`. Only the Auth trusted-origin policy can allow a different origin to use the ViteHub Auth session.",fix:({reason:e})=>e===`auth`?"Replace `auth: true` with `authorize: true`. With an `authorize()` callback, remove `auth` and return `false` from the callback when `user` is `null`.":e===`origins-without-identify`?"Remove `origins()`, or add `identify()` that reads a credential the page sends on purpose, such as a ticket in `params`.":e===`not-authorize`?"Set `authorize: true` to require a signed-in user, or set `authorize()` to a function that returns `true` to allow.":'Use `access: "public"` alone for open rooms. To limit access, remove `access` and set `authorize`.'},REALTIME_CHECKPOINT_UNSUPPORTED:{why:"The Realtime definition sets `history.checkpoint`, but its document adapter has no `checkpoint()` method, so `history.checkpoint()` could never run.",fix:"Add `checkpoint(context, { digest, message, user })` to the document adapter, use `document: { workspace }`, or remove `history`."},REALTIME_INVALID_USER:{why:"The realtime identity needs a user `id` that is a non-empty string of at most 256 characters.",fix:"Return a user with an `id` from the Auth session or from `authorize()`."},REALTIME_MISSING_DIGEST:{why:({operation:e})=>e===`save`?`Realtime saves need Workspace file digests, and the Workspace Store did not return one.`:`Realtime checkpoints need a stored document, and the save returned no digest.`,fix:"Use a Workspace Store that returns file digests, or return `digest` from the document adapter `save()`."},REALTIME_INVALID_POSTGRES_URL:{why:"REALTIME_POSTGRES_URL is set, and it is not a `postgres://` or `postgresql://` URL.",fix:`Set REALTIME_POSTGRES_URL to a Postgres URL, or remove it so that Realtime uses the connection of the Default Database.`},REALTIME_MISSING_BUS_CONNECTION:{why:({driver:e})=>e===`redis`?`Realtime driver "redis" shares rooms through Redis, and REDIS_URL is not set.`:`Realtime driver "postgres" shares rooms through Postgres, and the app has no Postgres Default Database and no REALTIME_POSTGRES_URL.`,fix:'Set REDIS_URL for Redis. For Postgres, define the Default Database with `dialect: "postgresql"`, or set REALTIME_POSTGRES_URL. Or set `realtime.driver` to "auto".'},REALTIME_ROOM_LOCK_TIMEOUT:{why:`Realtime waited 30 seconds for the save lock of a room, and another instance still holds it.`,fix:"Make the document adapter `save()` finish in less than 30 seconds. Realtime tries the save again."},REALTIME_DRIVER_CONFLICT:{why:({driver:e,host:t})=>e===`memory`?`Realtime driver "memory" is single-process only, and the ${t} host runs more than one process.`:e===`cloudflare`?`Realtime driver "cloudflare" does not work with the ${t} host.`:`Realtime driver "${e}" needs a Node.js server, and the ${t} host does not run one.`,fix:'Set `realtime.driver` to "cloudflare" with a Cloudflare host. With the Node host, use "auto", "postgres", "redis", or "memory".'},REALTIME_MISSING_DRIVER:{why:`Realtime production builds need one room driver, and ViteHub cannot select one for this deployment.`,fix:`Deploy with a Cloudflare host to use Durable Objects, or with the Node host to share rooms through Postgres or Redis.`},REALTIME_RENAMED_AUTHORITY_KEY:{why:({value:e})=>`\`realtime.authority\` is ${e}. ViteHub renamed this key to \`driver\`, and it does not read \`authority\`, so Realtime would not use the driver you chose.`,fix:({value:e})=>`Set \`realtime: { driver: ${e} }\`, or run \`npx @vite-hub/codemods driver-key\` to rename it in every config file.`}}});function Rs(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`epoch`in t)||!(`type`in t)||typeof t.epoch!=`string`||!t.epoch)return;if(t.type===`session`&&`access`in t&&(t.access===`read`||t.access===`write`))return t.access===`read`&&`reason`in t&&(t.reason===`access`||t.reason===`document`||t.reason===`version`)?{type:`session`,access:t.access,epoch:t.epoch,reason:t.reason}:{type:`session`,access:t.access,epoch:t.epoch};if(t.type===`reset`&&`reason`in t&&(t.reason===`source-changed`||t.reason===`stale`))return{type:`reset`,epoch:t.epoch,reason:t.reason}}catch{}}function zs(e){if(typeof e!=`string`||e.length===0||e.length>4096||e.includes(`\0`)||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`\\`)||e.includes(`//`)||/^[a-z]:/i.test(e))return!1;try{return Is(e)===e}catch{return!1}}function Bs(e){try{let t=JSON.parse(E(e));if((t.operation===`create`||t.operation===`delete`||t.operation===`update`)&&zs(t.path))return{operation:t.operation,path:t.path};if(t.operation===`move`&&zs(t.from)&&zs(t.to))return{operation:t.operation,from:t.from,to:t.to}}catch{}}function Vs(e){let t=_();return b(t,4),x(t,JSON.stringify(e)),v(t)}function Hs(e){let t=_();return b(t,6),x(t,JSON.stringify(e)),v(t)}function Us(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`id`in t)||typeof t.id!=`string`||!t.id||t.id.length>128||!(`kind`in t))return;if(t.kind===`request`)return{kind:`request`,id:t.id,body:`body`in t?t.body:void 0};if(t.kind!==`answer`||!(`ok`in t))return;if(t.ok===!0)return{kind:`answer`,id:t.id,ok:!0,body:`body`in t?t.body:void 0};if(t.ok===!1&&`why`in t&&typeof t.why==`string`)return{kind:`answer`,id:t.id,ok:!1,why:t.why}}catch{}}function Ws(e){let t;e.on(`status`,({status:n})=>{clearInterval(t),t=void 0;let r=e.ws;if(n!==`connected`||!r)return;let i=r.onmessage;r.onmessage=function(t){if(t.data!==`pong`)return i?.call(this,t);e.ws===r&&(e.wsLastMessageReceived=D())},t=setInterval(()=>{e.ws===r&&r.readyState===r.OPEN&&r.send(`ping`)},15e3)})}const Gs=Object.freeze({body:`body`,fields:`fields`,status:`status`});function Ks(e){return typeof e==`string`?e:null}function qs(e){let t=e.getMap(Gs.status),n=t.get(`issues`),r=t.get(`savedBy`),i={issues:Array.isArray(n)?n:[],savedBy:r&&!Array.isArray(r)&&r instanceof Object?r:null};return{digest:Ks(t.get(`digest`)),error:Ks(t.get(`error`)),issues:i.issues,savedAt:Ks(t.get(`savedAt`)),savedBy:i.savedBy}}function Js(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ys=[`#E11D48`,`#D97706`,`#059669`,`#0891B2`,`#2563EB`,`#7C3AED`,`#C026D3`];function $(e){try{return String(e)===e}catch{return!1}}function Xs(e){if(!$(e.id)||!e.id||e.id.length>256)throw Ls.REALTIME_INVALID_USER();let t=0;for(let n=0;n<e.id.length;n++)t=Math.imul(31,t)+e.id.charCodeAt(n)|0;let n=($(e.name)&&e.name||$(e.email)&&e.email||`Anonymous`).slice(0,256),r={color:Ys[Math.abs(t)%Ys.length],id:e.id,name:n};return $(e.image)&&e.image&&e.image.length<=2048&&(r.image=e.image),r}function Zs(e){return Js(e)?$(e.id)&&e.id.length>0&&e.id.length<=256&&$(e.name)&&e.name.length>0&&e.name.length<=256&&$(e.color)&&/^#[\da-f]{6}$/i.test(e.color)&&(e.image===void 0||$(e.image)&&e.image.length<=2048):!1}function Qs(e){let t=[];for(let[n,r]of e)if(Zs(r.user)){let{color:e,id:i,image:a,name:o}=r.user,s={color:e,id:i,name:o,clientId:n};a!==void 0&&(s.image=a),t.push(s)}return t}function $s(e,t,n={}){let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=[],o,s=`connecting`,c=!1,l=!1,u,d,f=()=>{for(let e of r)e()},ee=()=>{let t=n.origin?new URL(n.origin):window.location;return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${ms(`/_vitehub/realtime/${encodeURIComponent(e)}`,n.baseURL)}`},te=t.split(`/`).map(encodeURIComponent).join(`/`),ne={};function re(){c=!1,u=new Hr,d=new ps(ee(),te,u,{disableBc:!0,params:{...n.params,clientId:String(u.clientID)}});let e=d;Ws(e),e.messageHandlers[5]=(t,n)=>{let r=Rs(n);if(r){if(r.type===`session`){e.params.epoch=r.epoch;return}e.destroy(),u.destroy(),!l&&(re(),f())}},e.messageHandlers[6]=(t,n)=>{let r=Us(n);r?.kind===`request`&&ie(e,r.id,r.body)},e.awareness.off(`update`,e._awarenessUpdateHandler),e.awareness.on(`update`,({added:t,removed:n,updated:r})=>{let i=[...t,...r,...n].filter(t=>t===e.doc.clientID),a=e.ws;if(!i.length||!e.wsconnected||!a||a.readyState!==a.OPEN)return;let o=_();b(o,1),S(o,Vo(e.awareness,i)),a.send(v(o))});let t=n.identity??{id:`guest:${u.clientID}`};e.awareness.setLocalState({...ne,user:Xs({...t,id:t.id||`guest:${u.clientID}`})}),e.awareness.on(`change`,f),u.getMap(Gs.status).observe(f),e.on(`sync`,t=>{d===e&&(c=t,f())}),e.on(`status`,e=>{s=e.status,f()})}re();let p;n.changes&&(p=new ps(ee(),`%40workspace`,new Hr,{disableBc:!0,params:{...n.params,workspace:`events`}}),p.awareness.setLocalState(null),Ws(p),p.messageHandlers[4]=(e,t)=>{let n=Bs(t);if(n)for(let e of i)e(n)},p.on(`status`,e=>{e.status===`connected`&&ae()}));async function ie(e,t,n){let r=e=>Hs({kind:`answer`,id:t,ok:!1,why:e}),i;try{i=o?Hs({kind:`answer`,id:t,ok:!0,body:await o(n)}):r(`This page does not answer requests.`),i.byteLength>1047552&&(i=r(`The answer has ${i.byteLength} bytes, over the 1 MiB limit.`))}catch(e){i=r(e instanceof Error?e.message:String(e))}let a=e.ws;e.wsconnected&&a&&a.readyState===a.OPEN&&a.send(Uint8Array.from(i))}function ae(){let e=p?.ws;if(p?.wsconnected&&e&&e.readyState===e.OPEN)for(;a.length;)e.send(Uint8Array.from(Vs(a.shift())))}return{get awareness(){return d.awareness},get clientId(){return u.clientID},people:()=>Qs(d.awareness.getStates()),states:()=>{let e=new Map(d.awareness.getStates());return e.delete(u.clientID),e},status:()=>s,saveStatus:()=>c?qs(u):void 0,setLocal(e,t){t===null?delete ne[e]:ne[e]=t,d.awareness.setLocalStateField(e,t)},notify(e){p&&(a.push(e),ae())},onUpdate(e){return r.add(e),()=>r.delete(e)},onChange(e){return i.add(e),()=>i.delete(e)},onRequest(e){return o=e,()=>{o===e&&(o=void 0)}},destroy(){l=!0,d.destroy(),u.destroy(),p?.destroy(),p?.doc.destroy(),r.clear(),i.clear(),o=void 0}}}export{$s as connectRealtimeRoom};
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { F as RealtimeWorkspaceChange, d as RealtimeDocumentStatus, x as RealtimePerson } from "./types-1DVVG5ro.js";
1
+ import { L as RealtimeWorkspaceChange, d as RealtimeDocumentStatus, x as RealtimePerson } from "./types-Cvm0G3VJ.js";
2
2
  import * as awarenessProtocol from "y-protocols/awareness";
3
3
  //#region src/client.d.ts
4
4
  export type RealtimeRoomStatus = "connected" | "connecting" | "disconnected";
@@ -15,7 +15,7 @@ export interface RealtimeRoomOptions {
15
15
  /** Query parameters sent to the definition's authorization on presence and workspace connections. */
16
16
  params?: Record<string, string>;
17
17
  /**
18
- * The person this browser shows as. A definition with `identify` or `auth: true` replaces it with the server's
18
+ * The person this browser shows as. A definition with `identify` or `authorize: true` replaces it with the server's
19
19
  * identity, so only public definitions show it as given.
20
20
  */
21
21
  identity?: {
package/dist/client.js CHANGED
@@ -1,7 +1,7 @@
1
- import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } from "./keepalive-BCs-uXp4.js";
2
- import { a as decodeRealtimeRequestFramePayload, c as encodeRealtimeRequestFrame, i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, o as decodeWorkspaceChangePayload, x as workspaceRoomId } from "./object-CzKyK0hX.js";
1
+ import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } from "./keepalive-B4ONG6AD.js";
2
+ import { a as decodeRealtimeRequestFramePayload, c as encodeRealtimeRequestFrame, i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, o as decodeWorkspaceChangePayload, x as workspaceRoomId } from "./object-BgPPDLDE.js";
3
3
  import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
4
- import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-Tuy1y_l9.js";
4
+ import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-B6rvkHqd.js";
5
5
  import "lib0/decoding";
6
6
  import * as encoding from "lib0/encoding";
7
7
  import * as awarenessProtocol from "y-protocols/awareness";
@@ -30,7 +30,7 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
30
30
  };
31
31
  const url = () => {
32
32
  const app = options.origin ? new URL(options.origin) : window.location;
33
- return `${app.protocol === "https:" ? "wss:" : "ws:"}//${app.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`, options.baseURL)}`;
33
+ return `${app.protocol === "https:" ? "wss:" : "ws:"}//${app.host}${resolveRealtimeApplicationPath(`/_vitehub/realtime/${encodeURIComponent(definition)}`, options.baseURL)}`;
34
34
  };
35
35
  const room = documentId.split("/").map(encodeURIComponent).join("/");
36
36
  const localState = {};
@@ -1,8 +1,8 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
2
  import { Diagnostic } from "nostics";
3
3
  //#region src/definition.ts
4
4
  /**
5
- * Checks a definition when the server loads it. A definition must say who can use its rooms: `auth: true`,
5
+ * Checks a definition when the server loads it. A definition must say who can use its rooms: `authorize: true`,
6
6
  * `authorize()`, or `access: "public"`. `history.checkpoint` needs a document that can record history: a Workspace
7
7
  * document, or an adapter with `checkpoint()`.
8
8
  */
@@ -15,13 +15,13 @@ function defineRealtime(definition) {
15
15
  function assertRealtimeAccess(definition) {
16
16
  const access = definition.access;
17
17
  const authorize = definition.authorize;
18
- const auth = definition.auth === true;
19
- const hasAuthorize = typeof authorize === "function";
18
+ if ("auth" in definition) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "auth" });
20
19
  if (access !== void 0) {
21
20
  if (access !== "public") throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "not-public" });
22
- if (definition.auth !== void 0 || authorize !== void 0) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "public-with-rule" });
23
- } else if (!auth && !hasAuthorize) throw realtimeErrorDiagnostics.REALTIME_MISSING_ACCESS();
24
- if (auth && !definition.identify && definition.origins) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "origins-without-identify" });
21
+ if (authorize !== void 0) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "public-with-rule" });
22
+ } else if (authorize === void 0) throw realtimeErrorDiagnostics.REALTIME_MISSING_ACCESS();
23
+ else if (authorize !== true && typeof authorize !== "function") throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "not-authorize" });
24
+ if (authorize === true && !definition.identify && definition.origins) throw realtimeErrorDiagnostics.REALTIME_INVALID_ACCESS({ reason: "origins-without-identify" });
25
25
  }
26
26
  function assertRealtimeCheckpoint(definition) {
27
27
  if (!definition.document || !definition.history?.checkpoint) return;
@@ -1,5 +1,5 @@
1
- import { f as RealtimeEditor, u as RealtimeDocumentSnapshot } from "./types-1DVVG5ro.js";
2
- import "./layout-fyQnhwCg.js";
1
+ import { f as RealtimeEditor, u as RealtimeDocumentSnapshot } from "./types-Cvm0G3VJ.js";
2
+ import "./layout-B7i6-FnH.js";
3
3
  import * as Y from "yjs";
4
4
  //#region src/document.d.ts
5
5
  /** Builds a new room document from a stored snapshot. Only use it for rooms no client holds yet. */
@@ -1,4 +1,4 @@
1
- import { n as isRecord } from "./object-CzKyK0hX.js";
1
+ import { n as isRecord } from "./object-BgPPDLDE.js";
2
2
  import { n as realtimeDocumentLayout } from "./layout-DNaxppTZ.js";
3
3
  import "y-protocols/awareness";
4
4
  import * as Y from "yjs";
@@ -11,6 +11,10 @@ const realtimeErrorDiagnostics = /*#__PURE__*/ defineErrors({
11
11
  why: ({ action }) => `The realtime document disconnected or changed during \`${action}()\`.`,
12
12
  fix: "Call the method again after the new document connects. Read `synced` to know when it is ready."
13
13
  },
14
+ REALTIME_INVALID_DOCUMENT: {
15
+ why: ({ action }) => `The room body does not fit the editor schema, so \`${action}()\` did not write it. Writing it would lose content.`,
16
+ fix: "Keep editing until the document fits the editor extensions of the Realtime Definition, then call the method again. The room keeps the edits."
17
+ },
14
18
  REALTIME_INVALID_RESPONSE: {
15
19
  why: ({ action }) => `The realtime server answered \`${action}()\` with a response that the client cannot use.`,
16
20
  fix: "Use the same `@vite-hub/realtime` version on the client and the server, and build again."
@@ -19,9 +23,22 @@ const realtimeErrorDiagnostics = /*#__PURE__*/ defineErrors({
19
23
  why: ({ action }) => `\`${action}()\` needs a document, and \`documentId\` is empty.`,
20
24
  fix: "Pass a document path to `useRealtimeTiptap(definition, documentId)` before you call the method."
21
25
  },
26
+ REALTIME_READ_ONLY: {
27
+ why: ({ action }) => `The room is read-only, so \`${action}()\` cannot write the document.`,
28
+ fix: "Read `readOnlyReason` of `useRealtimeTiptap()` for the reason. Do not offer save or publish while it is set."
29
+ },
22
30
  REALTIME_REQUEST_FAILED: {
23
31
  why: ({ action, message, status }) => `The realtime \`${action}()\` request failed${status === void 0 ? "" : ` with HTTP ${status}`}${message ? `: ${message}` : "."}`,
24
- fix: "Read `error.why` for the server message, and `error.cause` for a network error. Retry when the server is available again."
32
+ fix: "Read `error.why` for the server message, `error.data.status` for the HTTP status, and `error.cause` for a network error. Retry when the server is available again.",
33
+ data: ({ status }) => ({ status })
34
+ },
35
+ REALTIME_SOURCE_CHANGED: {
36
+ why: ({ action }) => `The server refused \`${action}()\` because the stored document changed outside the room.`,
37
+ fix: "Tell the person that the stored document changed. Use `onReset()` to detect a room reset and read unsaved edits from the event's `previous` document."
38
+ },
39
+ REALTIME_SYNC_PENDING: {
40
+ why: ({ action }) => `The room did not receive every edit of this client in time, so \`${action}()\` did not run. The composable tried 20 times.`,
41
+ fix: "Call the method again when `synced` is true. When it keeps failing, check that the WebSocket stays connected."
25
42
  },
26
43
  REALTIME_ROOM_ABORTED: {
27
44
  why: "The request to the room stopped because its signal aborted.",
@@ -93,11 +110,11 @@ const realtimeErrorDiagnostics = /*#__PURE__*/ defineErrors({
93
110
  },
94
111
  REALTIME_MISSING_ACCESS: {
95
112
  why: "The Realtime definition sets no access rule, so it does not say who can read and write its rooms.",
96
- fix: "Set `auth: true` to require a signed-in user, add `authorize()` to decide each request, or set `access: \"public\"` to let anyone read and write."
113
+ fix: "Set `authorize: true` to require a signed-in user, set `authorize()` to decide each request, or set `access: \"public\"` to let anyone read and write."
97
114
  },
98
115
  REALTIME_INVALID_ACCESS: {
99
- why: ({ reason }) => reason === "public-with-rule" ? "The Realtime definition sets `access: \"public\"` together with `auth` or `authorize()`, so its access rule is not clear." : reason === "not-public" ? "The Realtime definition sets `access` to a value other than \"public\"." : "The Realtime definition sets `origins()` with `auth: true` and no `identify()`. The ViteHub Auth session is a cookie, so ViteHub accepts it only from the app's own origin.",
100
- fix: ({ reason }) => reason === "origins-without-identify" ? "Remove `origins()`, or add `identify()` that reads a credential the page sends on purpose, such as a ticket in `params`." : "Use `access: \"public\"` alone for open rooms. To limit access, remove `access` and set `auth: true` or `authorize()`."
116
+ why: ({ reason }) => reason === "auth" ? "The Realtime definition sets `auth`. Realtime replaced it with `authorize: true`, and an `authorize()` callback now also runs for signed-out callers." : reason === "public-with-rule" ? "The Realtime definition sets `access: \"public\"` together with `authorize`, so its access rule is not clear." : reason === "not-public" ? "The Realtime definition sets `access` to a value other than \"public\"." : reason === "not-authorize" ? "The Realtime definition sets `authorize` to a value that is not `true` or a function." : "The Realtime definition sets `origins()` with `authorize: true` and no `identify()`. Only the Auth trusted-origin policy can allow a different origin to use the ViteHub Auth session.",
117
+ fix: ({ reason }) => reason === "auth" ? "Replace `auth: true` with `authorize: true`. With an `authorize()` callback, remove `auth` and return `false` from the callback when `user` is `null`." : reason === "origins-without-identify" ? "Remove `origins()`, or add `identify()` that reads a credential the page sends on purpose, such as a ticket in `params`." : reason === "not-authorize" ? "Set `authorize: true` to require a signed-in user, or set `authorize()` to a function that returns `true` to allow." : "Use `access: \"public\"` alone for open rooms. To limit access, remove `access` and set `authorize`."
101
118
  },
102
119
  REALTIME_CHECKPOINT_UNSUPPORTED: {
103
120
  why: "The Realtime definition sets `history.checkpoint`, but its document adapter has no `checkpoint()` method, so `history.checkpoint()` could never run.",
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { A as RealtimeSaveOptions, C as RealtimeReadOnlyReason, D as RealtimeRequestEvent, E as RealtimeRequestErrorCode, F as RealtimeWorkspaceChange, I as RealtimeWorkspaceDocumentOptions, M as RealtimeSaved, N as RealtimeUser, O as RealtimeResetReason, P as RealtimeVerifyResult, S as RealtimePresenceDefinition, T as RealtimeRequestContext, _ as RealtimeLoadedDocument, a as RealtimeDefinition, b as RealtimePersistenceOptions, c as RealtimeDocumentContext, d as RealtimeDocumentStatus, f as RealtimeEditor, g as RealtimeIssue, h as RealtimeHoldOptions, i as RealtimeCheckpoint, j as RealtimeSaveResult, k as RealtimeRoomRequestErrorCode, l as RealtimeDocumentDefinition, m as RealtimeHistoryOptions, n as RealtimeAuthorizeContext, o as RealtimeDefinitionAccess, p as RealtimeFieldValue, s as RealtimeDocumentAdapter, u as RealtimeDocumentSnapshot, v as RealtimeOptions, x as RealtimePerson, y as RealtimeOriginContext } from "./types-1DVVG5ro.js";
1
+ import { A as RealtimeResetReason, C as RealtimeReadOnlyReason, D as RealtimeRequestErrorCode, E as RealtimeRequestError, F as RealtimeUser, I as RealtimeVerifyResult, L as RealtimeWorkspaceChange, M as RealtimeSaveOptions, N as RealtimeSaveResult, O as RealtimeRequestEvent, P as RealtimeSaved, R as RealtimeWorkspaceDocumentOptions, S as RealtimePresenceDefinition, T as RealtimeRequestContext, _ as RealtimeLoadedDocument, a as RealtimeDefinition, b as RealtimePersistenceOptions, c as RealtimeDocumentContext, d as RealtimeDocumentStatus, f as RealtimeEditor, g as RealtimeIssue, h as RealtimeHoldOptions, i as RealtimeCheckpoint, j as RealtimeRoomRequestErrorCode, k as RealtimeRequestResult, l as RealtimeDocumentDefinition, m as RealtimeHistoryOptions, n as RealtimeAuthorizeContext, o as RealtimeDefinitionAccess, p as RealtimeFieldValue, s as RealtimeDocumentAdapter, u as RealtimeDocumentSnapshot, v as RealtimeOptions, x as RealtimePerson, y as RealtimeOriginContext, z as RealtimeRequestFailure } from "./types-Cvm0G3VJ.js";
2
2
  import { n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-CmZizTYl.js";
3
- import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-fyQnhwCg.js";
3
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-B7i6-FnH.js";
4
4
  //#region src/definition.d.ts
5
5
  /**
6
- * Checks a definition when the server loads it. A definition must say who can use its rooms: `auth: true`,
6
+ * Checks a definition when the server loads it. A definition must say who can use its rooms: `authorize: true`,
7
7
  * `authorize()`, or `access: "public"`. `history.checkpoint` needs a document that can record history: a Workspace
8
8
  * document, or an adapter with `checkpoint()`.
9
9
  */
@@ -21,4 +21,4 @@ export declare function defineRealtimeEditor(editor: RealtimeEditor): RealtimeEd
21
21
  */
22
22
  export declare const realtimeMarkdownEditor: RealtimeEditor;
23
23
  //#endregion
24
- export { type RealtimeAuthorizeContext, type RealtimeCheckpoint, type RealtimeDefinition, type RealtimeDefinitionAccess, type RealtimeDocumentAdapter, RealtimeDocumentConflict, type RealtimeDocumentContext, type RealtimeDocumentDefinition, type RealtimeDocumentSnapshot, type RealtimeDocumentStatus, type RealtimeEditor, type RealtimeFieldValue, type RealtimeHistoryOptions, type RealtimeHoldOptions, type RealtimeIssue, type RealtimeLoadedDocument, type RealtimeOptions, type RealtimeOriginContext, type RealtimePersistenceOptions, type RealtimePerson, type RealtimePresenceDefinition, type RealtimeReadOnlyReason, type RealtimeRequestContext, type RealtimeRequestErrorCode, type RealtimeRequestEvent, type RealtimeResetReason, type RealtimeRoomRequestErrorCode, type RealtimeSaveOptions, type RealtimeSaveResult, type RealtimeSaved, type RealtimeUser, type RealtimeVerifyResult, type RealtimeWorkspaceChange, type RealtimeWorkspaceDocumentOptions, isRealtimeDocumentConflict, readRealtimeStatus, realtimeDocumentLayout };
24
+ export { type RealtimeAuthorizeContext, type RealtimeCheckpoint, type RealtimeDefinition, type RealtimeDefinitionAccess, type RealtimeDocumentAdapter, RealtimeDocumentConflict, type RealtimeDocumentContext, type RealtimeDocumentDefinition, type RealtimeDocumentSnapshot, type RealtimeDocumentStatus, type RealtimeEditor, type RealtimeFieldValue, type RealtimeHistoryOptions, type RealtimeHoldOptions, type RealtimeIssue, type RealtimeLoadedDocument, type RealtimeOptions, type RealtimeOriginContext, type RealtimePersistenceOptions, type RealtimePerson, type RealtimePresenceDefinition, type RealtimeReadOnlyReason, type RealtimeRequestContext, type RealtimeRequestError, type RealtimeRequestErrorCode, type RealtimeRequestEvent, type RealtimeRequestFailure, type RealtimeRequestResult, type RealtimeResetReason, type RealtimeRoomRequestErrorCode, type RealtimeSaveOptions, type RealtimeSaveResult, type RealtimeSaved, type RealtimeUser, type RealtimeVerifyResult, type RealtimeWorkspaceChange, type RealtimeWorkspaceDocumentOptions, isRealtimeDocumentConflict, readRealtimeStatus, realtimeDocumentLayout };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
2
- import { a as defineRealtime, n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-Bg8vCisd.js";
2
+ import { a as defineRealtime, n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-DYC_qXzM.js";
3
3
  import { n as defineRealtimeEditor, r as realtimeMarkdownEditor, t as createRealtimeEditorExtensions } from "./editor-BM5-vHqf.js";
4
4
  export { RealtimeDocumentConflict, createRealtimeEditorExtensions, defineRealtime, defineRealtimeEditor, isRealtimeDocumentConflict, readRealtimeStatus, realtimeDocumentLayout, realtimeMarkdownEditor };
@@ -1,4 +1,4 @@
1
- import { r as RealtimeAvailability } from "../../types-1DVVG5ro.js";
1
+ import { r as RealtimeAvailability } from "../../types-Cvm0G3VJ.js";
2
2
  //#region src/internal/runtime/unavailable.d.ts
3
3
  declare const availability: RealtimeAvailability;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { h as realtimeKeepalivePing } from "./object-CzKyK0hX.js";
1
+ import { h as realtimeKeepalivePing } from "./object-BgPPDLDE.js";
2
2
  import * as time from "lib0/time";
3
3
  //#region src/application-path.ts
4
4
  function resolveRealtimeApplicationPath(path, baseURL = typeof __VITEHUB_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_APP_BASE_URL__) {
@@ -1,4 +1,4 @@
1
- import { d as RealtimeDocumentStatus } from "./types-1DVVG5ro.js";
1
+ import { d as RealtimeDocumentStatus } from "./types-Cvm0G3VJ.js";
2
2
  import * as Y from "yjs";
3
3
  //#region src/layout.d.ts
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
2
  import * as decoding from "lib0/decoding";
3
3
  import * as encoding from "lib0/encoding";
4
4
  import { normalizeSafeWorkspacePath } from "@vite-hub/workspace/internal/path";
@@ -1,5 +1,5 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
- import { n as isRecord } from "./object-CzKyK0hX.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
+ import { n as isRecord } from "./object-BgPPDLDE.js";
3
3
  //#region src/presence.ts
4
4
  const personColors = [
5
5
  "#E11D48",
@@ -1,4 +1,4 @@
1
- import { k as RealtimeRoomRequestErrorCode } from "./types-1DVVG5ro.js";
1
+ import { j as RealtimeRoomRequestErrorCode } from "./types-Cvm0G3VJ.js";
2
2
  import { Result } from "@vite-hub/runtime";
3
3
  //#region src/request.d.ts
4
4
  /** The `$DurableObject` namespace binding that holds Realtime rooms on Cloudflare. */
@@ -1,4 +1,4 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import availability from "#vitehub/realtime/availability";
4
4
  //#region ../internal/src/runtime/cloudflare-env-lookup.ts
@@ -34,7 +34,7 @@ function isRealtimeAvailable() {
34
34
  }
35
35
  //#endregion
36
36
  //#region src/request.ts
37
- const routePrefix = "/api/_vitehub/realtime/";
37
+ const routePrefix = "/_vitehub/realtime/";
38
38
  /** Marks the request that `requestRealtimeRoom()` sends to a Durable Object. The Worker strips it from client requests. */
39
39
  const internalRequestHeader = "x-vitehub-realtime-request";
40
40
  const defaultRequestTimeout = 3e4;
package/dist/server.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { c as RealtimeDocumentContext, f as RealtimeEditor, l as RealtimeDocumentDefinition, s as RealtimeDocumentAdapter, w as RealtimeRegistry, x as RealtimePerson } from "./types-1DVVG5ro.js";
2
- import { i as RealtimeRoomRequestResult, n as RealtimeDurableObjectNamespace, o as requestRealtimeRoom, r as RealtimeRoomRequestOptions } from "./request-BUwa359H.js";
1
+ import { R as RealtimeWorkspaceDocumentOptions, c as RealtimeDocumentContext, f as RealtimeEditor, l as RealtimeDocumentDefinition, s as RealtimeDocumentAdapter, w as RealtimeRegistry, x as RealtimePerson } from "./types-Cvm0G3VJ.js";
2
+ import { i as RealtimeRoomRequestResult, n as RealtimeDurableObjectNamespace, o as requestRealtimeRoom, r as RealtimeRoomRequestOptions } from "./request-BwaohsJS.js";
3
3
  import { n as RealtimeBusMessage, r as RealtimeRoomRecord, t as RealtimeBus } from "./bus-protocol-wXkXW28q.js";
4
4
  import { n as isRealtimeDocumentConflict, t as RealtimeDocumentConflict } from "./conflict-CmZizTYl.js";
5
- import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-fyQnhwCg.js";
6
- import { i as readRealtimeYDoc, n as createRealtimeYDoc, r as diffRealtimeYDoc, t as containsRealtimeState } from "./document-DPaywuCO.js";
5
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-B7i6-FnH.js";
6
+ import { i as readRealtimeYDoc, n as createRealtimeYDoc, r as diffRealtimeYDoc, t as containsRealtimeState } from "./document-BfMW1zYU.js";
7
7
  import * as awarenessProtocol from "y-protocols/awareness";
8
8
  import * as Y from "yjs";
9
9
  import { Diagnostic } from "nostics";
@@ -74,10 +74,10 @@ export declare function readRealtimeWorkspaceDocument(readable: ReadonlyWorkspac
74
74
  }>;
75
75
  /**
76
76
  * Stores each Realtime document as the Markdown file at its path in a Workspace working tree.
77
- * `history.checkpoint()` commits the working tree to Workspace history. `document: { workspace }`
78
- * in a Realtime Definition uses this adapter.
77
+ * `history.checkpoint()` commits the working tree to Workspace history with the Store's author by default.
78
+ * `document: { workspace }` in a Realtime Definition uses this adapter.
79
79
  */
80
- export declare function workspaceDocument(workspaceName: string): RealtimeWorkspaceDocumentAdapter;
80
+ export declare function workspaceDocument(workspaceName: string, checkpointAuthor?: RealtimeWorkspaceDocumentOptions["checkpointAuthor"]): RealtimeWorkspaceDocumentAdapter;
81
81
  export declare function isRealtimeWorkspaceDocument(adapter: RealtimeDocumentAdapter): adapter is RealtimeWorkspaceDocumentAdapter;
82
82
  //#endregion
83
83
  //#region src/server.d.ts
package/dist/server.js CHANGED
@@ -1,11 +1,11 @@
1
- import { a as internalRequestHeader, c as localRequesters, d as routePrefix, f as toDurableRequestReply, i as durableRoomsInstance, l as requestRealtimeRoom, m as isRealtimeAvailable, n as defaultRequestTimeout, o as isDurableSockets, p as workerDurableObjects, r as defaultRequestWait, s as isRealtimeDurableObjectNamespace, u as roomRequestError } from "./request-CWaHqW3R.js";
2
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
3
- import { _ as realtimeReadOnlyCode, a as decodeRealtimeRequestFramePayload, b as realtimeSyncPendingCode, c as encodeRealtimeRequestFrame, f as readAwarenessClientIds, g as realtimeKeepalivePong, h as realtimeKeepalivePing, l as encodeWorkspaceChange, m as realtimeInvalidDocumentCode, n as isRecord, o as decodeWorkspaceChangePayload, p as realtimeForbiddenWriteCloseCode, s as encodeRealtimeControl, v as realtimeResetCloseCode, y as realtimeSourceChangedCode } from "./object-CzKyK0hX.js";
1
+ import { a as internalRequestHeader, c as localRequesters, d as routePrefix, f as toDurableRequestReply, i as durableRoomsInstance, l as requestRealtimeRoom, m as isRealtimeAvailable, n as defaultRequestTimeout, o as isDurableSockets, p as workerDurableObjects, r as defaultRequestWait, s as isRealtimeDurableObjectNamespace, u as roomRequestError } from "./request-C_bQc4NE.js";
2
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
3
+ import { _ as realtimeReadOnlyCode, a as decodeRealtimeRequestFramePayload, b as realtimeSyncPendingCode, c as encodeRealtimeRequestFrame, f as readAwarenessClientIds, g as realtimeKeepalivePong, h as realtimeKeepalivePing, l as encodeWorkspaceChange, m as realtimeInvalidDocumentCode, n as isRecord, o as decodeWorkspaceChangePayload, p as realtimeForbiddenWriteCloseCode, s as encodeRealtimeControl, v as realtimeResetCloseCode, y as realtimeSourceChangedCode } from "./object-BgPPDLDE.js";
4
4
  import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
5
- import { t as createRealtimeIdentity } from "./presence-Tuy1y_l9.js";
6
- import { i as assertRealtimeCheckpoint, n as isRealtimeDocumentConflict, r as assertRealtimeAccess, t as RealtimeDocumentConflict } from "./conflict-Bg8vCisd.js";
5
+ import { t as createRealtimeIdentity } from "./presence-B6rvkHqd.js";
6
+ import { i as assertRealtimeCheckpoint, n as isRealtimeDocumentConflict, r as assertRealtimeAccess, t as RealtimeDocumentConflict } from "./conflict-DYC_qXzM.js";
7
7
  import { r as realtimeMarkdownEditor } from "./editor-BM5-vHqf.js";
8
- import { a as keepRealtimeFinalNewline, c as realtimeJsonEqual, d as writeRealtimeStatus, i as diffRealtimeYDoc, l as realtimeStatusFingerprint, n as containsRealtimeState, o as readRealtimeYDoc, r as createRealtimeYDoc, s as realtimeCodecReadsBack, t as checkRealtimeBody, u as writeRealtimeFields } from "./document-DjBrcgpY.js";
8
+ import { a as keepRealtimeFinalNewline, c as realtimeJsonEqual, d as writeRealtimeStatus, i as diffRealtimeYDoc, l as realtimeStatusFingerprint, n as containsRealtimeState, o as readRealtimeYDoc, r as createRealtimeYDoc, s as realtimeCodecReadsBack, t as checkRealtimeBody, u as writeRealtimeFields } from "./document-U5rzg2vG.js";
9
9
  import { getViteHubErrorShape } from "@vite-hub/runtime";
10
10
  import * as decoding from "lib0/decoding";
11
11
  import * as encoding from "lib0/encoding";
@@ -312,10 +312,10 @@ async function serializeWorkspace(workspaceName, operation) {
312
312
  }
313
313
  /**
314
314
  * Stores each Realtime document as the Markdown file at its path in a Workspace working tree.
315
- * `history.checkpoint()` commits the working tree to Workspace history. `document: { workspace }`
316
- * in a Realtime Definition uses this adapter.
315
+ * `history.checkpoint()` commits the working tree to Workspace history with the Store's author by default.
316
+ * `document: { workspace }` in a Realtime Definition uses this adapter.
317
317
  */
318
- function workspaceDocument(workspaceName) {
318
+ function workspaceDocument(workspaceName, checkpointAuthor) {
319
319
  return {
320
320
  kind: "workspace",
321
321
  workspace: workspaceName,
@@ -360,10 +360,14 @@ function workspaceDocument(workspaceName) {
360
360
  stored: { body: written.markdown }
361
361
  };
362
362
  },
363
- async checkpoint({ documentId }, { digest, message }) {
363
+ async checkpoint({ documentId }, { digest, message, user }) {
364
364
  return await serializeWorkspace(workspaceName, async () => {
365
365
  const workspace = useWorkspaceFiles(workspaceName, { mode: "write" });
366
- const options = { message: message || `docs: checkpoint ${documentId}` };
366
+ const author = user && checkpointAuthor ? await checkpointAuthor(user) : void 0;
367
+ const options = {
368
+ message: message || `docs: checkpoint ${documentId}`,
369
+ ...author ? { author } : {}
370
+ };
367
371
  let snapshot;
368
372
  try {
369
373
  try {
@@ -718,7 +722,7 @@ function resolveRealtimeDefinition(definition) {
718
722
  if (cached) return cached;
719
723
  assertRealtimeCheckpoint(definition);
720
724
  const document = definition.document;
721
- const adapter = isDocumentAdapter(document) ? document : workspaceDocument(document.workspace);
725
+ const adapter = isDocumentAdapter(document) ? document : workspaceDocument(document.workspace, document.checkpointAuthor);
722
726
  const persistence = definition.persistence === false ? false : {
723
727
  debounce: duration(definition.persistence?.debounce, realtimePersistenceDefaults.debounce, "debounce"),
724
728
  maxWait: duration(definition.persistence?.maxWait, realtimePersistenceDefaults.maxWait, "maxWait")
@@ -859,7 +863,7 @@ function toRealtimeUser(value) {
859
863
  return user;
860
864
  }
861
865
  async function identify(request, event, definitionName, definition) {
862
- if (definition.auth && !definition.identify) {
866
+ if (definition.authorize === true && !definition.identify) {
863
867
  let auth;
864
868
  try {
865
869
  auth = await assertAuthOrigin(request, event);
@@ -871,7 +875,9 @@ async function identify(request, event, definitionName, definition) {
871
875
  return user;
872
876
  }
873
877
  const origin = request.headers.get("origin");
874
- if (origin && origin !== forwardedRequestOrigin(request) && !await definition.origins?.({
878
+ const foreign = !!origin && origin !== forwardedRequestOrigin(request);
879
+ const readsCallbackSession = typeof definition.authorize === "function" && !definition.identify && !!origin && (!foreign || !definition.origins);
880
+ if (foreign && !readsCallbackSession && !await definition.origins?.({
875
881
  definition: definitionName,
876
882
  event,
877
883
  origin,
@@ -886,15 +892,15 @@ async function identify(request, event, definitionName, definition) {
886
892
  event,
887
893
  request
888
894
  }));
889
- if (definition.auth && !user) throw new HTTPError({ status: 401 });
895
+ if (definition.authorize === true && !user) throw new HTTPError({ status: 401 });
890
896
  return user;
891
897
  }
892
- if (definition.document !== false || definition.scope !== "user") return null;
898
+ if (!(typeof definition.authorize === "function" ? readsCallbackSession : definition.document === false && definition.scope === "user")) return null;
893
899
  let auth;
894
900
  try {
895
901
  auth = await assertAuthOrigin(request, event);
896
902
  } catch (error) {
897
- if (isMissingAuth(error)) return null;
903
+ if (!foreign && isMissingAuth(error)) return null;
898
904
  throw new HTTPError({ status: 403 });
899
905
  }
900
906
  return toRealtimeUser((await auth.api.getSession({ headers: request.headers }))?.user);
@@ -904,8 +910,9 @@ function isMissingAuth(error) {
904
910
  return typeof error === "object" && error !== null && "code" in error && error.code === "AUTH_R0005";
905
911
  }
906
912
  async function allows(definition, context) {
913
+ if (definition.authorize === true) return true;
907
914
  if (definition.authorize) return await definition.authorize(context) === true;
908
- return definition.auth === true || definition.access === "public";
915
+ return definition.access === "public";
909
916
  }
910
917
  function errorMessage(error) {
911
918
  if (error instanceof Error && error.message) return error.message;
@@ -2185,7 +2192,7 @@ function createRealtimeHandler(registry, options = {}) {
2185
2192
  snapshot = await adapter.checkpoint(room.context, {
2186
2193
  digest: saved.digest,
2187
2194
  message: configured === true ? void 0 : configured?.message,
2188
- user: user ?? saved.savedBy ?? void 0
2195
+ user: user ?? void 0
2189
2196
  });
2190
2197
  } catch (error) {
2191
2198
  if (!isRealtimeDocumentConflict(error) && !isWorkspaceConflict(error)) throw error;
@@ -2241,7 +2248,7 @@ function createRealtimeHandler(registry, options = {}) {
2241
2248
  message: "This Realtime Definition has no document."
2242
2249
  });
2243
2250
  if (action === "checkpoint" && !resolved.definition.history?.checkpoint) throw new HTTPError({ status: 404 });
2244
- if (!await request.access("read") || action !== "refresh" && !await request.access("write")) throw new HTTPError({ status: 403 });
2251
+ if (!await request.access("read") || action !== "refresh" && !await request.access("write")) throw new HTTPError({ status: request.user ? 403 : 401 });
2245
2252
  const state = action === "refresh" ? void 0 : await readRealtimeRequestState(event.req);
2246
2253
  if (state && !state.byteLength) throw new HTTPError({
2247
2254
  status: 400,
@@ -2263,7 +2270,7 @@ function createRealtimeHandler(registry, options = {}) {
2263
2270
  });
2264
2271
  const websocketHandler = defineWebSocketHandler(async (event) => {
2265
2272
  const request = await requestContext(event);
2266
- if (!await request.access("read")) throw new HTTPError({ status: 403 });
2273
+ if (!await request.access("read")) throw new HTTPError({ status: request.user ? 403 : 401 });
2267
2274
  const writable = !request.workspaceEvents && !!request.resolved && await request.access("write");
2268
2275
  const identity = request.user ? createRealtimeIdentity({ ...request.user }) : void 0;
2269
2276
  const room = request.workspaceEvents ? await getEventsRoom(JSON.stringify([request.definitionName, { workspaceEvents: true }]), true, void 0) : request.resolved ? await getDocumentRoom(request.definitionName, request.documentId, request.resolved, resolveRealtimeRoomSql(event)) : await getEventsRoom(realtimeRoomKey(request.definitionName, request.documentId, request.scope), false, resolveRealtimeRoomSql(event));
@@ -1,7 +1,14 @@
1
- import { ViteHubContext } from "@vite-hub/runtime";
1
+ import { ResultError, ViteHubContext } from "@vite-hub/runtime";
2
2
  import { AnyExtension, JSONContent } from "@tiptap/core";
3
- import { WorkspaceSnapshot } from "@vite-hub/workspace";
3
+ import { WorkspaceAuthor, WorkspaceSnapshot } from "@vite-hub/workspace";
4
4
  import { H3Event } from "h3";
5
+ //#region src/error-diagnostics.d.ts
6
+ /** The `data` of a `REALTIME_REQUEST_FAILED` error. */
7
+ type RealtimeRequestFailure = {
8
+ /** HTTP status of the server answer, such as `409` when the stored document changed. `undefined` for a network error. */
9
+ status: number | undefined;
10
+ };
11
+ //#endregion
5
12
  //#region src/types.d.ts
6
13
  /** JSON value stored in one field of a structured Realtime document. */
7
14
  type RealtimeFieldValue = null | boolean | number | string | RealtimeFieldValue[] | {
@@ -63,6 +70,7 @@ interface RealtimeHistoryOptions {
63
70
  /** Digest of the save that the history entry must contain. */
64
71
  digest: string;
65
72
  message?: string;
73
+ /** The checkpoint requester, when identified. */
66
74
  user?: RealtimeUser;
67
75
  }
68
76
  /**
@@ -96,6 +104,8 @@ interface RealtimeHoldOptions {
96
104
  interface RealtimeWorkspaceDocumentOptions {
97
105
  /** Workspace whose working tree stores the Markdown file at the document path. */
98
106
  workspace: string;
107
+ /** Resolve an author's name and email approved for Git history. Return undefined to keep the Store's author. */
108
+ checkpointAuthor?: (user: RealtimeUser) => WorkspaceAuthor | undefined | Promise<WorkspaceAuthor | undefined>;
99
109
  }
100
110
  /**
101
111
  * Editor schema and Markdown codec shared by the server and the browser. The server never
@@ -169,33 +179,28 @@ interface RealtimeDefinitionIdentity {
169
179
  identify?: (context: RealtimeRequestContext) => RealtimeUser | null | undefined | Promise<RealtimeUser | null | undefined>;
170
180
  /**
171
181
  * Let a page on another origin connect, such as a script that sites load from the app. Return `true` to accept
172
- * `origin`. Without it, only the app's own origin connects. The browser sends cookies with a cross-site handshake
182
+ * `origin`. Without it, only the app's own origin or an origin trusted by Auth connects. The browser sends cookies with a cross-site handshake
173
183
  * too, so `identify` and `authorize` must then trust only what the page sends on purpose, such as a ticket in
174
- * `params`, never the session cookie. `auth: true` without `identify` rejects it: the Auth session is a cookie.
184
+ * `params`, never the session cookie. `authorize: true` without `identify` rejects it: the Auth session is a cookie.
175
185
  */
176
186
  origins?: (context: RealtimeOriginContext) => boolean | Promise<boolean>;
177
187
  }
178
188
  type RealtimeAuthorize = (context: RealtimeAuthorizeContext) => boolean | Promise<boolean>;
179
189
  /**
180
- * Who can use the rooms. Set one: `auth: true` requires an identified user, `authorize()` decides each request, and
181
- * `access: "public"` lets anyone read and write.
190
+ * Who can use the rooms. Set one: `authorize: true` requires an identified user, `authorize()` decides each request,
191
+ * and `access: "public"` lets anyone read and write.
182
192
  */
183
193
  type RealtimeDefinitionAccess = RealtimeDefinitionIdentity & ({
184
194
  access?: never;
185
- /** Require an identified user. Without `identify`, the identity is the ViteHub Auth session. */
186
- auth: true;
187
- /** Allow or deny one access mode. Only `true` allows. Write denial makes a connection read-only. */
188
- authorize?: RealtimeAuthorize;
189
- } | {
190
- access?: never;
191
- /** Require an identified user. Without `identify`, the identity is the ViteHub Auth session. */
192
- auth?: boolean;
193
- /** Allow or deny one access mode. Only `true` allows. Write denial makes a connection read-only. */
194
- authorize: RealtimeAuthorize;
195
+ /**
196
+ * `true` requires an identified user: `identify()`, or the ViteHub Auth session without it. A callback decides each
197
+ * request and access mode. It gets the identified user, or `null` when the caller is signed out. Only `true` allows.
198
+ * Write denial makes a connection read-only.
199
+ */
200
+ authorize: true | RealtimeAuthorize;
195
201
  } | {
196
202
  /** Let anyone who can reach the app read and write every room of this definition. */
197
203
  access: "public";
198
- auth?: never;
199
204
  authorize?: never;
200
205
  });
201
206
  interface RealtimeDocumentFields {
@@ -229,7 +234,7 @@ interface RealtimePresenceFields {
229
234
  * `"user"`: each person gets their own rooms. A room is keyed by the identity of whoever joins it, so the same room id
230
235
  * for two people is two rooms, and `requestRealtimeRoom()` must name the person with `{ user }`. The identity is the
231
236
  * ViteHub Auth session when the app has Auth, read without requiring one; everyone without a session shares one
232
- * `anonymous` scope. With `identify` or `auth: true`, those decide the identity.
237
+ * `anonymous` scope. With `identify` or `authorize: true`, those decide the identity.
233
238
  */
234
239
  scope?: "user";
235
240
  }
@@ -297,12 +302,18 @@ type RealtimeResetReason = "source-changed" | "stale";
297
302
  type RealtimeRegistry = Record<string, () => Promise<{
298
303
  default: RealtimeDefinition;
299
304
  }>>;
305
+ /** The codes that `requestRealtimeRoom()` returns in `[error, undefined]`. */
306
+ type RealtimeRoomRequestErrorCode = "REALTIME_ROOM_ABORTED" | "REALTIME_ROOM_CROWDED" | "REALTIME_ROOM_ELSEWHERE" | "REALTIME_ROOM_EMPTY" | "REALTIME_ROOM_REFUSED" | "REALTIME_ROOM_REQUESTS_OFF" | "REALTIME_ROOM_TIMEOUT";
300
307
  /**
301
308
  * Codes that `save()`, `history.checkpoint()`, and `refresh()` of `useRealtimeTiptap()` return in the `[error, data]` tuple.
309
+ * When the server names why it refused the request, the code is that name, such as `REALTIME_SOURCE_CHANGED`. Other
310
+ * server and network errors are `REALTIME_REQUEST_FAILED`.
302
311
  */
303
- /** The codes that `requestRealtimeRoom()` returns in `[error, undefined]`. */
304
- type RealtimeRoomRequestErrorCode = "REALTIME_ROOM_ABORTED" | "REALTIME_ROOM_CROWDED" | "REALTIME_ROOM_ELSEWHERE" | "REALTIME_ROOM_EMPTY" | "REALTIME_ROOM_REFUSED" | "REALTIME_ROOM_REQUESTS_OFF" | "REALTIME_ROOM_TIMEOUT";
305
- type RealtimeRequestErrorCode = "REALTIME_DISABLED" | "REALTIME_DISCONNECTED" | "REALTIME_INVALID_RESPONSE" | "REALTIME_MISSING_DOCUMENT" | "REALTIME_REQUEST_FAILED";
312
+ type RealtimeRequestErrorCode = "REALTIME_DISABLED" | "REALTIME_DISCONNECTED" | "REALTIME_INVALID_DOCUMENT" | "REALTIME_INVALID_RESPONSE" | "REALTIME_MISSING_DOCUMENT" | "REALTIME_READ_ONLY" | "REALTIME_REQUEST_FAILED" | "REALTIME_SOURCE_CHANGED" | "REALTIME_SYNC_PENDING";
313
+ /** The error of `save()`, `history.checkpoint()`, and `refresh()`. Check `code` to read the typed `data`. */
314
+ type RealtimeRequestError = ResultError<Exclude<RealtimeRequestErrorCode, "REALTIME_REQUEST_FAILED">, undefined> | ResultError<"REALTIME_REQUEST_FAILED", RealtimeRequestFailure>;
315
+ /** The `[error, data]` tuple of `save()`, `history.checkpoint()`, and `refresh()`. */
316
+ type RealtimeRequestResult<TData> = [error: RealtimeRequestError, data: undefined] | [error: undefined, data: TData];
306
317
  /**
307
318
  * Whether this build has a Realtime room driver. ViteHub generates it for each build; an unavailable build says why
308
319
  * and how to enable Realtime.
@@ -316,4 +327,4 @@ type RealtimeAvailability = {
316
327
  fix: string;
317
328
  };
318
329
  //#endregion
319
- export { RealtimeSaveOptions as A, RealtimeReadOnlyReason as C, RealtimeRequestEvent as D, RealtimeRequestErrorCode as E, RealtimeWorkspaceChange as F, RealtimeWorkspaceDocumentOptions as I, RealtimeSaved as M, RealtimeUser as N, RealtimeResetReason as O, RealtimeVerifyResult as P, RealtimePresenceDefinition as S, RealtimeRequestContext as T, RealtimeLoadedDocument as _, RealtimeDefinition as a, RealtimePersistenceOptions as b, RealtimeDocumentContext as c, RealtimeDocumentStatus as d, RealtimeEditor as f, RealtimeIssue as g, RealtimeHoldOptions as h, RealtimeCheckpoint as i, RealtimeSaveResult as j, RealtimeRoomRequestErrorCode as k, RealtimeDocumentDefinition as l, RealtimeHistoryOptions as m, RealtimeAuthorizeContext as n, RealtimeDefinitionAccess as o, RealtimeFieldValue as p, RealtimeAvailability as r, RealtimeDocumentAdapter as s, DiscoveredRealtimeDefinition as t, RealtimeDocumentSnapshot as u, RealtimeOptions as v, RealtimeRegistry as w, RealtimePerson as x, RealtimeOriginContext as y };
330
+ export { RealtimeResetReason as A, RealtimeReadOnlyReason as C, RealtimeRequestErrorCode as D, RealtimeRequestError as E, RealtimeUser as F, RealtimeVerifyResult as I, RealtimeWorkspaceChange as L, RealtimeSaveOptions as M, RealtimeSaveResult as N, RealtimeRequestEvent as O, RealtimeSaved as P, RealtimeWorkspaceDocumentOptions as R, RealtimePresenceDefinition as S, RealtimeRequestContext as T, RealtimeLoadedDocument as _, RealtimeDefinition as a, RealtimePersistenceOptions as b, RealtimeDocumentContext as c, RealtimeDocumentStatus as d, RealtimeEditor as f, RealtimeIssue as g, RealtimeHoldOptions as h, RealtimeCheckpoint as i, RealtimeRoomRequestErrorCode as j, RealtimeRequestResult as k, RealtimeDocumentDefinition as l, RealtimeHistoryOptions as m, RealtimeAuthorizeContext as n, RealtimeDefinitionAccess as o, RealtimeFieldValue as p, RealtimeAvailability as r, RealtimeDocumentAdapter as s, DiscoveredRealtimeDefinition as t, RealtimeDocumentSnapshot as u, RealtimeOptions as v, RealtimeRegistry as w, RealtimePerson as x, RealtimeOriginContext as y, RealtimeRequestFailure as z };
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as DiscoveredRealtimeDefinition, v as RealtimeOptions } from "./types-1DVVG5ro.js";
1
+ import { t as DiscoveredRealtimeDefinition, v as RealtimeOptions } from "./types-Cvm0G3VJ.js";
2
2
  import { Plugin } from "vite";
3
3
  //#region src/discovery.d.ts
4
4
  export declare function discoverRealtimeDefinitions(rootDir: string, serverDirs?: string[]): DiscoveredRealtimeDefinition[];
package/dist/vite.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
- import { o as realtimeNamespaceVariable, s as realtimePostgresUrlVariable } from "./bus-Bi-Ec414.js";
3
- import { g as realtimeKeepalivePong, h as realtimeKeepalivePing, r as isRecordOrFunction, t as cloneRecord } from "./object-CzKyK0hX.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
+ import { o as realtimeNamespaceVariable, s as realtimePostgresUrlVariable } from "./bus-CKv8gQZf.js";
3
+ import { g as realtimeKeepalivePong, h as realtimeKeepalivePing, r as isRecordOrFunction, t as cloneRecord } from "./object-BgPPDLDE.js";
4
4
  import availability from "./internal/runtime/unavailable.js";
5
5
  import { defineDiagnostics } from "nostics";
6
6
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
@@ -271,7 +271,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
271
271
  },
272
272
  INTERNAL_R0004: {
273
273
  ...dynamicError,
274
- fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
274
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `url()` Source options, or ask the server for a smaller response."
275
275
  },
276
276
  INTERNAL_R0005: {
277
277
  ...dynamicError,
@@ -317,6 +317,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
317
317
  why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
318
318
  fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
319
319
  },
320
+ INTERNAL_DEV_SERVER_NOT_FOUND: {
321
+ why: ({ command }) => `[vitehub] No dev server of this project is running, and --url is not set, so \`vitehub ${command}\` has no app to call.`,
322
+ fix: "Start the dev server of this project, such as with `pnpm dev`, or pass --url with the app URL, such as --url http://localhost:3000."
323
+ },
320
324
  INTERNAL_FORGE_NOT_INSTALLED: {
321
325
  why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
322
326
  fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
@@ -503,6 +507,14 @@ function durabilityModuleFile(importMetaUrl) {
503
507
  return fileURLToPath(new URL(importMetaUrl.endsWith(".ts") ? "./durability.ts" : "./durability.js", importMetaUrl));
504
508
  }
505
509
  //#endregion
510
+ //#region ../internal/src/inspect.ts
511
+ function relativeDefinitionFile(projectRoot, file) {
512
+ return relative$1(projectRoot, file).replaceAll("\\", "/");
513
+ }
514
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
515
+ new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
516
+ new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
517
+ //#endregion
506
518
  //#region ../internal/src/build/vite.ts
507
519
  const projectRootDirectoryMarkers = [
508
520
  ["server", "agents"],
@@ -724,14 +736,6 @@ function discoverRealtimeDefinitions(rootDir, serverDirs) {
724
736
  })]);
725
737
  }
726
738
  //#endregion
727
- //#region ../internal/src/inspect.ts
728
- function relativeDefinitionFile(projectRoot, file) {
729
- return relative$1(projectRoot, file).replaceAll("\\", "/");
730
- }
731
- const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
732
- new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
733
- new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
734
- //#endregion
735
739
  //#region src/inspect.ts
736
740
  const driverLabels = {
737
741
  auto: "auto: Cloudflare Durable Objects on Cloudflare, memory in development, shared rooms on a Node server, build error elsewhere",
@@ -817,13 +821,14 @@ function describeRealtimeDefinitionSource(parse, file, source) {
817
821
  }];
818
822
  const values = properties(object);
819
823
  const editor = values.get("editor");
820
- const auth = literal(values.get("auth")) === true;
824
+ const signedIn = literal(values.get("authorize")) === true;
825
+ const callback = values.has("authorize") && !signedIn;
821
826
  const publicAccess = literal(values.get("access")) === "public";
822
- const authorization = (rule) => values.has("authorize") ? rule : publicAccess ? "public: anyone may read and write" : auth ? "every identified user" : "missing: the server rejects this definition";
827
+ const authorization = (rule) => callback ? rule : publicAccess ? "public: anyone may read and write" : signedIn ? "every identified user" : "missing: the server rejects this definition";
823
828
  const perDocument = editor?.type === "ArrowFunctionExpression" || editor?.type === "FunctionExpression";
824
829
  const identity = {
825
830
  label: "Identity",
826
- value: values.has("identify") ? `identify()${auth ? ", required" : ""}` : auth ? "ViteHub Auth session, required" : "anonymous; presence names are client-asserted"
831
+ value: values.has("identify") ? `identify()${signedIn ? ", required" : ""}` : signedIn ? "ViteHub Auth session, required" : callback ? "ViteHub Auth session when signed in" : "anonymous; presence names are client-asserted"
827
832
  };
828
833
  if (literal(values.get("document")) === false) return [
829
834
  {
@@ -1122,7 +1127,7 @@ function hubRealtime(options = {}) {
1122
1127
  kit.addHandler({
1123
1128
  handler: handlerFile,
1124
1129
  lazy: true,
1125
- route: `${mount}/api/_vitehub/realtime/**`
1130
+ route: `${mount}/_vitehub/realtime/**`
1126
1131
  });
1127
1132
  if (durablePlugin) kit.addPlugin(durablePlugin);
1128
1133
  if (busPlugin) kit.addPlugin(busPlugin);
package/dist/vue.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { C as RealtimeReadOnlyReason, E as RealtimeRequestErrorCode, F as RealtimeWorkspaceChange, M as RealtimeSaved, N as RealtimeUser, O as RealtimeResetReason, d as RealtimeDocumentStatus, f as RealtimeEditor, i as RealtimeCheckpoint, x as RealtimePerson } from "./types-1DVVG5ro.js";
2
- import { i as readRealtimeYDoc } from "./document-DPaywuCO.js";
3
- import { Result } from "@vite-hub/runtime";
1
+ import { A as RealtimeResetReason, C as RealtimeReadOnlyReason, D as RealtimeRequestErrorCode, E as RealtimeRequestError, F as RealtimeUser, L as RealtimeWorkspaceChange, P as RealtimeSaved, d as RealtimeDocumentStatus, f as RealtimeEditor, i as RealtimeCheckpoint, k as RealtimeRequestResult, x as RealtimePerson, z as RealtimeRequestFailure } from "./types-Cvm0G3VJ.js";
2
+ import { i as readRealtimeYDoc } from "./document-BfMW1zYU.js";
4
3
  import { Awareness } from "y-protocols/awareness";
5
4
  import { WebsocketProvider } from "y-websocket";
6
5
  import * as Y from "yjs";
@@ -64,18 +63,18 @@ export declare function useRealtimeTiptap(definition: string, documentId: MaybeR
64
63
  /** The server rejects edits from this connection. `readOnlyReason` tells why; `saveStatus` holds the details. */
65
64
  readOnly: import("vue").ComputedRef<boolean>;
66
65
  readOnlyReason: Ref<RealtimeReadOnlyReason | null, RealtimeReadOnlyReason | null>;
67
- refresh: () => Promise<Result<{
66
+ refresh: () => Promise<RealtimeRequestResult<{
68
67
  digest: string | null;
69
68
  reseeded: boolean;
70
- }, RealtimeRequestErrorCode>>;
69
+ }>>;
71
70
  onReset: (listener: (event: RealtimeResetEvent) => void) => () => void;
72
- save: () => Promise<Result<RealtimeSaved, RealtimeRequestErrorCode>>;
71
+ save: () => Promise<RealtimeRequestResult<RealtimeSaved>>;
73
72
  saveStatus: import("vue").ShallowRef<RealtimeDocumentStatus | undefined, RealtimeDocumentStatus | undefined>;
74
73
  saving: import("vue").ComputedRef<boolean>;
75
74
  status: Ref<RealtimeStatus, RealtimeStatus>;
76
75
  synced: Ref<boolean, boolean>;
77
76
  history: {
78
- checkpoint: () => Promise<Result<RealtimeCheckpoint, RealtimeRequestErrorCode>>;
77
+ checkpoint: () => Promise<RealtimeRequestResult<RealtimeCheckpoint>>;
79
78
  pending: import("vue").ComputedRef<boolean>;
80
79
  };
81
80
  workspace: {
@@ -85,4 +84,4 @@ export declare function useRealtimeTiptap(definition: string, documentId: MaybeR
85
84
  destroy: () => void;
86
85
  };
87
86
  //#endregion
88
- export { type RealtimeCaretOptions, type RealtimeCaretUser, type RealtimeRequestErrorCode, readRealtimeYDoc };
87
+ export { type RealtimeCaretOptions, type RealtimeCaretUser, type RealtimeRequestError, type RealtimeRequestErrorCode, type RealtimeRequestFailure, type RealtimeRequestResult, readRealtimeYDoc };
package/dist/vue.js CHANGED
@@ -1,10 +1,10 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-B_66irmt.js";
2
- import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } from "./keepalive-BCs-uXp4.js";
3
- import { i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, n as isRecord, o as decodeWorkspaceChangePayload, u as isRetryableRealtimeRequestCode, x as workspaceRoomId } from "./object-CzKyK0hX.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
+ import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } from "./keepalive-B4ONG6AD.js";
3
+ import { _ as realtimeReadOnlyCode, b as realtimeSyncPendingCode, i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, m as realtimeInvalidDocumentCode, n as isRecord, o as decodeWorkspaceChangePayload, u as isRetryableRealtimeRequestCode, x as workspaceRoomId, y as realtimeSourceChangedCode } from "./object-BgPPDLDE.js";
4
4
  import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
5
- import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-Tuy1y_l9.js";
5
+ import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-B6rvkHqd.js";
6
6
  import { t as createRealtimeEditorExtensions } from "./editor-BM5-vHqf.js";
7
- import { _ as yCursorPlugin, b as yUndoPlugin, f as absolutePositionToRelativePosition, g as undo, h as relativePositionToAbsolutePosition, m as redo, o as readRealtimeYDoc, p as defaultSelectionBuilder, v as ySyncPlugin, x as yUndoPluginKey, y as ySyncPluginKey } from "./document-DjBrcgpY.js";
7
+ import { _ as yCursorPlugin, b as yUndoPlugin, f as absolutePositionToRelativePosition, g as undo, h as relativePositionToAbsolutePosition, m as redo, o as readRealtimeYDoc, p as defaultSelectionBuilder, v as ySyncPlugin, x as yUndoPluginKey, y as ySyncPluginKey } from "./document-U5rzg2vG.js";
8
8
  import "lib0/decoding";
9
9
  import * as encoding from "lib0/encoding";
10
10
  import * as awarenessProtocol from "y-protocols/awareness";
@@ -239,6 +239,15 @@ const RealtimeCaret = Extension.create({
239
239
  });
240
240
  //#endregion
241
241
  //#region src/vue.ts
242
+ /** The error for a code that the server put in `data.code` of a refused request, so the app can tell the reasons apart. */
243
+ function serverRequestError(code, action) {
244
+ switch (code) {
245
+ case realtimeInvalidDocumentCode: return realtimeErrorDiagnostics.REALTIME_INVALID_DOCUMENT({ action });
246
+ case realtimeReadOnlyCode: return realtimeErrorDiagnostics.REALTIME_READ_ONLY({ action });
247
+ case realtimeSourceChangedCode: return realtimeErrorDiagnostics.REALTIME_SOURCE_CHANGED({ action });
248
+ case realtimeSyncPendingCode: return realtimeErrorDiagnostics.REALTIME_SYNC_PENDING({ action });
249
+ }
250
+ }
242
251
  const workspaceChangeFlushIntervalMs = 11;
243
252
  function isString(value) {
244
253
  return typeof value === "string";
@@ -304,17 +313,16 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
304
313
  let workspaceChangeTimer;
305
314
  const enabled = () => options.enabled === void 0 || toValue(options.enabled);
306
315
  let canConnect = !getCurrentInstance();
307
- function destroyDocument(keepDocument = false, preserveRefresh = false) {
308
- for (const controller of requestControllers) if (!preserveRefresh || !refreshControllers.has(controller)) controller.abort();
309
- if (preserveRefresh) {
310
- for (const controller of requestControllers) if (!refreshControllers.has(controller)) requestControllers.delete(controller);
311
- } else {
312
- requestControllers.clear();
313
- refreshControllers.clear();
316
+ function destroyDocument(resetReason) {
317
+ for (const controller of requestControllers) {
318
+ if (resetReason === "source-changed" || resetReason && refreshControllers.has(controller)) continue;
319
+ controller.abort();
320
+ requestControllers.delete(controller);
321
+ refreshControllers.delete(controller);
314
322
  }
315
323
  connectedDocumentId = void 0;
316
324
  provider.value?.destroy();
317
- if (!keepDocument) document.value?.destroy();
325
+ if (!resetReason) document.value?.destroy();
318
326
  provider.value = void 0;
319
327
  document.value = void 0;
320
328
  people.value = [];
@@ -363,7 +371,7 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
363
371
  pendingWorkspaceChanges.length = 0;
364
372
  }
365
373
  function serverURL() {
366
- return `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}`)}`;
374
+ return `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}${resolveRealtimeApplicationPath(`/_vitehub/realtime/${encodeURIComponent(definition)}`)}`;
367
375
  }
368
376
  if (typeof window !== "undefined") {
369
377
  const workspaceDocument = markRaw(new Y.Doc());
@@ -444,7 +452,7 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
444
452
  }
445
453
  function reset(id, reason, epoch) {
446
454
  const previous = document.value;
447
- destroyDocument(true, true);
455
+ destroyDocument(reason);
448
456
  if (previous) try {
449
457
  for (const listener of resetListeners) listener({
450
458
  epoch,
@@ -471,18 +479,19 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
471
479
  const room = id.split("/").map(encodeURIComponent).join("/");
472
480
  const current = document.value;
473
481
  const query = action === "checkpoint" ? "history=checkpoint" : `document=${action}`;
474
- const stillCurrent = () => !controller.signal.aborted && !!current && connectedDocumentId === id && document.value === current && toValue(documentId) === id && enabled();
482
+ const stillInScope = () => !controller.signal.aborted && toValue(documentId) === id && enabled();
483
+ const stillCurrent = () => !!current && connectedDocumentId === id && document.value === current;
475
484
  for (let attempt = 0;; attempt++) {
476
- if (action !== "refresh" && !stillCurrent()) return disconnected();
485
+ if (!stillInScope() || action !== "refresh" && !stillCurrent()) return disconnected();
477
486
  let response;
478
487
  try {
479
- response = await fetch(resolveRealtimeApplicationPath(`/api/_vitehub/realtime/${encodeURIComponent(definition)}/${room}?${query}`), {
488
+ response = await fetch(resolveRealtimeApplicationPath(`/_vitehub/realtime/${encodeURIComponent(definition)}/${room}?${query}`), {
480
489
  body: action === "refresh" ? void 0 : Uint8Array.from(Y.encodeStateAsUpdate(current)).buffer,
481
490
  method: "POST",
482
491
  signal: controller.signal
483
492
  });
484
493
  } catch (cause) {
485
- if (controller.signal.aborted) return disconnected();
494
+ if (!stillInScope() || action !== "refresh" && !stillCurrent()) return disconnected();
486
495
  return [realtimeErrorDiagnostics.REALTIME_REQUEST_FAILED({
487
496
  action,
488
497
  cause
@@ -492,18 +501,20 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
492
501
  try {
493
502
  data = await response.json();
494
503
  } catch {
495
- if (controller.signal.aborted) return disconnected();
504
+ data = void 0;
496
505
  }
497
- if (action !== "refresh" && !stillCurrent()) return disconnected();
498
- if (response.ok) return [void 0, data];
506
+ if (!stillInScope()) return disconnected();
499
507
  const errorData = isRecord(data) ? data : void 0;
500
508
  const nestedData = isRecord(errorData?.data) ? errorData.data : void 0;
509
+ const serverCode = isString(nestedData?.code) ? nestedData.code : void 0;
510
+ if (action !== "refresh" && !stillCurrent() && (response.ok || serverCode !== "REALTIME_SOURCE_CHANGED")) return disconnected();
511
+ if (response.ok) return [void 0, data];
501
512
  const message = isString(errorData?.statusMessage) && errorData.statusMessage ? errorData.statusMessage : isString(errorData?.message) ? errorData.message : void 0;
502
- if (response.status === 409 && isRetryableRealtimeRequestCode(isString(nestedData?.code) ? nestedData.code : void 0) && attempt < 20) {
513
+ if (response.status === 409 && isRetryableRealtimeRequestCode(serverCode) && attempt < 20) {
503
514
  await new Promise((resolve) => setTimeout(resolve, 50));
504
515
  continue;
505
516
  }
506
- return [realtimeErrorDiagnostics.REALTIME_REQUEST_FAILED({
517
+ return [serverRequestError(serverCode, action) ?? realtimeErrorDiagnostics.REALTIME_REQUEST_FAILED({
507
518
  action,
508
519
  message,
509
520
  status: response.status
@@ -522,7 +533,7 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
522
533
  }
523
534
  /**
524
535
  * Saves the room through its document adapter now, including every edit this client has sent.
525
- * Returns `[error, saved]`; `error.code` is a `RealtimeRequestErrorCode`.
536
+ * Returns `[error, saved]`; `error.code` is a `RealtimeRequestErrorCode`; `REALTIME_REQUEST_FAILED` has the HTTP status in `error.data.status`.
526
537
  */
527
538
  async function save() {
528
539
  if (!enabled()) return [realtimeErrorDiagnostics.REALTIME_DISABLED({ action: "save" }), void 0];
@@ -535,7 +546,7 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
535
546
  }
536
547
  /**
537
548
  * Saves the room and records a durable history entry through the document adapter.
538
- * Returns `[error, checkpoint]`; `error.code` is a `RealtimeRequestErrorCode`.
549
+ * Returns `[error, checkpoint]`; `error.code` is a `RealtimeRequestErrorCode`; `REALTIME_REQUEST_FAILED` has the HTTP status in `error.data.status`.
539
550
  */
540
551
  async function checkpoint() {
541
552
  if (!enabled()) return [realtimeErrorDiagnostics.REALTIME_DISABLED({ action: "checkpoint" }), void 0];
@@ -548,7 +559,7 @@ function useRealtimeTiptap(definition, documentId, options = {}) {
548
559
  }
549
560
  /**
550
561
  * Asks the room to compare its seed with the stored document. A changed source resets every client.
551
- * Returns `[error, result]`; `error.code` is a `RealtimeRequestErrorCode`.
562
+ * Returns `[error, result]`; `error.code` is a `RealtimeRequestErrorCode`; `REALTIME_REQUEST_FAILED` has the HTTP status in `error.data.status`.
552
563
  */
553
564
  async function refresh() {
554
565
  return await requestResult("refresh", isRefreshResult);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/realtime",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Realtime document primitives and Vite integration for ViteHub.",
5
5
  "keywords": [
6
6
  "collaboration",
@@ -91,8 +91,8 @@
91
91
  "dependencies": {
92
92
  "@tiptap/extension-collaboration": "^3.31.4",
93
93
  "@tiptap/y-tiptap": "^3.0.9",
94
- "@vite-hub/auth": "0.3.0",
95
- "@vite-hub/workspace": "0.3.0",
94
+ "@vite-hub/auth": "0.4.1",
95
+ "@vite-hub/workspace": "0.4.1",
96
96
  "h3": "^2.0.8",
97
97
  "ioredis": "^5.11.1",
98
98
  "lib0": "^0.2.119",
@@ -105,7 +105,7 @@
105
105
  "prosemirror-view": "^1.42.3",
106
106
  "y-protocols": "^1.0.7",
107
107
  "y-websocket": "^3.1.0",
108
- "@vite-hub/runtime": "0.3.0"
108
+ "@vite-hub/runtime": "0.4.1"
109
109
  },
110
110
  "devDependencies": {
111
111
  "@tiptap/core": "^3.31.4",
@@ -119,7 +119,7 @@
119
119
  "@tiptap/starter-kit": "^3.31.4",
120
120
  "@types/json-schema": "^7.0.15",
121
121
  "@types/node": "^24.19.1",
122
- "@vite-hub/database": "0.3.0",
122
+ "@vite-hub/database": "0.4.1",
123
123
  "@vite-hub/internal": "0.0.1",
124
124
  "happy-dom": "21.0.3",
125
125
  "linkedom": "^0.18.13",
@@ -160,7 +160,7 @@
160
160
  }
161
161
  },
162
162
  "engines": {
163
- "node": ">=22.18.0"
163
+ "node": ">=24.15.0"
164
164
  },
165
165
  "scripts": {
166
166
  "build": "vp pack",