@pairdraw/cloud 0.0.0-stage → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-MIT +21 -0
  3. package/NOTICE +7 -0
  4. package/README.md +37 -2
  5. package/dist/bin/ai-relay.d.mts +1 -0
  6. package/dist/bin/ai-relay.mjs +31 -0
  7. package/dist/bin/ai-relay.mjs.map +1 -0
  8. package/dist/bin/server.d.mts +1 -0
  9. package/dist/bin/server.mjs +29 -0
  10. package/dist/bin/server.mjs.map +1 -0
  11. package/dist/client.d.ts +1578 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +2008 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/contract.d.ts +2 -0
  16. package/dist/contract.js +2 -0
  17. package/dist/contract2.js +1673 -0
  18. package/dist/contract2.js.map +1 -0
  19. package/dist/email.d.ts +155 -0
  20. package/dist/email.d.ts.map +1 -0
  21. package/dist/email.js +700 -0
  22. package/dist/email.js.map +1 -0
  23. package/dist/index.d.ts +1945 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/listen.mjs +1905 -0
  26. package/dist/listen.mjs.map +1 -0
  27. package/dist/runtime-node.d.mts +10715 -0
  28. package/dist/runtime-node.d.mts.map +1 -0
  29. package/dist/runtime-node.mjs +32 -0
  30. package/dist/runtime-node.mjs.map +1 -0
  31. package/dist/server.d.ts +13772 -0
  32. package/dist/server.d.ts.map +1 -0
  33. package/dist/server.js +8856 -0
  34. package/dist/server.js.map +1 -0
  35. package/dist/server.mjs +8836 -0
  36. package/dist/server.mjs.map +1 -0
  37. package/dist/server2.mjs +505 -0
  38. package/dist/server2.mjs.map +1 -0
  39. package/package.json +120 -4
  40. package/src/admin/api/routes.ts +223 -0
  41. package/src/admin/api/security.ts +12 -0
  42. package/src/admin/audit/service.ts +138 -0
  43. package/src/admin/email/service.ts +140 -0
  44. package/src/admin/enrollment/email.ts +77 -0
  45. package/src/admin/enrollment/service.ts +308 -0
  46. package/src/admin/errors.ts +20 -0
  47. package/src/admin/index.ts +19 -0
  48. package/src/admin/list.ts +61 -0
  49. package/src/admin/operations/service.ts +70 -0
  50. package/src/admin/schema.ts +26 -0
  51. package/src/admin/users/service.ts +369 -0
  52. package/src/ai-relay/app.ts +251 -0
  53. package/src/ai-relay/config.ts +120 -0
  54. package/src/ai-relay/db/index.ts +10 -0
  55. package/src/ai-relay/db/migrate.ts +32 -0
  56. package/src/ai-relay/db/migrations/001_usage.ts +26 -0
  57. package/src/ai-relay/db/schema.ts +20 -0
  58. package/src/ai-relay/index.ts +18 -0
  59. package/src/ai-relay/metering.ts +68 -0
  60. package/src/ai-relay/usage.ts +115 -0
  61. package/src/client/ai.ts +96 -0
  62. package/src/client/api.ts +530 -0
  63. package/src/client/auth/client.ts +188 -0
  64. package/src/client/auth/failure.ts +54 -0
  65. package/src/client/auth/navigation.ts +45 -0
  66. package/src/client/device-authorization.ts +134 -0
  67. package/src/client/discovery.ts +105 -0
  68. package/src/client/images.ts +81 -0
  69. package/src/client/index.ts +53 -0
  70. package/src/client/portal/account.ts +183 -0
  71. package/src/client/portal/administration.ts +130 -0
  72. package/src/client/portal/client.ts +18 -0
  73. package/src/client/portal/request.ts +115 -0
  74. package/src/client/profiles.ts +79 -0
  75. package/src/client/response.ts +51 -0
  76. package/src/client/workspaces.ts +142 -0
  77. package/src/contract/account.ts +204 -0
  78. package/src/contract/admin/index.ts +187 -0
  79. package/src/contract/ai.ts +150 -0
  80. package/src/contract/collaboration.ts +45 -0
  81. package/src/contract/comments.ts +149 -0
  82. package/src/contract/discovery.ts +81 -0
  83. package/src/contract/documents.ts +263 -0
  84. package/src/contract/entitlements.ts +28 -0
  85. package/src/contract/index.ts +210 -0
  86. package/src/contract/links.ts +108 -0
  87. package/src/contract/portal.ts +11 -0
  88. package/src/contract/profiles.ts +88 -0
  89. package/src/contract/relay.ts +370 -0
  90. package/src/contract/sharing.ts +215 -0
  91. package/src/contract/versions.ts +87 -0
  92. package/src/contract/workspaces.ts +100 -0
  93. package/src/email/index.ts +13 -0
  94. package/src/email/render.ts +304 -0
  95. package/src/email/schema.ts +144 -0
  96. package/src/email/templates/brand.ts +125 -0
  97. package/src/email/templates/document-invitation.ts +39 -0
  98. package/src/email/templates/enrollment.ts +30 -0
  99. package/src/email/templates/layout.ts +20 -0
  100. package/src/runtime/cloudflare/email.ts +70 -0
  101. package/src/runtime/cloudflare/environment.ts +57 -0
  102. package/src/runtime/cloudflare/index.ts +3 -0
  103. package/src/runtime/cloudflare/relay.ts +136 -0
  104. package/src/runtime/cloudflare/site.ts +13 -0
  105. package/src/runtime/cloudflare/tsconfig.json +21 -0
  106. package/src/runtime/cloudflare/worker.ts +161 -0
  107. package/src/runtime/node/admin.ts +59 -0
  108. package/src/runtime/node/ai-relay/main.ts +35 -0
  109. package/src/runtime/node/ai-relay/server.ts +63 -0
  110. package/src/runtime/node/application.ts +50 -0
  111. package/src/runtime/node/bootstrap.ts +22 -0
  112. package/src/runtime/node/cleanup.ts +24 -0
  113. package/src/runtime/node/command.ts +17 -0
  114. package/src/runtime/node/config.ts +16 -0
  115. package/src/runtime/node/email/runtime.ts +44 -0
  116. package/src/runtime/node/email/transport.ts +112 -0
  117. package/src/runtime/node/entitlements/main.ts +41 -0
  118. package/src/runtime/node/entitlements/refusal.ts +15 -0
  119. package/src/runtime/node/index.ts +25 -0
  120. package/src/runtime/node/listen.ts +35 -0
  121. package/src/runtime/node/main.ts +29 -0
  122. package/src/runtime/node/migrate.ts +13 -0
  123. package/src/runtime/node/quota-reconcile.ts +9 -0
  124. package/src/runtime/node/relay.ts +54 -0
  125. package/src/runtime/node/server.ts +119 -0
  126. package/src/runtime/node/site.ts +64 -0
  127. package/src/runtime/postgres/database.ts +19 -0
  128. package/src/runtime/s3/objects.ts +244 -0
  129. package/src/runtime/site/server.ts +82 -0
  130. package/src/server/account/actions.ts +66 -0
  131. package/src/server/account/routes.ts +300 -0
  132. package/src/server/ai/errors.ts +7 -0
  133. package/src/server/ai/index.ts +4 -0
  134. package/src/server/ai/keys.ts +43 -0
  135. package/src/server/ai/routes.ts +43 -0
  136. package/src/server/ai/service.ts +70 -0
  137. package/src/server/api/index.ts +8 -0
  138. package/src/server/api/router.ts +129 -0
  139. package/src/server/api/types.ts +7 -0
  140. package/src/server/app.ts +385 -0
  141. package/src/server/auth/account.ts +73 -0
  142. package/src/server/auth/activity.ts +213 -0
  143. package/src/server/auth/adapter.ts +79 -0
  144. package/src/server/auth/email.ts +125 -0
  145. package/src/server/auth/endpoints.ts +57 -0
  146. package/src/server/auth/factory.ts +583 -0
  147. package/src/server/auth/index.ts +17 -0
  148. package/src/server/auth/mfa-assurance.ts +55 -0
  149. package/src/server/auth/runtime.ts +26 -0
  150. package/src/server/auth/session.ts +19 -0
  151. package/src/server/auth/social-providers.ts +55 -0
  152. package/src/server/auth/user-agent.ts +16 -0
  153. package/src/server/auth/workspace-access.ts +23 -0
  154. package/src/server/cleanup/configured.ts +38 -0
  155. package/src/server/cleanup/documents.ts +231 -0
  156. package/src/server/cleanup/index.ts +29 -0
  157. package/src/server/cleanup/objects.ts +27 -0
  158. package/src/server/cleanup/revisions.ts +246 -0
  159. package/src/server/cleanup/uploads.ts +129 -0
  160. package/src/server/cleanup/worker.ts +79 -0
  161. package/src/server/collaboration/index.ts +28 -0
  162. package/src/server/collaboration/relay/authorize.ts +54 -0
  163. package/src/server/collaboration/relay/awareness.ts +104 -0
  164. package/src/server/collaboration/relay/comments.ts +86 -0
  165. package/src/server/collaboration/relay/documents.ts +39 -0
  166. package/src/server/collaboration/relay/hub.ts +567 -0
  167. package/src/server/collaboration/relay/index.ts +15 -0
  168. package/src/server/collaboration/relay/persistence.ts +48 -0
  169. package/src/server/collaboration/routes.ts +77 -0
  170. package/src/server/collaboration/service.ts +190 -0
  171. package/src/server/config/deployment.ts +178 -0
  172. package/src/server/config/index.ts +20 -0
  173. package/src/server/config/limits.ts +8 -0
  174. package/src/server/config/public.ts +66 -0
  175. package/src/server/config/schema.ts +512 -0
  176. package/src/server/db/database.ts +15 -0
  177. package/src/server/db/expressions.ts +13 -0
  178. package/src/server/db/index.ts +21 -0
  179. package/src/server/db/migrate.ts +177 -0
  180. package/src/server/db/migrations/001_foundation.ts +164 -0
  181. package/src/server/db/migrations/002_upload_cleanup_claims.ts +34 -0
  182. package/src/server/db/migrations/003_document_cleanup_claims.ts +23 -0
  183. package/src/server/db/migrations/004_document_sharing.ts +82 -0
  184. package/src/server/db/migrations/005_document_collaboration_epoch.ts +13 -0
  185. package/src/server/db/migrations/006_invitation_continuation.ts +27 -0
  186. package/src/server/db/migrations/007_collaboration_state.ts +25 -0
  187. package/src/server/db/migrations/008_storage_reservations.ts +37 -0
  188. package/src/server/db/migrations/009_workspace_entitlements.ts +22 -0
  189. package/src/server/db/migrations/010_upload_finalization.ts +22 -0
  190. package/src/server/db/migrations/011_upload_finalization_lease.ts +12 -0
  191. package/src/server/db/migrations/012_transactional_email.ts +48 -0
  192. package/src/server/db/migrations/013_admin_enrollment.ts +54 -0
  193. package/src/server/db/migrations/014_enrollment_email_kinds.ts +30 -0
  194. package/src/server/db/migrations/015_cloud_rate_limit.ts +22 -0
  195. package/src/server/db/migrations/016_auth_schema.ts +16 -0
  196. package/src/server/db/migrations/017_authentication_email_kinds.ts +32 -0
  197. package/src/server/db/migrations/018_authentication_mfa.ts +78 -0
  198. package/src/server/db/migrations/019_better_auth_account_issuer.ts +42 -0
  199. package/src/server/db/migrations/020_workspace_invitations.ts +57 -0
  200. package/src/server/db/migrations/021_document_versions.ts +66 -0
  201. package/src/server/db/migrations/022_entitlement_external_version.ts +17 -0
  202. package/src/server/db/migrations/023_document_images.ts +61 -0
  203. package/src/server/db/migrations/024_account_activity.ts +66 -0
  204. package/src/server/db/migrations/025_table_names.ts +58 -0
  205. package/src/server/db/migrations/026_user_picture.ts +30 -0
  206. package/src/server/db/migrations/027_sharing_comments_snapshots_profiles.ts +74 -0
  207. package/src/server/db/migrations/helpers.ts +78 -0
  208. package/src/server/db/tables.ts +399 -0
  209. package/src/server/documents/access.ts +103 -0
  210. package/src/server/documents/errors.ts +16 -0
  211. package/src/server/documents/images.ts +405 -0
  212. package/src/server/documents/index.ts +14 -0
  213. package/src/server/documents/limits.ts +57 -0
  214. package/src/server/documents/repository.ts +131 -0
  215. package/src/server/documents/routes.ts +239 -0
  216. package/src/server/documents/service.ts +607 -0
  217. package/src/server/documents/summary.ts +36 -0
  218. package/src/server/documents/types.ts +13 -0
  219. package/src/server/documents/versions/checkpoint.ts +98 -0
  220. package/src/server/documents/versions/history.ts +25 -0
  221. package/src/server/documents/versions/index.ts +4 -0
  222. package/src/server/documents/versions/routes.ts +112 -0
  223. package/src/server/documents/versions/service.ts +396 -0
  224. package/src/server/email/crypto.ts +57 -0
  225. package/src/server/email/index.ts +18 -0
  226. package/src/server/email/invitations.ts +30 -0
  227. package/src/server/email/service.ts +247 -0
  228. package/src/server/email/types.ts +56 -0
  229. package/src/server/email/worker.ts +33 -0
  230. package/src/server/index.ts +288 -0
  231. package/src/server/internal/index.ts +8 -0
  232. package/src/server/internal/routes.ts +41 -0
  233. package/src/server/internal/schema.ts +10 -0
  234. package/src/server/internal/service.ts +44 -0
  235. package/src/server/invitations/index.ts +6 -0
  236. package/src/server/invitations/types.ts +30 -0
  237. package/src/server/objects/index.ts +16 -0
  238. package/src/server/objects/types.ts +81 -0
  239. package/src/server/pictures/index.ts +9 -0
  240. package/src/server/pictures/provider.ts +61 -0
  241. package/src/server/pictures/routes.ts +21 -0
  242. package/src/server/pictures/service.ts +235 -0
  243. package/src/server/policy/configured.ts +23 -0
  244. package/src/server/policy/database.ts +108 -0
  245. package/src/server/policy/entitlements.ts +29 -0
  246. package/src/server/policy/index.ts +17 -0
  247. package/src/server/policy/keys.ts +23 -0
  248. package/src/server/policy/policy.ts +117 -0
  249. package/src/server/policy/provider.ts +67 -0
  250. package/src/server/policy/schema.ts +69 -0
  251. package/src/server/policy/service.ts +85 -0
  252. package/src/server/policy/static.ts +62 -0
  253. package/src/server/profiles/index.ts +12 -0
  254. package/src/server/profiles/routes.ts +103 -0
  255. package/src/server/profiles/service.ts +266 -0
  256. package/src/server/quota/index.ts +7 -0
  257. package/src/server/quota/reconcile.ts +61 -0
  258. package/src/server/quota/storage.ts +165 -0
  259. package/src/server/rate-limit/cleanup.ts +16 -0
  260. package/src/server/rate-limit/index.ts +12 -0
  261. package/src/server/rate-limit/keys.ts +38 -0
  262. package/src/server/rate-limit/middleware.ts +137 -0
  263. package/src/server/rate-limit/postgres.ts +79 -0
  264. package/src/server/sharing/access.ts +29 -0
  265. package/src/server/sharing/actor.ts +12 -0
  266. package/src/server/sharing/capabilities/service.ts +318 -0
  267. package/src/server/sharing/continuation.ts +83 -0
  268. package/src/server/sharing/contracts.ts +82 -0
  269. package/src/server/sharing/crypto.ts +48 -0
  270. package/src/server/sharing/document-routes.ts +41 -0
  271. package/src/server/sharing/errors.ts +20 -0
  272. package/src/server/sharing/grants/service.ts +79 -0
  273. package/src/server/sharing/http.ts +45 -0
  274. package/src/server/sharing/index.ts +40 -0
  275. package/src/server/sharing/invitations/service.ts +315 -0
  276. package/src/server/sharing/policy.ts +42 -0
  277. package/src/server/sharing/routes.ts +251 -0
  278. package/src/server/sharing/service.ts +117 -0
  279. package/src/server/validation.ts +24 -0
  280. package/src/server/worker/interval.ts +23 -0
  281. package/src/server/worker/periodic.ts +42 -0
  282. package/src/server/workspaces/index.ts +16 -0
  283. package/src/server/workspaces/members.ts +502 -0
  284. package/src/server/workspaces/repository.ts +91 -0
  285. package/src/server/workspaces/routes.ts +198 -0
  286. package/src/server/workspaces/service.ts +84 -0
@@ -0,0 +1,1673 @@
1
+ import { isValid } from "js-base64";
2
+ import * as v from "valibot";
3
+ import { isEqual, omitBy, zipObject } from "es-toolkit";
4
+ import { Inflate, deflateSync } from "fflate";
5
+ import * as decoding from "lib0/decoding";
6
+ import * as encoding from "lib0/encoding";
7
+ import * as Y from "yjs";
8
+ import { commentThreadsSchema } from "@pairdraw/scene-graph/comments";
9
+ import { encodeParam, parseURL, withFragment, withQuery } from "ufo";
10
+ //#region src/contract/account.ts
11
+ const cloudAccountStateSchema = v.picklist([
12
+ "active",
13
+ "pending",
14
+ "rejected",
15
+ "revoked"
16
+ ]);
17
+ const cloudIdentitySchema = v.object({
18
+ userId: v.string(),
19
+ email: v.pipe(v.string(), v.email()),
20
+ name: v.string(),
21
+ /** The account's picture, such as one a social provider gave it. */
22
+ image: v.optional(v.nullable(v.string())),
23
+ deploymentRole: v.optional(v.picklist(["user", "admin"]))
24
+ });
25
+ const cloudAccountStatusResponseSchema = v.object({
26
+ user: cloudIdentitySchema,
27
+ state: cloudAccountStateSchema
28
+ });
29
+ const cloudAuthenticationProviderSchema = v.picklist([
30
+ "credential",
31
+ "google",
32
+ "apple"
33
+ ]);
34
+ const cloudAuthenticationMethodSchema = v.object({
35
+ id: v.string(),
36
+ provider: cloudAuthenticationProviderSchema,
37
+ createdAt: v.string(),
38
+ canUnlink: v.boolean()
39
+ });
40
+ const cloudAuthenticationMethodsResponseSchema = v.object({
41
+ methods: v.array(cloudAuthenticationMethodSchema),
42
+ availableSocialProviders: v.array(v.picklist(["google", "apple"]))
43
+ });
44
+ const cloudPasswordChangeSchema = v.object({
45
+ currentPassword: v.string(),
46
+ newPassword: v.string()
47
+ });
48
+ const cloudSocialLinkSchema = v.object({
49
+ provider: v.picklist(["google", "apple"]),
50
+ callbackURL: v.pipe(v.string(), v.url())
51
+ });
52
+ const cloudSocialLinkResponseSchema = v.object({ url: v.pipe(v.string(), v.url()) });
53
+ const cloudUnlinkAuthenticationMethodSchema = v.object({ methodId: v.string() });
54
+ const accountSecurityErrorCodeSchema = v.picklist([
55
+ "current_password_invalid",
56
+ "password_too_short",
57
+ "password_too_long",
58
+ "last_authentication_method",
59
+ "session_not_fresh",
60
+ "authentication_method_failed",
61
+ "email_unchanged",
62
+ "email_change_unavailable",
63
+ "current_session",
64
+ "picture_invalid"
65
+ ]);
66
+ const accountSecurityErrorResponseSchema = v.object({ error: v.object({ code: accountSecurityErrorCodeSchema }) });
67
+ const cloudMFAStatusSchema = v.object({
68
+ required: v.boolean(),
69
+ enabled: v.boolean(),
70
+ totpEnabled: v.boolean(),
71
+ assured: v.boolean(),
72
+ totpAvailable: v.boolean(),
73
+ passkeysAvailable: v.boolean(),
74
+ recoveryCodesAvailable: v.boolean()
75
+ });
76
+ const cloudMFAStatusResponseSchema = v.object({ mfa: cloudMFAStatusSchema });
77
+ const cloudMFAEnableSchema = v.object({ password: v.optional(v.string()) });
78
+ const cloudMFAEnableResponseSchema = v.object({
79
+ totpURI: v.string(),
80
+ backupCodes: v.array(v.string())
81
+ });
82
+ const cloudMFAVerifySchema = v.object({ code: v.pipe(v.string(), v.trim(), v.minLength(1)) });
83
+ const cloudMFAVerifyResponseSchema = v.object({ ok: v.literal(true) });
84
+ const cloudMFARecoveryCodesResponseSchema = v.object({ backupCodes: v.array(v.string()) });
85
+ const cloudPasskeySchema = v.object({
86
+ id: v.string(),
87
+ name: v.nullish(v.string()),
88
+ createdAt: v.string()
89
+ });
90
+ const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) });
91
+ const cloudPasskeyDeleteSchema = v.object({ id: v.string() });
92
+ function parseCloudMFAEnable(input) {
93
+ return v.parse(cloudMFAEnableSchema, input);
94
+ }
95
+ function parseCloudMFAVerify(input) {
96
+ return v.parse(cloudMFAVerifySchema, input);
97
+ }
98
+ function parseCloudPasskeyDelete(input) {
99
+ return v.parse(cloudPasskeyDeleteSchema, input);
100
+ }
101
+ function parseCloudPasswordChange(input) {
102
+ return v.parse(cloudPasswordChangeSchema, input);
103
+ }
104
+ function parseCloudSocialLink(input) {
105
+ return v.parse(cloudSocialLinkSchema, input);
106
+ }
107
+ function parseCloudUnlinkAuthenticationMethod(input) {
108
+ return v.parse(cloudUnlinkAuthenticationMethodSchema, input);
109
+ }
110
+ const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) });
111
+ /** Who an account belongs to, as the portal shows it. */
112
+ const cloudPersonSchema = v.object({
113
+ id: v.string(),
114
+ name: v.string(),
115
+ email: v.pipe(v.string(), v.email()),
116
+ /** The address of the account's picture, which the server serves; null shows initials. */
117
+ image: v.nullable(v.string())
118
+ });
119
+ /** What a person can see and change about themselves. */
120
+ const cloudProfileSchema = v.object({
121
+ ...cloudPersonSchema.entries,
122
+ createdAt: v.string(),
123
+ /** Whether the server can send the verification a new email address needs. */
124
+ emailChangeAvailable: v.boolean()
125
+ });
126
+ const cloudProfileResponseSchema = v.object({ profile: cloudProfileSchema });
127
+ const cloudProfileUpdateSchema = v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)) });
128
+ /** The largest picture an account may upload, once the page has cropped and shrunk it. */
129
+ const CLOUD_PICTURE_MAX_BYTES = 262144;
130
+ /** The width and height a page shrinks a picture to before it uploads it. */
131
+ const CLOUD_PICTURE_SIZE = 256;
132
+ const cloudPictureUploadSchema = v.object({
133
+ /** The picture's PNG or JPEG bytes, in Base64. */
134
+ data: v.pipe(v.string(), v.maxLength(Math.ceil(CLOUD_PICTURE_MAX_BYTES / 3) * 4), v.check((value) => isValid(value))) });
135
+ /** The address the account's picture is now served from. */
136
+ const cloudPictureResponseSchema = v.object({ image: v.string() });
137
+ const cloudEmailChangeSchema = v.object({
138
+ newEmail: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
139
+ callbackURL: v.pipe(v.string(), v.url())
140
+ });
141
+ /** How a sign-in was made: the method it used, or the desktop app's approved code. */
142
+ const cloudSignInMethodSchema = v.picklist([
143
+ "password",
144
+ "google",
145
+ "apple",
146
+ "passkey",
147
+ "two-step",
148
+ "email-link",
149
+ "desktop",
150
+ "other"
151
+ ]);
152
+ const cloudAccountSessionSchema = v.object({
153
+ id: v.string(),
154
+ /** The session this request was made with. */
155
+ current: v.boolean(),
156
+ method: v.nullable(cloudSignInMethodSchema),
157
+ ipAddress: v.nullable(v.string()),
158
+ /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
159
+ browser: v.nullable(v.string()),
160
+ system: v.nullable(v.string()),
161
+ createdAt: v.string(),
162
+ lastActiveAt: v.string(),
163
+ expiresAt: v.string()
164
+ });
165
+ const cloudAccountSessionsResponseSchema = v.object({ sessions: v.array(cloudAccountSessionSchema) });
166
+ const cloudSessionRevokeSchema = v.object({ sessionId: v.pipe(v.string(), v.minLength(1)) });
167
+ const cloudSignInSchema = v.object({
168
+ id: v.string(),
169
+ method: cloudSignInMethodSchema,
170
+ ipAddress: v.nullable(v.string()),
171
+ /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
172
+ browser: v.nullable(v.string()),
173
+ system: v.nullable(v.string()),
174
+ createdAt: v.string()
175
+ });
176
+ const cloudSignInsResponseSchema = v.object({ signIns: v.array(cloudSignInSchema) });
177
+ function parseCloudProfileUpdate(input) {
178
+ return v.parse(cloudProfileUpdateSchema, input);
179
+ }
180
+ function parseCloudPictureUpload(input) {
181
+ return v.parse(cloudPictureUploadSchema, input);
182
+ }
183
+ function parseCloudEmailChange(input) {
184
+ return v.parse(cloudEmailChangeSchema, input);
185
+ }
186
+ function parseCloudSessionRevoke(input) {
187
+ return v.parse(cloudSessionRevokeSchema, input);
188
+ }
189
+ //#endregion
190
+ //#region src/contract/ai.ts
191
+ /**
192
+ * The contract between editors, Cloud, and an AI service. Cloud only advertises the service and
193
+ * signs short-lived tokens for it; the service, official or self-hosted, proxies models and keeps
194
+ * the credit wallet. It is versioned apart from the Cloud protocol so a service can change without
195
+ * a Cloud release.
196
+ */
197
+ const CLOUD_AI_CONTRACT_VERSION = "1";
198
+ /** The `aud` of every token Cloud signs for an AI service. */
199
+ const CLOUD_AI_TOKEN_AUDIENCE = "pairdraw-ai";
200
+ /** Where Cloud publishes the public keys an AI service verifies its tokens with. */
201
+ const CLOUD_AI_JWKS_PATH = "/.well-known/jwks.json";
202
+ /**
203
+ * Where a service answers, below the discovered `endpoint`. Model requests follow the OpenAI chat
204
+ * completions API, so an OpenAI-compatible client takes `${endpoint}${base}` as its base URL.
205
+ */
206
+ const CLOUD_AI_API_PATHS = {
207
+ base: "/v1",
208
+ chatCompletions: "/v1/chat/completions",
209
+ catalog: "/v1/catalog",
210
+ wallet: "/v1/wallet",
211
+ usage: "/v1/usage"
212
+ };
213
+ const urlSchema = v.pipe(v.string(), v.url());
214
+ const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
215
+ const cloudAIDiscoverySchema = v.object({
216
+ endpoint: urlSchema,
217
+ contractVersion: v.literal("1")
218
+ });
219
+ const cloudBillingDiscoverySchema = v.object({ portalURL: urlSchema });
220
+ const createAITokenSchema = v.object({ workspaceId: v.pipe(v.string(), v.uuid()) });
221
+ function parseCreateAIToken(input) {
222
+ return v.parse(createAITokenSchema, input);
223
+ }
224
+ const aiTokenSchema = v.object({
225
+ token: v.pipe(v.string(), v.minLength(1)),
226
+ expiresAt: v.pipe(v.string(), v.isoTimestamp())
227
+ });
228
+ /** What an AI service may rely on once a token's signature, issuer, audience, and expiry check. */
229
+ const aiTokenClaimsSchema = v.object({
230
+ iss: urlSchema,
231
+ aud: v.literal(CLOUD_AI_TOKEN_AUDIENCE),
232
+ sub: v.pipe(v.string(), v.minLength(1)),
233
+ workspaceId: v.pipe(v.string(), v.uuid()),
234
+ /** Credits the workspace's plan grants each month; `null` when Cloud sets no allowance. */
235
+ monthlyCreditAllowance: v.nullable(creditsSchema),
236
+ iat: v.pipe(v.number(), v.integer()),
237
+ exp: v.pipe(v.number(), v.integer())
238
+ });
239
+ const aiModelSchema = v.object({
240
+ id: v.pipe(v.string(), v.minLength(1)),
241
+ label: v.pipe(v.string(), v.minLength(1)),
242
+ /** Credits per million input and output tokens. */
243
+ creditsPerMillionInputTokens: creditsSchema,
244
+ creditsPerMillionOutputTokens: creditsSchema,
245
+ contextTokens: v.pipe(v.number(), v.integer(), v.minValue(1)),
246
+ capabilities: v.object({
247
+ reasoning: v.boolean(),
248
+ vision: v.boolean(),
249
+ tools: v.boolean()
250
+ })
251
+ });
252
+ const aiCatalogSchema = v.object({
253
+ models: v.array(aiModelSchema),
254
+ defaultModelID: v.pipe(v.string(), v.minLength(1))
255
+ });
256
+ const aiCreditBucketSchema = v.object({
257
+ kind: v.picklist([
258
+ "allowance",
259
+ "purchased",
260
+ "grant"
261
+ ]),
262
+ remaining: creditsSchema,
263
+ expiresAt: v.nullable(v.pipe(v.string(), v.isoTimestamp()))
264
+ });
265
+ /**
266
+ * A service records a request's charge before the request's answer ends, so a wallet read after
267
+ * an answer includes what it cost.
268
+ */
269
+ const aiWalletSchema = v.object({
270
+ /** Credits left to spend; `null` when the service sets no limit. */
271
+ balance: v.nullable(creditsSchema),
272
+ /** Spent first to last. */
273
+ buckets: v.array(aiCreditBucketSchema)
274
+ });
275
+ const aiUsageEntrySchema = v.object({
276
+ id: v.pipe(v.string(), v.minLength(1)),
277
+ createdAt: v.pipe(v.string(), v.isoTimestamp()),
278
+ kind: v.picklist([
279
+ "model",
280
+ "image",
281
+ "search"
282
+ ]),
283
+ modelID: v.nullable(v.string()),
284
+ userId: v.pipe(v.string(), v.minLength(1)),
285
+ credits: creditsSchema
286
+ });
287
+ const aiUsageQuerySchema = v.object({ cursor: v.optional(v.pipe(v.string(), v.minLength(1))) });
288
+ function parseAIUsageQuery(input) {
289
+ return v.parse(aiUsageQuerySchema, input);
290
+ }
291
+ const aiUsagePageSchema = v.object({
292
+ entries: v.array(aiUsageEntrySchema),
293
+ next: v.nullable(v.string())
294
+ });
295
+ /** Errors an AI service answers with, beside the upstream model's own. */
296
+ const aiErrorCodeSchema = v.picklist([
297
+ "unauthorized",
298
+ "insufficient_credits",
299
+ "model_not_allowed",
300
+ "rate_limited"
301
+ ]);
302
+ const aiErrorSchema = v.object({ error: v.object({
303
+ code: aiErrorCodeSchema,
304
+ message: v.optional(v.string()),
305
+ /** With `insufficient_credits`: when the workspace's allowance renews, if the service knows. */
306
+ resetsAt: v.optional(v.pipe(v.string(), v.isoTimestamp()))
307
+ }) });
308
+ const AI_ERROR_STATUS = {
309
+ unauthorized: 401,
310
+ insufficient_credits: 402,
311
+ model_not_allowed: 403,
312
+ rate_limited: 429
313
+ };
314
+ //#endregion
315
+ //#region src/contract/workspaces.ts
316
+ const workspaceRoleSchema = v.picklist([
317
+ "viewer",
318
+ "editor",
319
+ "admin"
320
+ ]);
321
+ const workspaceSummarySchema = v.object({
322
+ id: v.pipe(v.string(), v.uuid()),
323
+ name: v.string(),
324
+ slug: v.string(),
325
+ role: workspaceRoleSchema,
326
+ createdAt: v.string(),
327
+ updatedAt: v.string()
328
+ });
329
+ const createWorkspaceSchema = v.object({
330
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)),
331
+ slug: v.optional(v.pipe(v.string(), v.trim(), v.minLength(3), v.maxLength(63), v.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)))
332
+ });
333
+ const workspaceListSchema = v.object({ workspaces: v.array(workspaceSummarySchema) });
334
+ const updateWorkspaceSchema = v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)) });
335
+ /** Someone who belongs to a workspace, and what they may do in it. */
336
+ const workspaceMemberSchema = v.object({
337
+ userId: v.string(),
338
+ name: v.string(),
339
+ email: v.string(),
340
+ image: v.nullable(v.string()),
341
+ role: workspaceRoleSchema,
342
+ joinedAt: v.string()
343
+ });
344
+ /** An invitation to join a workspace that has not been accepted yet. */
345
+ const workspaceInvitationSchema = v.object({
346
+ id: v.pipe(v.string(), v.uuid()),
347
+ email: v.string(),
348
+ role: workspaceRoleSchema,
349
+ /** Who sent it; the name is null once their account is gone. */
350
+ invitedBy: v.object({
351
+ id: v.string(),
352
+ name: v.nullable(v.string())
353
+ }),
354
+ invitedAt: v.string(),
355
+ expiresAt: v.string()
356
+ });
357
+ const workspaceMembersSchema = v.object({
358
+ members: v.array(workspaceMemberSchema),
359
+ /** Only administrators see pending invitations. */
360
+ invitations: v.array(workspaceInvitationSchema)
361
+ });
362
+ const createWorkspaceInvitationSchema = v.object({
363
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
364
+ role: workspaceRoleSchema
365
+ });
366
+ /** A new invitation and its link, for an administrator to pass on when email is off. */
367
+ const createdWorkspaceInvitationSchema = v.object({
368
+ invitation: workspaceInvitationSchema,
369
+ acceptanceURL: v.string()
370
+ });
371
+ const updateWorkspaceMemberSchema = v.object({ role: workspaceRoleSchema });
372
+ function parseCreateWorkspace(input) {
373
+ return v.parse(createWorkspaceSchema, input);
374
+ }
375
+ function parseUpdateWorkspace(input) {
376
+ return v.parse(updateWorkspaceSchema, input);
377
+ }
378
+ function parseCreateWorkspaceInvitation(input) {
379
+ return v.parse(createWorkspaceInvitationSchema, input);
380
+ }
381
+ function parseUpdateWorkspaceMember(input) {
382
+ return v.parse(updateWorkspaceMemberSchema, input);
383
+ }
384
+ //#endregion
385
+ //#region src/contract/admin/index.ts
386
+ const timestampSchema = v.pipe(v.string(), v.isoTimestamp());
387
+ const nullableTimestampSchema = v.nullable(timestampSchema);
388
+ const countSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
389
+ /**
390
+ * What every admin list answers besides its rows: how many rows match the search and filter
391
+ * across every page, and how many match the search under each filter.
392
+ */
393
+ function listTotals(filters) {
394
+ return {
395
+ total: countSchema,
396
+ counts: v.object(zipObject(filters, filters.map(() => countSchema)))
397
+ };
398
+ }
399
+ const adminErrorCodeSchema = v.picklist([
400
+ "bad_request",
401
+ "unauthorized",
402
+ "forbidden",
403
+ "not_found",
404
+ "rate_limited",
405
+ "invalid_enrollment_transition",
406
+ "last_admin_required",
407
+ "self_admin_action_forbidden",
408
+ "email_regeneration_unavailable",
409
+ "mfa_required"
410
+ ]);
411
+ const adminErrorResponseSchema = v.object({ error: v.object({ code: adminErrorCodeSchema }) });
412
+ const enrollmentStatusSchema = v.picklist([
413
+ "pending",
414
+ "approved",
415
+ "rejected",
416
+ "revoked"
417
+ ]);
418
+ const enrollmentSchema = v.object({
419
+ id: v.string(),
420
+ email: v.pipe(v.string(), v.email()),
421
+ name: v.nullable(v.string()),
422
+ reason: v.nullable(v.string()),
423
+ status: enrollmentStatusSchema,
424
+ requestedAt: timestampSchema,
425
+ reviewedAt: nullableTimestampSchema,
426
+ reviewedBy: v.nullable(v.string()),
427
+ /** The reviewer's name, in lists, while the server still knows them. */
428
+ reviewerName: v.optional(v.nullable(v.string())),
429
+ reviewNote: v.nullable(v.string()),
430
+ approvedUserId: v.nullable(v.string()),
431
+ requestRevision: v.pipe(v.number(), v.integer(), v.minValue(1))
432
+ });
433
+ const enrollmentsResponseSchema = v.object({
434
+ enrollments: v.array(enrollmentSchema),
435
+ ...listTotals(enrollmentStatusSchema.options)
436
+ });
437
+ const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSchema });
438
+ const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema });
439
+ const cloudAdminUserSchema = v.object({
440
+ ...cloudPersonSchema.entries,
441
+ role: v.optional(v.string()),
442
+ banned: v.nullable(v.boolean()),
443
+ banReason: v.optional(v.nullable(v.string())),
444
+ createdAt: timestampSchema,
445
+ /** An authenticator app or a passkey confirms this account's sign-ins. */
446
+ twoStep: v.boolean(),
447
+ /** When one of the account's sessions was last used, or null when none is left. */
448
+ lastActiveAt: nullableTimestampSchema,
449
+ workspaceCount: countSchema
450
+ });
451
+ /** Which accounts a list of people shows. */
452
+ const cloudAdminUserFilterSchema = v.picklist([
453
+ "all",
454
+ "administrators",
455
+ "suspended",
456
+ "without-two-step"
457
+ ]);
458
+ const cloudAdminUsersResponseSchema = v.object({
459
+ users: v.array(cloudAdminUserSchema),
460
+ ...listTotals(cloudAdminUserFilterSchema.options)
461
+ });
462
+ const cloudAdminUserDetailSchema = v.object({
463
+ user: v.object({
464
+ ...cloudAdminUserSchema.entries,
465
+ emailVerified: v.boolean()
466
+ }),
467
+ methods: v.array(v.object({
468
+ provider: v.string(),
469
+ createdAt: timestampSchema
470
+ })),
471
+ authenticator: v.boolean(),
472
+ passkeyCount: countSchema,
473
+ sessions: v.array(cloudAccountSessionSchema),
474
+ signIns: v.array(cloudSignInSchema),
475
+ workspaces: v.array(v.object({
476
+ id: v.string(),
477
+ name: v.string(),
478
+ role: workspaceRoleSchema,
479
+ memberCount: countSchema,
480
+ joinedAt: timestampSchema
481
+ }))
482
+ });
483
+ const adminMutationResponseSchema = v.object({ ok: v.literal(true) });
484
+ const transactionalEmailAdminSchema = v.object({
485
+ id: v.string(),
486
+ kind: v.string(),
487
+ recipientEmailNormalized: v.pipe(v.string(), v.email()),
488
+ status: v.string(),
489
+ attemptCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
490
+ nextAttemptAt: timestampSchema,
491
+ transport: v.nullable(v.string()),
492
+ transportMessageId: v.nullable(v.string()),
493
+ lastErrorCode: v.nullable(v.string()),
494
+ createdAt: timestampSchema,
495
+ acceptedAt: nullableTimestampSchema,
496
+ regeneratable: v.boolean()
497
+ });
498
+ /** Which messages a list of email shows, by how their delivery went. */
499
+ const cloudAdminEmailFilterSchema = v.picklist([
500
+ "all",
501
+ "sent",
502
+ "waiting",
503
+ "failed"
504
+ ]);
505
+ const adminEmailResponseSchema = v.object({
506
+ messages: v.array(transactionalEmailAdminSchema),
507
+ ...listTotals(cloudAdminEmailFilterSchema.options)
508
+ });
509
+ /** Who or what an event names; `name` is null once the server no longer knows it. */
510
+ const auditPartySchema = v.object({
511
+ id: v.string(),
512
+ name: v.nullable(v.string())
513
+ });
514
+ const adminAuditEventSchema = v.object({
515
+ id: v.string(),
516
+ actor: auditPartySchema,
517
+ action: v.string(),
518
+ /** What the event is about: an account, an access request, or an email. */
519
+ subject: v.object({
520
+ ...auditPartySchema.entries,
521
+ type: v.string()
522
+ }),
523
+ metadata: v.unknown(),
524
+ createdAt: timestampSchema
525
+ });
526
+ /** Which events a list of activity shows, by what they are about. */
527
+ const cloudAdminAuditFilterSchema = v.picklist([
528
+ "all",
529
+ "accounts",
530
+ "requests",
531
+ "email"
532
+ ]);
533
+ const adminAuditResponseSchema = v.object({
534
+ events: v.array(adminAuditEventSchema),
535
+ ...listTotals(cloudAdminAuditFilterSchema.options)
536
+ });
537
+ const adminOperationsResponseSchema = v.object({
538
+ deployment: v.picklist(["official", "self-hosted"]),
539
+ enrollmentMode: v.picklist([
540
+ "open",
541
+ "approval",
542
+ "closed"
543
+ ]),
544
+ emailTransport: v.picklist([
545
+ "none",
546
+ "smtp",
547
+ "cloudflare"
548
+ ]),
549
+ pendingEnrollment: v.pipe(v.number(), v.integer(), v.minValue(0)),
550
+ pendingEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
551
+ failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
552
+ accounts: countSchema,
553
+ workspaces: countSchema,
554
+ documents: countSchema,
555
+ storedBytes: countSchema
556
+ });
557
+ //#endregion
558
+ //#region src/contract/documents.ts
559
+ const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1073741824;
560
+ const checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/));
561
+ /** Whether a value is a SHA-256 checksum as the server names stored objects, base64 encoded. */
562
+ function isCloudChecksum(value) {
563
+ return v.is(checksumSchema, value);
564
+ }
565
+ /** The most images one revision, or one request for image uploads, may name. */
566
+ const CLOUD_MAX_DOCUMENT_IMAGES = 1e4;
567
+ /**
568
+ * An image's name inside a `.fig` file that Cloud stores apart from it: the SHA-1 Figma names it
569
+ * by, or an older plain name. A client leaves images under other names inside the file.
570
+ */
571
+ const CLOUD_IMAGE_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
572
+ const imageNameSchema = v.pipe(v.string(), v.regex(CLOUD_IMAGE_NAME_PATTERN));
573
+ const objectDownloadSchema = v.object({
574
+ url: v.pipe(v.string(), v.url()),
575
+ method: v.literal("GET"),
576
+ headers: v.record(v.string(), v.string()),
577
+ expiresAt: v.string()
578
+ });
579
+ /** An image a stored revision uses, where to download it, and what to check it against. */
580
+ const documentImageDownloadSchema = v.object({
581
+ name: imageNameSchema,
582
+ checksum: checksumSchema,
583
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
584
+ download: objectDownloadSchema
585
+ });
586
+ /** Where to download an image a document uses, found by its checksum. */
587
+ const documentImageLinkSchema = v.object({
588
+ checksum: checksumSchema,
589
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
590
+ download: objectDownloadSchema
591
+ });
592
+ /** The images a live room names, by checksum, that a peer needs links for. */
593
+ const requestImageLinksSchema = v.object({ checksums: v.pipe(v.array(checksumSchema), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
594
+ /**
595
+ * What someone may do with a document: look at it, look at it and comment, or edit it. Commenters
596
+ * join its room read-only and send comments through the relay's comment channel.
597
+ */
598
+ const DOCUMENT_PERMISSIONS = [
599
+ "view",
600
+ "comment",
601
+ "edit"
602
+ ];
603
+ const documentPermissionSchema = v.picklist(DOCUMENT_PERMISSIONS);
604
+ const documentAccessSourceSchema = v.picklist([
605
+ "owner",
606
+ "workspace",
607
+ "direct-grant"
608
+ ]);
609
+ const documentAccessSchema = v.object({
610
+ permission: documentPermissionSchema,
611
+ canManageSharing: v.boolean(),
612
+ sources: v.array(documentAccessSourceSchema),
613
+ /**
614
+ * The revision the document holds now, null before its first save; servers from before snapshot
615
+ * links leave it out.
616
+ */
617
+ currentRevisionId: v.optional(v.nullable(v.pipe(v.string(), v.uuid())))
618
+ });
619
+ const documentSummarySchema = v.object({
620
+ id: v.pipe(v.string(), v.uuid()),
621
+ workspaceId: v.pipe(v.string(), v.uuid()),
622
+ name: v.string(),
623
+ currentRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
624
+ version: v.number(),
625
+ createdAt: v.string(),
626
+ updatedAt: v.string()
627
+ });
628
+ /** A document someone granted the person directly, in a workspace they are not a member of. */
629
+ const sharedDocumentSchema = v.object({
630
+ ...documentSummarySchema.entries,
631
+ workspaceName: v.string(),
632
+ permission: documentPermissionSchema,
633
+ sharedBy: v.nullable(v.object({ name: v.string() })),
634
+ sharedAt: v.string()
635
+ });
636
+ const documentDownloadSchema = v.object({
637
+ document: documentSummarySchema,
638
+ revisionId: v.pipe(v.string(), v.uuid()),
639
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
640
+ checksum: checksumSchema,
641
+ contentType: v.string(),
642
+ download: objectDownloadSchema,
643
+ /** The images the stored file leaves out, which a client puts back under their names. */
644
+ images: v.pipe(v.array(documentImageDownloadSchema), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES))
645
+ });
646
+ const cloudActorSchema = v.object({
647
+ userId: v.string(),
648
+ email: v.pipe(v.string(), v.email()),
649
+ name: v.string()
650
+ });
651
+ const cloudSessionSchema = v.object({ user: cloudActorSchema });
652
+ const workspaceUsageSchema = v.object({
653
+ bytesUsed: v.pipe(v.number(), v.integer(), v.minValue(0)),
654
+ objectCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
655
+ documentCount: v.pipe(v.number(), v.integer(), v.minValue(0))
656
+ });
657
+ const CLOUD_DOCUMENT_NAME_MAX_LENGTH = 255;
658
+ const createDocumentSchema = v.object({
659
+ id: v.optional(v.pipe(v.string(), v.uuid())),
660
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255))
661
+ });
662
+ const createUploadSchema = v.object({
663
+ baseRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
664
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)),
665
+ checksum: checksumSchema,
666
+ contentType: v.literal("application/octet-stream")
667
+ });
668
+ const imageSizeSchema = v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES));
669
+ /** Where a client puts an object: one presigned PUT, or the parts of a multipart upload. */
670
+ const objectUploadSchema = v.variant("kind", [v.object({
671
+ kind: v.literal("single"),
672
+ url: v.pipe(v.string(), v.url()),
673
+ method: v.literal("PUT"),
674
+ headers: v.record(v.string(), v.string()),
675
+ expiresAt: v.string()
676
+ }), v.object({
677
+ kind: v.literal("multipart"),
678
+ uploadId: v.string(),
679
+ partSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
680
+ parts: v.array(v.object({
681
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1)),
682
+ url: v.pipe(v.string(), v.url()),
683
+ method: v.literal("PUT"),
684
+ headers: v.record(v.string(), v.string())
685
+ })),
686
+ expiresAt: v.string()
687
+ })]);
688
+ /** An upload the server offers for an image the workspace lacks. */
689
+ const imageUploadOfferSchema = v.object({
690
+ checksum: checksumSchema,
691
+ uploadId: v.pipe(v.string(), v.uuid()),
692
+ upload: objectUploadSchema
693
+ });
694
+ /** The images a save will refer to; the server answers with uploads for those it lacks. */
695
+ const requestImageUploadsSchema = v.object({ images: v.pipe(v.array(v.object({
696
+ checksum: checksumSchema,
697
+ byteSize: imageSizeSchema
698
+ })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
699
+ const completedUploadPartSchema = v.object({
700
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1e4)),
701
+ etag: v.pipe(v.string(), v.minLength(1), v.maxLength(255))
702
+ });
703
+ const commitUploadSchema = v.object({
704
+ checksum: checksumSchema,
705
+ /** The document title captured with this revision; omitted by older clients. */
706
+ name: v.optional(createDocumentSchema.entries.name),
707
+ multipart: v.optional(v.object({
708
+ uploadId: v.pipe(v.string(), v.minLength(1)),
709
+ parts: v.pipe(v.array(completedUploadPartSchema), v.minLength(1), v.maxLength(1e4))
710
+ })),
711
+ /** The images the uploaded file leaves out, each stored in the workspace or uploaded before. */
712
+ images: v.optional(v.pipe(v.array(v.object({
713
+ name: imageNameSchema,
714
+ checksum: checksumSchema
715
+ })), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)), [])
716
+ });
717
+ /** The image uploads a save asked for, committed together once their bytes are in place. */
718
+ const commitImageUploadsSchema = v.object({ uploads: v.pipe(v.array(v.object({
719
+ uploadId: v.pipe(v.string(), v.uuid()),
720
+ checksum: checksumSchema,
721
+ multipart: commitUploadSchema.entries.multipart
722
+ })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
723
+ function parseCreateDocument(input) {
724
+ return v.parse(createDocumentSchema, input);
725
+ }
726
+ function parseCreateUpload(input) {
727
+ return v.parse(createUploadSchema, input);
728
+ }
729
+ function parseRequestImageUploads(input) {
730
+ return v.parse(requestImageUploadsSchema, input);
731
+ }
732
+ function parseCommitImageUploads(input) {
733
+ return v.parse(commitImageUploadsSchema, input);
734
+ }
735
+ function parseRequestImageLinks(input) {
736
+ return v.parse(requestImageLinksSchema, input);
737
+ }
738
+ function parseCommitUpload(input) {
739
+ return v.parse(commitUploadSchema, input);
740
+ }
741
+ //#endregion
742
+ //#region src/contract/collaboration.ts
743
+ const collaborationPrincipalSchema = v.variant("kind", [v.object({
744
+ kind: v.literal("user"),
745
+ userId: v.string(),
746
+ name: v.string(),
747
+ email: v.pipe(v.string(), v.email())
748
+ }), v.object({
749
+ kind: v.literal("guest"),
750
+ guestId: v.string(),
751
+ name: v.string()
752
+ })]);
753
+ /**
754
+ * Who the relay verified a peer to be, as it writes into that peer's presence under `cloud`, so
755
+ * other peers can trust it over what the peer says of itself.
756
+ */
757
+ const cloudPresenceSchema = v.object({
758
+ kind: v.picklist(["user", "guest"]),
759
+ id: v.string(),
760
+ name: v.string(),
761
+ permission: documentPermissionSchema
762
+ });
763
+ const collaborationTicketSchema = v.object({
764
+ token: v.string(),
765
+ provider: v.optional(v.picklist(["trystero", "relay"])),
766
+ serverURL: v.optional(v.pipe(v.string(), v.url())),
767
+ documentId: v.pipe(v.string(), v.uuid()),
768
+ roomId: v.string(),
769
+ roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),
770
+ principal: collaborationPrincipalSchema,
771
+ permission: documentPermissionSchema,
772
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
773
+ expiresAt: v.string(),
774
+ serverEnforcedWrites: v.boolean()
775
+ });
776
+ //#endregion
777
+ //#region src/contract/relay.ts
778
+ /** Where the relay accepts WebSocket upgrades, under the Cloud API origin. */
779
+ const RELAY_PATH = "/api/collaboration/relay";
780
+ /**
781
+ * The relay URL's query parameter naming the ticket's document, so a runtime that keeps each
782
+ * document's room in its own place can route the socket there before the ticket arrives.
783
+ */
784
+ const RELAY_DOCUMENT_PARAM = "document";
785
+ /** The relay's public URL on the same origin as the API, unless the deployment names another. */
786
+ function defaultRelayURL(publicURL) {
787
+ const url = new URL(RELAY_PATH, publicURL);
788
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
789
+ return url.href;
790
+ }
791
+ /**
792
+ * The room messages collaboration sends. The relay reads the document ones to keep its copy,
793
+ * persist it, and drop writes from viewers; it forwards the rest unread.
794
+ */
795
+ const COLLAB_ACTIONS = {
796
+ yjsUpdate: "yjs-update",
797
+ syncStep1: "sync-step1",
798
+ syncReply: "sync-reply",
799
+ awareness: "awareness",
800
+ agentPreview: "agent-preview",
801
+ upload: "upload",
802
+ /** A commenter's comment threads, which the relay checks and writes into the room itself. */
803
+ comments: "comments",
804
+ /** From the server only: the document's version history changed, so open lists load it again. */
805
+ versions: "versions"
806
+ };
807
+ /**
808
+ * The most a room message may decode to, compressed or not. A peer's update past it is dropped
809
+ * before it is decoded, so a small compressed reply cannot expand without bound.
810
+ */
811
+ const MAX_COLLAB_MESSAGE_BYTES = 268435456;
812
+ /**
813
+ * What a peer joining needs is the whole document, which repeats the same field names across
814
+ * every layer, so the reply to its state vector travels compressed; Yjs's V2 encoding already
815
+ * groups that repetition, and together they make a room's first sync about a twelfth the size.
816
+ * Edits travel as V2 updates uncompressed: they are small, and arrive in a stream.
817
+ */
818
+ function encodeSyncReply(document, stateVector) {
819
+ return deflateSync(Y.encodeStateAsUpdateV2(document, stateVector));
820
+ }
821
+ /**
822
+ * Compressed input is inflated this much at a time, so a reply stops within a step of passing
823
+ * the limit: deflate expands at most about 1,032 times, so a step can overshoot by about 16 MB.
824
+ */
825
+ const INFLATE_STEP = 16384;
826
+ /**
827
+ * The V2 update a peer sent, inflated first when `compressed`, as a sync reply is; null once it
828
+ * would decode past `limit` bytes. Throws on data that does not inflate.
829
+ */
830
+ function decodeRoomUpdate(data, { limit, compressed = false }) {
831
+ if (!compressed) return data.length <= limit ? data : null;
832
+ const chunks = [];
833
+ let size = 0;
834
+ const inflate = new Inflate((chunk) => {
835
+ size += chunk.length;
836
+ if (size <= limit) chunks.push(chunk);
837
+ });
838
+ for (let offset = 0; offset < data.length; offset += INFLATE_STEP) {
839
+ inflate.push(data.subarray(offset, offset + INFLATE_STEP), offset + INFLATE_STEP >= data.length);
840
+ if (size > limit) return null;
841
+ }
842
+ const inflated = new Uint8Array(size);
843
+ let at = 0;
844
+ for (const chunk of chunks) {
845
+ inflated.set(chunk, at);
846
+ at += chunk.length;
847
+ }
848
+ return inflated;
849
+ }
850
+ /** The peer ID the relay itself uses: it holds the room's document and answers sync requests. */
851
+ const RELAY_SERVER_PEER = "server";
852
+ /** The longest name a peer's presence may carry; peers drop presence with a longer one. */
853
+ const MAX_PRESENCE_NAME_LENGTH = 40;
854
+ /** A name as presence carries it: trimmed and cut to what every peer accepts. */
855
+ function presenceName(name) {
856
+ return name.trim().slice(0, 40);
857
+ }
858
+ /**
859
+ * Close codes in the WebSocket application range. A client reconnects with a fresh ticket after
860
+ * `expired`, and gives up on the others.
861
+ */
862
+ const RELAY_CLOSE = {
863
+ unauthorized: 4401,
864
+ expired: 4403,
865
+ roomFull: 4409,
866
+ messageTooLarge: 4413,
867
+ protocol: 4400,
868
+ /** The document was restored to a version, so its room started over under a new ID. */
869
+ restored: 4410
870
+ };
871
+ const CLIENT_AUTH = 0;
872
+ const CLIENT_MESSAGE = 1;
873
+ const CLIENT_FRAGMENT = 2;
874
+ const SERVER_WELCOME = 0;
875
+ const SERVER_JOIN = 1;
876
+ const SERVER_LEAVE = 2;
877
+ const SERVER_MESSAGE = 3;
878
+ const SERVER_FRAGMENT = 4;
879
+ /**
880
+ * The most one WebSocket message carries. A frame past it travels as fragments of this size that
881
+ * the receiver joins again, so a large paste or a room's first sync fits under any host's message
882
+ * cap, such as the 32 MiB of Cloudflare Workers, and the relay can turn away a viewer's or an
883
+ * unadmitted peer's large frame before holding it whole.
884
+ */
885
+ const RELAY_FRAGMENT_BYTES = 262144;
886
+ /** The smallest per-message limit a relay may set: one fragment and its few bytes of framing. */
887
+ const RELAY_MINIMUM_MESSAGE_BYTES = 262160;
888
+ /**
889
+ * What the relay adds to a frame it forwards: the frame type, the sender's peer ID, and lengths.
890
+ * A client reads frames this much past the relay's own limit, so a forwarded edit at that limit
891
+ * still arrives.
892
+ */
893
+ const RELAY_FORWARDING_BYTES = 65536;
894
+ /** Encodes into a buffer of its own, which `WebSocket.send` accepts. */
895
+ function toSendable(write) {
896
+ return new Uint8Array(encoding.encode(write));
897
+ }
898
+ function encodeRelayClientFrame(frame) {
899
+ return toSendable((encoder) => {
900
+ if (frame.type === "auth") {
901
+ encoding.writeVarUint(encoder, CLIENT_AUTH);
902
+ encoding.writeVarString(encoder, frame.token);
903
+ return;
904
+ }
905
+ encoding.writeVarUint(encoder, CLIENT_MESSAGE);
906
+ encoding.writeVarString(encoder, frame.namespace);
907
+ encoding.writeVarString(encoder, frame.target ?? "");
908
+ encoding.writeVarUint8Array(encoder, frame.payload);
909
+ });
910
+ }
911
+ function encodeRelayServerFrame(frame) {
912
+ return toSendable((encoder) => {
913
+ switch (frame.type) {
914
+ case "welcome":
915
+ encoding.writeVarUint(encoder, SERVER_WELCOME);
916
+ encoding.writeVarString(encoder, frame.peerId);
917
+ encoding.writeVarUint(encoder, frame.peers.length);
918
+ for (const peer of frame.peers) encoding.writeVarString(encoder, peer);
919
+ return;
920
+ case "join":
921
+ case "leave":
922
+ encoding.writeVarUint(encoder, frame.type === "join" ? SERVER_JOIN : SERVER_LEAVE);
923
+ encoding.writeVarString(encoder, frame.peerId);
924
+ return;
925
+ case "message":
926
+ encoding.writeVarUint(encoder, SERVER_MESSAGE);
927
+ encoding.writeVarString(encoder, frame.namespace);
928
+ encoding.writeVarString(encoder, frame.from);
929
+ encoding.writeVarUint8Array(encoder, frame.payload);
930
+ }
931
+ });
932
+ }
933
+ /** The frame as it goes over the socket: itself, or fragments of it when it is large. */
934
+ function fragments(tag, frame) {
935
+ if (frame.byteLength <= 262144) return [frame];
936
+ const parts = [];
937
+ for (let offset = 0; offset < frame.byteLength; offset += RELAY_FRAGMENT_BYTES) {
938
+ const end = Math.min(offset + RELAY_FRAGMENT_BYTES, frame.byteLength);
939
+ parts.push(toSendable((encoder) => {
940
+ encoding.writeVarUint(encoder, tag);
941
+ encoding.writeVarUint(encoder, end < frame.byteLength ? 1 : 0);
942
+ encoding.writeVarUint8Array(encoder, frame.subarray(offset, end));
943
+ }));
944
+ }
945
+ return parts;
946
+ }
947
+ /** A client frame as the socket messages that carry it, in order. */
948
+ function relayClientMessages(frame) {
949
+ return fragments(CLIENT_FRAGMENT, encodeRelayClientFrame(frame));
950
+ }
951
+ /** A server frame as the socket messages that carry it, in order. */
952
+ function relayServerMessages(frame) {
953
+ return fragments(SERVER_FRAGMENT, encodeRelayServerFrame(frame));
954
+ }
955
+ /**
956
+ * Joins one socket's fragments into the frames they carry. A socket sends a frame's fragments in
957
+ * a row, so a whole frame arriving between them is malformed. `limit` caps the joined frame and is
958
+ * read for every message, so it can follow what the sender may do.
959
+ */
960
+ function createAssembler(tag, limit) {
961
+ let parts = [];
962
+ let size = 0;
963
+ /** Set while the rest of a refused frame arrives, so its tail never reads as a frame of its own. */
964
+ let discarding = false;
965
+ const reset = () => {
966
+ parts = [];
967
+ size = 0;
968
+ };
969
+ return { push(data) {
970
+ let decoder;
971
+ let type;
972
+ try {
973
+ decoder = decoding.createDecoder(data);
974
+ type = decoding.readVarUint(decoder);
975
+ } catch {
976
+ reset();
977
+ return { type: "malformed" };
978
+ }
979
+ if (type !== tag) {
980
+ if (parts.length > 0) {
981
+ reset();
982
+ return { type: "malformed" };
983
+ }
984
+ return {
985
+ type: "frame",
986
+ data
987
+ };
988
+ }
989
+ let more;
990
+ let chunk;
991
+ try {
992
+ more = decoding.readVarUint(decoder);
993
+ chunk = decoding.readVarUint8Array(decoder);
994
+ } catch {
995
+ reset();
996
+ discarding = true;
997
+ return { type: "malformed" };
998
+ }
999
+ if (decoder.pos !== data.byteLength || more > 1) {
1000
+ reset();
1001
+ discarding = more !== 0;
1002
+ return { type: "malformed" };
1003
+ }
1004
+ if (discarding) {
1005
+ discarding = more === 1;
1006
+ return { type: "partial" };
1007
+ }
1008
+ size += chunk.byteLength;
1009
+ if (size > limit()) {
1010
+ reset();
1011
+ discarding = more === 1;
1012
+ return { type: "too-large" };
1013
+ }
1014
+ parts.push(chunk.slice());
1015
+ if (more === 1) return { type: "partial" };
1016
+ const joined = new Uint8Array(size);
1017
+ let at = 0;
1018
+ for (const part of parts) {
1019
+ joined.set(part, at);
1020
+ at += part.byteLength;
1021
+ }
1022
+ reset();
1023
+ return {
1024
+ type: "frame",
1025
+ data: joined
1026
+ };
1027
+ } };
1028
+ }
1029
+ /** Joins the fragments a client sends; the relay holds one per socket. */
1030
+ function createRelayClientAssembler(limit) {
1031
+ return createAssembler(CLIENT_FRAGMENT, limit);
1032
+ }
1033
+ /** Joins the fragments the relay sends; a client holds one per socket. */
1034
+ function createRelayServerAssembler(limit) {
1035
+ return createAssembler(SERVER_FRAGMENT, limit);
1036
+ }
1037
+ /**
1038
+ * lib0 reads byte arrays as views of the underlying buffer, which can run past the end of the
1039
+ * frame's own view, as with pooled socket buffers. A frame is valid only when decoding consumed
1040
+ * exactly its bytes, and payloads are copied out of the shared buffer.
1041
+ */
1042
+ function complete(decoder, data, frame) {
1043
+ return decoder.pos === data.byteLength ? frame : null;
1044
+ }
1045
+ function readPayload(decoder) {
1046
+ return decoding.readVarUint8Array(decoder).slice();
1047
+ }
1048
+ /** Returns null for a frame that is malformed or of an unknown type. */
1049
+ function decodeRelayClientFrame(data) {
1050
+ try {
1051
+ const decoder = decoding.createDecoder(data);
1052
+ const type = decoding.readVarUint(decoder);
1053
+ if (type === CLIENT_AUTH) return complete(decoder, data, {
1054
+ type: "auth",
1055
+ token: decoding.readVarString(decoder)
1056
+ });
1057
+ if (type !== CLIENT_MESSAGE) return null;
1058
+ const namespace = decoding.readVarString(decoder);
1059
+ const target = decoding.readVarString(decoder);
1060
+ const payload = readPayload(decoder);
1061
+ return complete(decoder, data, {
1062
+ type: "message",
1063
+ namespace,
1064
+ target: target || null,
1065
+ payload
1066
+ });
1067
+ } catch {
1068
+ return null;
1069
+ }
1070
+ }
1071
+ /** Returns null for a frame that is malformed or of an unknown type. */
1072
+ function decodeRelayServerFrame(data) {
1073
+ try {
1074
+ const decoder = decoding.createDecoder(data);
1075
+ switch (decoding.readVarUint(decoder)) {
1076
+ case SERVER_WELCOME: {
1077
+ const peerId = decoding.readVarString(decoder);
1078
+ const count = decoding.readVarUint(decoder);
1079
+ const peers = [];
1080
+ for (let index = 0; index < count; index++) peers.push(decoding.readVarString(decoder));
1081
+ return complete(decoder, data, {
1082
+ type: "welcome",
1083
+ peerId,
1084
+ peers
1085
+ });
1086
+ }
1087
+ case SERVER_JOIN: return complete(decoder, data, {
1088
+ type: "join",
1089
+ peerId: decoding.readVarString(decoder)
1090
+ });
1091
+ case SERVER_LEAVE: return complete(decoder, data, {
1092
+ type: "leave",
1093
+ peerId: decoding.readVarString(decoder)
1094
+ });
1095
+ case SERVER_MESSAGE: return complete(decoder, data, {
1096
+ type: "message",
1097
+ namespace: decoding.readVarString(decoder),
1098
+ from: decoding.readVarString(decoder),
1099
+ payload: readPayload(decoder)
1100
+ });
1101
+ default: return null;
1102
+ }
1103
+ } catch {
1104
+ return null;
1105
+ }
1106
+ }
1107
+ //#endregion
1108
+ //#region src/contract/comments.ts
1109
+ /**
1110
+ * The room map that holds a document's comment threads by ID. Each thread is a map of its fields,
1111
+ * and its `replies` field a map of replies by ID, so people commenting at once all keep theirs.
1112
+ */
1113
+ const ROOM_COMMENT_THREADS = "commentThreads";
1114
+ /** The most threads one message on the comment channel may carry. */
1115
+ const MAX_RELAYED_COMMENT_THREADS = 20;
1116
+ /**
1117
+ * The most bytes one message on the comment channel carries: well under the smallest message
1118
+ * limit a relay may set, with room for framing, so a commenter's message never closes its socket.
1119
+ */
1120
+ const MAX_RELAYED_COMMENT_BYTES = 196624;
1121
+ /** The longest comment or reply the relay writes for a commenter, in characters. */
1122
+ const MAX_RELAYED_COMMENT_TEXT = 1e4;
1123
+ /** The most replies a thread a commenter sends may hold. */
1124
+ const MAX_RELAYED_COMMENT_REPLIES = 500;
1125
+ const commentRelayMessageSchema = v.object({ threads: v.pipe(v.array(v.unknown()), v.minLength(1), v.maxLength(20), v.transform((items) => {
1126
+ const parsed = v.safeParse(commentThreadsSchema, items);
1127
+ return parsed.success ? parsed.output : [];
1128
+ })) });
1129
+ /** A commenter's changed threads, as it sends them on the relay's comment channel. */
1130
+ function encodeCommentRelayMessage(threads) {
1131
+ return new TextEncoder().encode(JSON.stringify({ threads }));
1132
+ }
1133
+ /** Bytes `encodeCommentRelayMessage` adds around its threads: `{"threads":[` and `]}`. */
1134
+ const COMMENT_MESSAGE_FRAMING_BYTES = encodeCommentRelayMessage([]).byteLength;
1135
+ /**
1136
+ * Packs threads into as few comment channel messages as fit `MAX_RELAYED_COMMENT_THREADS` and
1137
+ * `MAX_RELAYED_COMMENT_BYTES`. A thread too large for a message of its own cannot be sent; it is
1138
+ * returned in `oversized` instead.
1139
+ */
1140
+ function packCommentRelayMessages(threads) {
1141
+ const encoder = new TextEncoder();
1142
+ const messages = [];
1143
+ const oversized = [];
1144
+ let batch = [];
1145
+ let bytes = COMMENT_MESSAGE_FRAMING_BYTES;
1146
+ const flush = () => {
1147
+ if (batch.length > 0) messages.push(encodeCommentRelayMessage(batch));
1148
+ batch = [];
1149
+ bytes = COMMENT_MESSAGE_FRAMING_BYTES;
1150
+ };
1151
+ for (const thread of threads) {
1152
+ const size = encoder.encode(JSON.stringify(thread)).byteLength;
1153
+ if (COMMENT_MESSAGE_FRAMING_BYTES + size > MAX_RELAYED_COMMENT_BYTES) {
1154
+ oversized.push(thread);
1155
+ continue;
1156
+ }
1157
+ const added = size + (batch.length > 0 ? 1 : 0);
1158
+ if (batch.length >= 20 || bytes + added > MAX_RELAYED_COMMENT_BYTES) {
1159
+ flush();
1160
+ bytes += size;
1161
+ } else bytes += added;
1162
+ batch.push(thread);
1163
+ }
1164
+ flush();
1165
+ return {
1166
+ messages,
1167
+ oversized
1168
+ };
1169
+ }
1170
+ /** The threads a comment channel message carries, or null when it is not one. */
1171
+ function decodeCommentRelayMessage(data) {
1172
+ let text;
1173
+ try {
1174
+ text = new TextDecoder("utf-8", {
1175
+ fatal: true,
1176
+ ignoreBOM: false
1177
+ }).decode(data);
1178
+ } catch {
1179
+ return null;
1180
+ }
1181
+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), commentRelayMessageSchema), text);
1182
+ return parsed.success ? parsed.output.threads : null;
1183
+ }
1184
+ function byCreatedAt(first, second) {
1185
+ return first.createdAt.localeCompare(second.createdAt);
1186
+ }
1187
+ /** A thread as the room holds it, read as files are; null when there is none or it is unreadable. */
1188
+ function readRoomCommentThread(threads, id) {
1189
+ const record = threads.get(id);
1190
+ if (!(record instanceof Y.Map)) return null;
1191
+ const json = record.toJSON();
1192
+ if (typeof json !== "object" || json === null) return null;
1193
+ const replies = Reflect.get(json, "replies");
1194
+ const listed = typeof replies === "object" && replies !== null ? Object.values(replies) : [];
1195
+ const parsed = v.safeParse(commentThreadsSchema, [{
1196
+ ...json,
1197
+ replies: listed
1198
+ }]);
1199
+ const thread = parsed.success ? parsed.output[0] : void 0;
1200
+ return thread ? {
1201
+ ...thread,
1202
+ replies: thread.replies.toSorted(byCreatedAt)
1203
+ } : null;
1204
+ }
1205
+ /**
1206
+ * Writes a thread into the room in the layout editors write it: its fields one by one, and its
1207
+ * replies keyed by ID, changing only what differs so a field another peer changed keeps its change.
1208
+ */
1209
+ function writeRoomCommentThread(threads, thread) {
1210
+ let record = threads.get(thread.id);
1211
+ if (!(record instanceof Y.Map)) {
1212
+ record = new Y.Map();
1213
+ threads.set(thread.id, record);
1214
+ }
1215
+ const target = record;
1216
+ const { replies, ...fields } = thread;
1217
+ const entries = new Map(Object.entries(fields));
1218
+ for (const key of Array.from(target.keys())) if (key !== "replies" && !entries.has(key)) target.delete(key);
1219
+ for (const [key, value] of entries) if (value === void 0) {
1220
+ if (target.has(key)) target.delete(key);
1221
+ } else if (!isEqual(target.get(key), value)) target.set(key, structuredClone(value));
1222
+ let byId = target.get("replies");
1223
+ if (!(byId instanceof Y.Map)) {
1224
+ byId = new Y.Map();
1225
+ target.set("replies", byId);
1226
+ }
1227
+ const replyMap = byId;
1228
+ for (const reply of replies) {
1229
+ const value = omitBy(reply, (field) => field === void 0);
1230
+ if (!isEqual(replyMap.get(reply.id), value)) replyMap.set(reply.id, structuredClone(value));
1231
+ }
1232
+ }
1233
+ //#endregion
1234
+ //#region src/contract/entitlements.ts
1235
+ const workspaceEntitlementsSchema = v.object({
1236
+ features: v.object({
1237
+ links: v.boolean(),
1238
+ guestView: v.boolean(),
1239
+ guestEdit: v.boolean(),
1240
+ guestPresence: v.boolean(),
1241
+ collaboration: v.boolean(),
1242
+ revisionHistory: v.boolean(),
1243
+ cloudAI: v.optional(v.boolean(), false)
1244
+ }),
1245
+ limits: v.object({
1246
+ maximumFileBytes: v.pipe(v.number(), v.integer(), v.minValue(1)),
1247
+ maximumStorageBytes: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
1248
+ maximumParticipants: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
1249
+ monthlyCreditAllowance: v.optional(v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0))), null)
1250
+ }),
1251
+ usage: v.object({
1252
+ committedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0)),
1253
+ reservedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0))
1254
+ })
1255
+ });
1256
+ //#endregion
1257
+ //#region src/contract/discovery.ts
1258
+ const CLOUD_PROTOCOL_VERSION = "1";
1259
+ const CLOUD_DISCOVERY_PATH = "/.well-known/pairdraw";
1260
+ const cloudDeploymentSchema = v.picklist(["official", "self-hosted"]);
1261
+ const cloudAuthenticationSchema = v.object({
1262
+ emailPassword: v.optional(v.object({
1263
+ signIn: v.boolean(),
1264
+ signUp: v.boolean(),
1265
+ minimumPasswordLength: v.pipe(v.number(), v.integer(), v.minValue(8)),
1266
+ captcha: v.optional(v.object({
1267
+ provider: v.literal("cloudflare-turnstile"),
1268
+ siteKey: v.pipe(v.string(), v.trim(), v.minLength(1))
1269
+ }))
1270
+ })),
1271
+ socialProviders: v.array(v.picklist(["apple", "google"])),
1272
+ enterpriseSSO: v.boolean(),
1273
+ enrollmentMode: v.optional(v.picklist([
1274
+ "open",
1275
+ "approval",
1276
+ "closed"
1277
+ ]), "open"),
1278
+ mfa: v.optional(v.object({
1279
+ deploymentAdminRequired: v.boolean(),
1280
+ totp: v.boolean(),
1281
+ passkeys: v.boolean(),
1282
+ recoveryCodes: v.boolean()
1283
+ }))
1284
+ });
1285
+ const cloudCapabilitiesSchema = v.object({
1286
+ documents: v.boolean(),
1287
+ workspaces: v.boolean(),
1288
+ collaboration: v.boolean()
1289
+ });
1290
+ /** A released editor version, `major.minor.patch`. */
1291
+ const cloudEditorVersionSchema = v.pipe(v.string(), v.regex(/^\d+\.\d+\.\d+$/));
1292
+ /**
1293
+ * Whether editors offer this server to everyone, and from which editor version on. Only the
1294
+ * official server's listing is read: it turns the Cloud entry points on without an editor release,
1295
+ * and an editor older than the minimum keeps them hidden.
1296
+ */
1297
+ const cloudListingSchema = v.object({ minimumEditorVersion: cloudEditorVersionSchema });
1298
+ const cloudDiscoverySchema = v.object({
1299
+ protocolVersion: v.literal("1"),
1300
+ deployment: cloudDeploymentSchema,
1301
+ apiURL: v.pipe(v.string(), v.url()),
1302
+ authURL: v.pipe(v.string(), v.url()),
1303
+ /** Whether the server's own editor works with files on this device without signing in. */
1304
+ localEditor: v.optional(v.boolean(), true),
1305
+ authentication: cloudAuthenticationSchema,
1306
+ capabilities: cloudCapabilitiesSchema,
1307
+ listing: v.optional(cloudListingSchema),
1308
+ /** The AI service editors reach with Cloud-signed tokens; absent when the deployment has none. */
1309
+ ai: v.optional(cloudAIDiscoverySchema),
1310
+ /** Where people manage their plan and buy credits; absent when the deployment does not bill. */
1311
+ billing: v.optional(cloudBillingDiscoverySchema)
1312
+ });
1313
+ /** The server's own address, where its editor and pages are, from its auth API's. */
1314
+ function cloudServerOrigin(discovery) {
1315
+ return new URL(discovery.authURL).origin;
1316
+ }
1317
+ function parseCloudDiscovery(input) {
1318
+ return v.parse(cloudDiscoverySchema, input);
1319
+ }
1320
+ //#endregion
1321
+ //#region src/contract/sharing.ts
1322
+ const documentShareSchema = v.object({
1323
+ id: v.pipe(v.string(), v.uuid()),
1324
+ documentId: v.pipe(v.string(), v.uuid()),
1325
+ permission: documentPermissionSchema,
1326
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
1327
+ createdBy: v.string(),
1328
+ createdAt: v.string(),
1329
+ updatedAt: v.string(),
1330
+ expiresAt: v.nullable(v.string()),
1331
+ revokedAt: v.nullable(v.string()),
1332
+ lastUsedAt: v.nullable(v.string()),
1333
+ /**
1334
+ * The revision a snapshot link shows, frozen as it was shared, or null for a live link that
1335
+ * opens the document's room. Servers that predate snapshots leave it out.
1336
+ */
1337
+ revisionId: v.optional(v.nullable(v.pipe(v.string(), v.uuid())), null)
1338
+ });
1339
+ /**
1340
+ * Which revision a snapshot link pins: the document's current one, or one of its revisions by ID.
1341
+ * A snapshot link is always view-only and never opens the document's room.
1342
+ */
1343
+ const shareSnapshotSchema = v.union([v.literal("current"), v.pipe(v.string(), v.uuid())]);
1344
+ /** When a link stops working, as an ISO timestamp; `null` keeps it working until revoked. */
1345
+ const shareExpirySchema = v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp())));
1346
+ const createDocumentShareSchema = v.pipe(v.object({
1347
+ permission: documentPermissionSchema,
1348
+ expiresAt: shareExpirySchema,
1349
+ /** Makes a snapshot link to this revision instead of a live link. */
1350
+ snapshot: v.optional(shareSnapshotSchema)
1351
+ }), v.check((input) => input.snapshot === void 0 || input.permission === "view", "A snapshot link only lets people view"));
1352
+ const updateDocumentShareSchema = v.object({
1353
+ permission: v.optional(documentPermissionSchema),
1354
+ expiresAt: shareExpirySchema,
1355
+ /** Pins a snapshot link to another revision, as Update snapshot does; live links refuse it. */
1356
+ snapshot: v.optional(shareSnapshotSchema)
1357
+ });
1358
+ const resolveDocumentShareSchema = v.object({
1359
+ secret: v.pipe(v.string(), v.minLength(32), v.maxLength(128)),
1360
+ guestName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
1361
+ guestId: v.optional(v.pipe(v.string(), v.minLength(16), v.maxLength(128)))
1362
+ });
1363
+ /** A guest's request for the links of images a shared document's live room names. */
1364
+ const requestSharedImageLinksSchema = v.object({
1365
+ ...resolveDocumentShareSchema.entries,
1366
+ ...requestImageLinksSchema.entries
1367
+ });
1368
+ function parseRequestSharedImageLinks(input) {
1369
+ return v.parse(requestSharedImageLinksSchema, input);
1370
+ }
1371
+ const resolvedDocumentShareSchema = v.object({
1372
+ documentId: v.pipe(v.string(), v.uuid()),
1373
+ permission: documentPermissionSchema,
1374
+ principal: collaborationPrincipalSchema,
1375
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
1376
+ /** The revision a snapshot link shows; null for a live link. */
1377
+ revisionId: v.optional(v.nullable(v.pipe(v.string(), v.uuid())), null)
1378
+ });
1379
+ const cloudUserProfileSchema = v.object({
1380
+ id: v.string(),
1381
+ name: v.string(),
1382
+ email: v.pipe(v.string(), v.email()),
1383
+ image: v.nullable(v.pipe(v.string(), v.url()))
1384
+ });
1385
+ const documentGrantSchema = v.object({
1386
+ id: v.pipe(v.string(), v.uuid()),
1387
+ documentId: v.pipe(v.string(), v.uuid()),
1388
+ userId: v.string(),
1389
+ permission: documentPermissionSchema,
1390
+ createdBy: v.string(),
1391
+ createdAt: v.string(),
1392
+ updatedAt: v.string()
1393
+ });
1394
+ /** What accepting an invitation gave: access to a document, or a place in a workspace. */
1395
+ const acceptedInvitationSchema = v.variant("kind", [v.object({
1396
+ kind: v.literal("document"),
1397
+ grant: documentGrantSchema
1398
+ }), v.object({
1399
+ kind: v.literal("workspace"),
1400
+ workspaceId: v.pipe(v.string(), v.uuid()),
1401
+ role: workspaceRoleSchema
1402
+ })]);
1403
+ const lookupCloudUserSchema = v.object({ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()) });
1404
+ const putDocumentGrantSchema = v.object({ permission: documentPermissionSchema });
1405
+ const createDocumentInvitationSchema = v.object({
1406
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
1407
+ permission: documentPermissionSchema
1408
+ });
1409
+ const acceptDocumentInvitationSchema = v.object({ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128)) });
1410
+ const createInvitationContinuationSchema = v.object({
1411
+ invitationId: v.pipe(v.string(), v.uuid()),
1412
+ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))
1413
+ });
1414
+ const invitationContinuationSchema = v.object({ id: v.pipe(v.string(), v.minLength(16), v.maxLength(128)) });
1415
+ const invitationPreviewFields = {
1416
+ inviterName: v.string(),
1417
+ expiresAt: v.string(),
1418
+ recipientHint: v.string()
1419
+ };
1420
+ /** What an invitation link opens: one document, or a whole workspace. */
1421
+ const invitationPreviewSchema = v.variant("kind", [v.object({
1422
+ kind: v.literal("document"),
1423
+ documentName: v.string(),
1424
+ permission: documentPermissionSchema,
1425
+ ...invitationPreviewFields
1426
+ }), v.object({
1427
+ kind: v.literal("workspace"),
1428
+ workspaceName: v.string(),
1429
+ role: workspaceRoleSchema,
1430
+ ...invitationPreviewFields
1431
+ })]);
1432
+ const documentInvitationSchema = v.object({
1433
+ id: v.pipe(v.string(), v.uuid()),
1434
+ documentId: v.pipe(v.string(), v.uuid()),
1435
+ email: v.pipe(v.string(), v.email()),
1436
+ permission: documentPermissionSchema,
1437
+ invitedBy: v.string(),
1438
+ invitedAt: v.string(),
1439
+ expiresAt: v.string(),
1440
+ acceptedAt: v.nullable(v.string())
1441
+ });
1442
+ function parseCreateInvitationContinuation(input) {
1443
+ return v.parse(createInvitationContinuationSchema, input);
1444
+ }
1445
+ function parseLookupCloudUser(input) {
1446
+ return v.parse(lookupCloudUserSchema, input);
1447
+ }
1448
+ function parseCreateDocumentShare(input) {
1449
+ return v.parse(createDocumentShareSchema, input);
1450
+ }
1451
+ function parseUpdateDocumentShare(input) {
1452
+ return v.parse(updateDocumentShareSchema, input);
1453
+ }
1454
+ function parseResolveDocumentShare(input) {
1455
+ return v.parse(resolveDocumentShareSchema, input);
1456
+ }
1457
+ function parsePutDocumentGrant(input) {
1458
+ return v.parse(putDocumentGrantSchema, input);
1459
+ }
1460
+ function parseCreateDocumentInvitation(input) {
1461
+ return v.parse(createDocumentInvitationSchema, input);
1462
+ }
1463
+ function parseAcceptDocumentInvitation(input) {
1464
+ return v.parse(acceptDocumentInvitationSchema, input);
1465
+ }
1466
+ //#endregion
1467
+ //#region src/contract/links.ts
1468
+ const CLOUD_LINK_PATH = /^\/(invitations|share|documents|view)\/([^/]+)$/;
1469
+ /**
1470
+ * A link on the server's own editor. The server is the link's own address, so the link needs
1471
+ * nothing else to name it; a secret travels in the fragment, so it never reaches access logs or
1472
+ * `Referer` headers.
1473
+ */
1474
+ function serverLink(serverURL, path, query = {}, secret) {
1475
+ const { protocol, host } = parseURL(serverURL);
1476
+ if (protocol !== "https:" && protocol !== "http:") throw new Error("A Cloud server address must use HTTP or HTTPS");
1477
+ const link = withQuery(`${protocol}//${host}${path}`, query);
1478
+ return secret ? withFragment(link, secret) : link;
1479
+ }
1480
+ /** An invitation to a document or a workspace, `/invitations/:id#token`. */
1481
+ function cloudInvitationURL(serverURL, invitationId, token) {
1482
+ return serverLink(serverURL, `/invitations/${encodeParam(invitationId)}`, {}, token);
1483
+ }
1484
+ /** A document shared by link, `/share/:id#secret`. */
1485
+ function cloudShareURL(serverURL, shareId, secret) {
1486
+ return serverLink(serverURL, `/share/${encodeParam(shareId)}`, {}, secret);
1487
+ }
1488
+ /**
1489
+ * A document's address for its members, `/documents/:id`, or one of its versions with
1490
+ * `?version=…`. It carries no secret: whoever opens it signs in, and the server decides.
1491
+ */
1492
+ function cloudDocumentURL(serverURL, documentId, versionId = null) {
1493
+ return serverLink(serverURL, cloudDocumentPath(documentId), { version: versionId ?? void 0 });
1494
+ }
1495
+ /**
1496
+ * A document in a workspace on someone's public profile, `/view/:id`, which anyone may open
1497
+ * read-only without signing in.
1498
+ */
1499
+ function cloudPublicDocumentURL(serverURL, documentId) {
1500
+ return serverLink(serverURL, `/view/${encodeParam(documentId)}`);
1501
+ }
1502
+ /** A public profile's page on the server, `/u/:handle`. */
1503
+ function cloudPublicProfilePath(handle) {
1504
+ return `/u/${encodeParam(handle)}`;
1505
+ }
1506
+ function cloudDocumentPath(documentId) {
1507
+ return `/documents/${encodeParam(documentId)}`;
1508
+ }
1509
+ /**
1510
+ * The kind and ID of a Cloud link's path, or null for any other path. The ID is decoded; a broken
1511
+ * escape such as `%E0` is no link.
1512
+ */
1513
+ function parseCloudLinkPath(pathname) {
1514
+ const [, kind, id] = pathname.match(CLOUD_LINK_PATH) ?? [];
1515
+ if (kind !== "invitations" && kind !== "share" && kind !== "documents" && kind !== "view" || !id) return null;
1516
+ try {
1517
+ return {
1518
+ kind,
1519
+ id: decodeURIComponent(id)
1520
+ };
1521
+ } catch {
1522
+ return null;
1523
+ }
1524
+ }
1525
+ /**
1526
+ * The desktop app's form of a Cloud link, `pairdraw://cloud?url=<link>#secret`: the web link,
1527
+ * whose address names the server, with its secret kept in the fragment.
1528
+ * `desktop/src/launch/links.rs` validates it before the editor sees it.
1529
+ */
1530
+ function cloudDesktopLinkURL(kind, id, serverURL, secret) {
1531
+ const link = serverLink(serverURL, `/${kind}/${encodeParam(id)}`);
1532
+ return withFragment(withQuery("pairdraw://cloud", { url: link }), secret);
1533
+ }
1534
+ //#endregion
1535
+ //#region src/contract/portal.ts
1536
+ /**
1537
+ * The pages a Cloud server shows on its own address, apart from the editor: the welcome page for
1538
+ * visitors who are not signed in, sign-in and desktop sign-in approval, account settings, the
1539
+ * administration console, and public profiles (`/u/<handle>`). Every runtime serves the portal's `cloud.html` at and below these
1540
+ * paths, and the editor's `index.html` at the root and at any other page the API does not answer.
1541
+ */
1542
+ const CLOUD_PORTAL_PAGE_ROOTS = [
1543
+ "/welcome",
1544
+ "/auth",
1545
+ "/account",
1546
+ "/admin",
1547
+ "/u"
1548
+ ];
1549
+ function isCloudPortalPage(path) {
1550
+ return CLOUD_PORTAL_PAGE_ROOTS.some((root) => path === root || path.startsWith(`${root}/`));
1551
+ }
1552
+ //#endregion
1553
+ //#region src/contract/profiles.ts
1554
+ /** A public profile's address on the server, `/u/<handle>`: lowercase letters, digits, and dashes. */
1555
+ const PUBLIC_PROFILE_HANDLE_PATTERN = /^[a-z0-9](?:[a-z0-9-]{1,30}[a-z0-9])$/;
1556
+ const PUBLIC_PROFILE_BIO_MAX_LENGTH = 280;
1557
+ const handleSchema = v.pipe(v.string(), v.trim(), v.toLowerCase(), v.regex(PUBLIC_PROFILE_HANDLE_PATTERN));
1558
+ /** A document a public workspace lists, which anyone may open read-only. */
1559
+ const publicDocumentSummarySchema = v.object({
1560
+ id: v.pipe(v.string(), v.uuid()),
1561
+ name: v.string(),
1562
+ updatedAt: v.string()
1563
+ });
1564
+ const publicWorkspaceSchema = v.object({
1565
+ id: v.pipe(v.string(), v.uuid()),
1566
+ name: v.string(),
1567
+ slug: v.string(),
1568
+ documents: v.array(publicDocumentSummarySchema)
1569
+ });
1570
+ /** What anyone sees at `/u/<handle>`: who the person is and the workspaces they made public. */
1571
+ const publicProfileSchema = v.object({
1572
+ handle: v.string(),
1573
+ name: v.string(),
1574
+ image: v.nullable(v.string()),
1575
+ bio: v.nullable(v.string()),
1576
+ workspaces: v.array(publicWorkspaceSchema)
1577
+ });
1578
+ /** A workspace the signed-in person administers, and whether it is on their public profile. */
1579
+ const publicProfileWorkspaceSettingSchema = v.object({
1580
+ id: v.pipe(v.string(), v.uuid()),
1581
+ name: v.string(),
1582
+ public: v.boolean()
1583
+ });
1584
+ /** The signed-in person's own public profile settings; a null handle means no public profile. */
1585
+ const publicProfileSettingsSchema = v.object({
1586
+ handle: v.nullable(v.string()),
1587
+ bio: v.nullable(v.string()),
1588
+ workspaces: v.array(publicProfileWorkspaceSettingSchema)
1589
+ });
1590
+ /** Claims, changes, or (with a null handle) removes the person's public profile. */
1591
+ const updatePublicProfileSchema = v.object({
1592
+ handle: v.nullable(handleSchema),
1593
+ bio: v.optional(v.nullable(v.pipe(v.string(), v.trim(), v.maxLength(280))))
1594
+ });
1595
+ /** Lists a workspace on its administrator's public profile, or takes it off. */
1596
+ const publishWorkspaceSchema = v.object({ public: v.boolean() });
1597
+ /** A public document as anyone may download it. */
1598
+ const publicDocumentDownloadSchema = v.object({ document: documentDownloadSchema });
1599
+ /** Whether a value is a handle a public profile may take. */
1600
+ function isPublicProfileHandle(value) {
1601
+ return PUBLIC_PROFILE_HANDLE_PATTERN.test(value);
1602
+ }
1603
+ function parseUpdatePublicProfile(input) {
1604
+ return v.parse(updatePublicProfileSchema, input);
1605
+ }
1606
+ function parsePublishWorkspace(input) {
1607
+ return v.parse(publishWorkspaceSchema, input);
1608
+ }
1609
+ //#endregion
1610
+ //#region src/contract/versions.ts
1611
+ /** How long a version's name may be; the history list shows the start of longer ones. */
1612
+ const DOCUMENT_VERSION_NAME_MAX_LENGTH = 100;
1613
+ const DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH = 1e3;
1614
+ /** A checkpoint the server kept on its own, or a version someone named. */
1615
+ const documentVersionKindSchema = v.picklist(["checkpoint", "named"]);
1616
+ const documentVersionSchema = v.object({
1617
+ id: v.pipe(v.string(), v.uuid()),
1618
+ revisionId: v.pipe(v.string(), v.uuid()),
1619
+ kind: documentVersionKindSchema,
1620
+ name: v.nullable(v.string()),
1621
+ description: v.nullable(v.string()),
1622
+ createdAt: v.string(),
1623
+ /** Who made the version: the author of a checkpoint's save, or who named or restored it. */
1624
+ createdBy: v.object({
1625
+ id: v.string(),
1626
+ name: v.nullable(v.string())
1627
+ }),
1628
+ /** The version this one restored, while that version is still in the history. */
1629
+ restoredFromVersionId: v.nullable(v.pipe(v.string(), v.uuid())),
1630
+ /** Whether the document holds this version now. */
1631
+ current: v.boolean()
1632
+ });
1633
+ const documentVersionsSchema = v.object({
1634
+ versions: v.array(documentVersionSchema),
1635
+ /** Pass as `before` for the next, older page; null on the last one. */
1636
+ nextCursor: v.nullable(v.pipe(v.string(), v.uuid()))
1637
+ });
1638
+ const versionNameSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100));
1639
+ const versionDescriptionSchema = v.pipe(v.string(), v.trim(), v.maxLength(DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH));
1640
+ /** Names the document as it is now, like Save to version history. */
1641
+ const saveDocumentVersionSchema = v.object({
1642
+ name: versionNameSchema,
1643
+ description: v.optional(versionDescriptionSchema, "")
1644
+ });
1645
+ /** Names a version or changes its name; a null name deletes its info and leaves a checkpoint. */
1646
+ const updateDocumentVersionSchema = v.object({
1647
+ name: v.nullable(versionNameSchema),
1648
+ description: v.optional(versionDescriptionSchema, "")
1649
+ });
1650
+ const duplicateDocumentVersionSchema = v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255)) });
1651
+ const documentVersionResponseSchema = v.object({ version: documentVersionSchema });
1652
+ /** A version with where to download it, so a link to it can show it without the history. */
1653
+ const documentVersionDownloadSchema = v.object({
1654
+ document: documentDownloadSchema,
1655
+ version: documentVersionSchema
1656
+ });
1657
+ const restoredDocumentSchema = v.object({
1658
+ document: documentSummarySchema,
1659
+ version: documentVersionSchema
1660
+ });
1661
+ function parseSaveDocumentVersion(input) {
1662
+ return v.parse(saveDocumentVersionSchema, input);
1663
+ }
1664
+ function parseUpdateDocumentVersion(input) {
1665
+ return v.parse(updateDocumentVersionSchema, input);
1666
+ }
1667
+ function parseDuplicateDocumentVersion(input) {
1668
+ return v.parse(duplicateDocumentVersionSchema, input);
1669
+ }
1670
+ //#endregion
1671
+ export { AI_ERROR_STATUS, CLOUD_AI_API_PATHS, CLOUD_AI_CONTRACT_VERSION, CLOUD_AI_JWKS_PATH, CLOUD_AI_TOKEN_AUDIENCE, CLOUD_DISCOVERY_PATH, CLOUD_DOCUMENT_NAME_MAX_LENGTH, CLOUD_IMAGE_NAME_PATTERN, CLOUD_MAX_DOCUMENT_IMAGES, CLOUD_PICTURE_MAX_BYTES, CLOUD_PICTURE_SIZE, CLOUD_PORTAL_PAGE_ROOTS, CLOUD_PROTOCOL_MAX_UPLOAD_BYTES, CLOUD_PROTOCOL_VERSION, COLLAB_ACTIONS, DOCUMENT_PERMISSIONS, DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH, DOCUMENT_VERSION_NAME_MAX_LENGTH, MAX_COLLAB_MESSAGE_BYTES, MAX_PRESENCE_NAME_LENGTH, MAX_RELAYED_COMMENT_BYTES, MAX_RELAYED_COMMENT_REPLIES, MAX_RELAYED_COMMENT_TEXT, MAX_RELAYED_COMMENT_THREADS, PUBLIC_PROFILE_BIO_MAX_LENGTH, PUBLIC_PROFILE_HANDLE_PATTERN, RELAY_CLOSE, RELAY_DOCUMENT_PARAM, RELAY_FORWARDING_BYTES, RELAY_FRAGMENT_BYTES, RELAY_MINIMUM_MESSAGE_BYTES, RELAY_PATH, RELAY_SERVER_PEER, ROOM_COMMENT_THREADS, acceptDocumentInvitationSchema, acceptedInvitationSchema, accountSecurityErrorCodeSchema, accountSecurityErrorResponseSchema, adminAuditEventSchema, adminAuditResponseSchema, adminEmailResponseSchema, adminErrorCodeSchema, adminErrorResponseSchema, adminMutationResponseSchema, adminOperationsResponseSchema, aiCatalogSchema, aiCreditBucketSchema, aiErrorCodeSchema, aiErrorSchema, aiModelSchema, aiTokenClaimsSchema, aiTokenSchema, aiUsageEntrySchema, aiUsagePageSchema, aiUsageQuerySchema, aiWalletSchema, cloudAIDiscoverySchema, cloudAccountMutationResponseSchema, cloudAccountSessionSchema, cloudAccountSessionsResponseSchema, cloudAccountStateSchema, cloudAccountStatusResponseSchema, cloudActorSchema, cloudAdminAuditFilterSchema, cloudAdminEmailFilterSchema, cloudAdminSessionResponseSchema, cloudAdminUserDetailSchema, cloudAdminUserFilterSchema, cloudAdminUserSchema, cloudAdminUsersResponseSchema, cloudAuthenticationMethodSchema, cloudAuthenticationMethodsResponseSchema, cloudAuthenticationProviderSchema, cloudAuthenticationSchema, cloudBillingDiscoverySchema, cloudCapabilitiesSchema, cloudDeploymentSchema, cloudDesktopLinkURL, cloudDiscoverySchema, cloudDocumentPath, cloudDocumentURL, cloudEditorVersionSchema, cloudEmailChangeSchema, cloudIdentitySchema, cloudInvitationURL, cloudListingSchema, cloudMFAEnableResponseSchema, cloudMFAEnableSchema, cloudMFARecoveryCodesResponseSchema, cloudMFAStatusResponseSchema, cloudMFAStatusSchema, cloudMFAVerifyResponseSchema, cloudMFAVerifySchema, cloudPasskeyDeleteSchema, cloudPasskeySchema, cloudPasskeysResponseSchema, cloudPasswordChangeSchema, cloudPersonSchema, cloudPictureResponseSchema, cloudPictureUploadSchema, cloudPresenceSchema, cloudProfileResponseSchema, cloudProfileSchema, cloudProfileUpdateSchema, cloudPublicDocumentURL, cloudPublicProfilePath, cloudServerOrigin, cloudSessionRevokeSchema, cloudSessionSchema, cloudShareURL, cloudSignInMethodSchema, cloudSignInSchema, cloudSignInsResponseSchema, cloudSocialLinkResponseSchema, cloudSocialLinkSchema, cloudUnlinkAuthenticationMethodSchema, cloudUserProfileSchema, collaborationPrincipalSchema, collaborationTicketSchema, commitImageUploadsSchema, commitUploadSchema, createAITokenSchema, createDocumentInvitationSchema, createDocumentSchema, createDocumentShareSchema, createInvitationContinuationSchema, createRelayClientAssembler, createRelayServerAssembler, createUploadSchema, createWorkspaceInvitationSchema, createWorkspaceSchema, createdWorkspaceInvitationSchema, decodeCommentRelayMessage, decodeRelayClientFrame, decodeRelayServerFrame, decodeRoomUpdate, defaultRelayURL, documentAccessSchema, documentAccessSourceSchema, documentDownloadSchema, documentGrantSchema, documentImageDownloadSchema, documentImageLinkSchema, documentInvitationSchema, documentPermissionSchema, documentShareSchema, documentSummarySchema, documentVersionDownloadSchema, documentVersionKindSchema, documentVersionResponseSchema, documentVersionSchema, documentVersionsSchema, duplicateDocumentVersionSchema, encodeCommentRelayMessage, encodeRelayClientFrame, encodeRelayServerFrame, encodeSyncReply, enrollmentReviewResponseSchema, enrollmentSchema, enrollmentStatusSchema, enrollmentsResponseSchema, imageUploadOfferSchema, invitationContinuationSchema, invitationPreviewSchema, isCloudChecksum, isCloudPortalPage, isPublicProfileHandle, lookupCloudUserSchema, objectUploadSchema, packCommentRelayMessages, parseAIUsageQuery, parseAcceptDocumentInvitation, parseCloudDiscovery, parseCloudEmailChange, parseCloudLinkPath, parseCloudMFAEnable, parseCloudMFAVerify, parseCloudPasskeyDelete, parseCloudPasswordChange, parseCloudPictureUpload, parseCloudProfileUpdate, parseCloudSessionRevoke, parseCloudSocialLink, parseCloudUnlinkAuthenticationMethod, parseCommitImageUploads, parseCommitUpload, parseCreateAIToken, parseCreateDocument, parseCreateDocumentInvitation, parseCreateDocumentShare, parseCreateInvitationContinuation, parseCreateUpload, parseCreateWorkspace, parseCreateWorkspaceInvitation, parseDuplicateDocumentVersion, parseLookupCloudUser, parsePublishWorkspace, parsePutDocumentGrant, parseRequestImageLinks, parseRequestImageUploads, parseRequestSharedImageLinks, parseResolveDocumentShare, parseSaveDocumentVersion, parseUpdateDocumentShare, parseUpdateDocumentVersion, parseUpdatePublicProfile, parseUpdateWorkspace, parseUpdateWorkspaceMember, presenceName, publicDocumentDownloadSchema, publicDocumentSummarySchema, publicProfileSchema, publicProfileSettingsSchema, publicProfileWorkspaceSettingSchema, publicWorkspaceSchema, publishWorkspaceSchema, putDocumentGrantSchema, readRoomCommentThread, relayClientMessages, relayServerMessages, requestImageLinksSchema, requestImageUploadsSchema, requestSharedImageLinksSchema, resolveDocumentShareSchema, resolvedDocumentShareSchema, restoredDocumentSchema, saveDocumentVersionSchema, shareSnapshotSchema, sharedDocumentSchema, transactionalEmailAdminSchema, updateDocumentShareSchema, updateDocumentVersionSchema, updatePublicProfileSchema, updateWorkspaceMemberSchema, updateWorkspaceSchema, workspaceEntitlementsSchema, workspaceInvitationSchema, workspaceListSchema, workspaceMemberSchema, workspaceMembersSchema, workspaceRoleSchema, workspaceSummarySchema, workspaceUsageSchema, writeRoomCommentThread };
1672
+
1673
+ //# sourceMappingURL=contract2.js.map