@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
package/dist/client.js ADDED
@@ -0,0 +1,2008 @@
1
+ import { isValid } from "js-base64";
2
+ import * as v from "valibot";
3
+ import { zipObject } from "es-toolkit";
4
+ import { joinURL, withQuery, withoutFragment } from "ufo";
5
+ import { pickBy } from "es-toolkit/object";
6
+ import { hc } from "hono/client";
7
+ import { passkeyClient } from "@better-auth/passkey/client";
8
+ import { createAuthClient } from "better-auth/client";
9
+ import { deviceAuthorizationClient, twoFactorClient } from "better-auth/client/plugins";
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
+ v.object({
45
+ currentPassword: v.string(),
46
+ newPassword: v.string()
47
+ });
48
+ 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
+ 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
+ v.object({ password: v.optional(v.string()) });
78
+ const cloudMFAEnableResponseSchema = v.object({
79
+ totpURI: v.string(),
80
+ backupCodes: v.array(v.string())
81
+ });
82
+ 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
+ v.object({ id: v.string() });
92
+ const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) });
93
+ /** Who an account belongs to, as the portal shows it. */
94
+ const cloudPersonSchema = v.object({
95
+ id: v.string(),
96
+ name: v.string(),
97
+ email: v.pipe(v.string(), v.email()),
98
+ /** The address of the account's picture, which the server serves; null shows initials. */
99
+ image: v.nullable(v.string())
100
+ });
101
+ /** What a person can see and change about themselves. */
102
+ const cloudProfileSchema = v.object({
103
+ ...cloudPersonSchema.entries,
104
+ createdAt: v.string(),
105
+ /** Whether the server can send the verification a new email address needs. */
106
+ emailChangeAvailable: v.boolean()
107
+ });
108
+ const cloudProfileResponseSchema = v.object({ profile: cloudProfileSchema });
109
+ v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)) });
110
+ v.object({
111
+ /** The picture's PNG or JPEG bytes, in Base64. */
112
+ data: v.pipe(v.string(), v.maxLength(Math.ceil(262144 / 3) * 4), v.check((value) => isValid(value))) });
113
+ /** The address the account's picture is now served from. */
114
+ const cloudPictureResponseSchema = v.object({ image: v.string() });
115
+ v.object({
116
+ newEmail: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
117
+ callbackURL: v.pipe(v.string(), v.url())
118
+ });
119
+ /** How a sign-in was made: the method it used, or the desktop app's approved code. */
120
+ const cloudSignInMethodSchema = v.picklist([
121
+ "password",
122
+ "google",
123
+ "apple",
124
+ "passkey",
125
+ "two-step",
126
+ "email-link",
127
+ "desktop",
128
+ "other"
129
+ ]);
130
+ const cloudAccountSessionSchema = v.object({
131
+ id: v.string(),
132
+ /** The session this request was made with. */
133
+ current: v.boolean(),
134
+ method: v.nullable(cloudSignInMethodSchema),
135
+ ipAddress: v.nullable(v.string()),
136
+ /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
137
+ browser: v.nullable(v.string()),
138
+ system: v.nullable(v.string()),
139
+ createdAt: v.string(),
140
+ lastActiveAt: v.string(),
141
+ expiresAt: v.string()
142
+ });
143
+ const cloudAccountSessionsResponseSchema = v.object({ sessions: v.array(cloudAccountSessionSchema) });
144
+ v.object({ sessionId: v.pipe(v.string(), v.minLength(1)) });
145
+ const cloudSignInSchema = v.object({
146
+ id: v.string(),
147
+ method: cloudSignInMethodSchema,
148
+ ipAddress: v.nullable(v.string()),
149
+ /** The browser and system the server read from the client's user agent, such as `Chrome 141`. */
150
+ browser: v.nullable(v.string()),
151
+ system: v.nullable(v.string()),
152
+ createdAt: v.string()
153
+ });
154
+ const cloudSignInsResponseSchema = v.object({ signIns: v.array(cloudSignInSchema) });
155
+ /** The `aud` of every token Cloud signs for an AI service. */
156
+ const CLOUD_AI_TOKEN_AUDIENCE = "pairdraw-ai";
157
+ /**
158
+ * Where a service answers, below the discovered `endpoint`. Model requests follow the OpenAI chat
159
+ * completions API, so an OpenAI-compatible client takes `${endpoint}${base}` as its base URL.
160
+ */
161
+ const CLOUD_AI_API_PATHS = {
162
+ base: "/v1",
163
+ chatCompletions: "/v1/chat/completions",
164
+ catalog: "/v1/catalog",
165
+ wallet: "/v1/wallet",
166
+ usage: "/v1/usage"
167
+ };
168
+ const urlSchema = v.pipe(v.string(), v.url());
169
+ const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
170
+ const cloudAIDiscoverySchema = v.object({
171
+ endpoint: urlSchema,
172
+ contractVersion: v.literal("1")
173
+ });
174
+ const cloudBillingDiscoverySchema = v.object({ portalURL: urlSchema });
175
+ v.object({ workspaceId: v.pipe(v.string(), v.uuid()) });
176
+ const aiTokenSchema = v.object({
177
+ token: v.pipe(v.string(), v.minLength(1)),
178
+ expiresAt: v.pipe(v.string(), v.isoTimestamp())
179
+ });
180
+ v.object({
181
+ iss: urlSchema,
182
+ aud: v.literal(CLOUD_AI_TOKEN_AUDIENCE),
183
+ sub: v.pipe(v.string(), v.minLength(1)),
184
+ workspaceId: v.pipe(v.string(), v.uuid()),
185
+ /** Credits the workspace's plan grants each month; `null` when Cloud sets no allowance. */
186
+ monthlyCreditAllowance: v.nullable(creditsSchema),
187
+ iat: v.pipe(v.number(), v.integer()),
188
+ exp: v.pipe(v.number(), v.integer())
189
+ });
190
+ const aiModelSchema = v.object({
191
+ id: v.pipe(v.string(), v.minLength(1)),
192
+ label: v.pipe(v.string(), v.minLength(1)),
193
+ /** Credits per million input and output tokens. */
194
+ creditsPerMillionInputTokens: creditsSchema,
195
+ creditsPerMillionOutputTokens: creditsSchema,
196
+ contextTokens: v.pipe(v.number(), v.integer(), v.minValue(1)),
197
+ capabilities: v.object({
198
+ reasoning: v.boolean(),
199
+ vision: v.boolean(),
200
+ tools: v.boolean()
201
+ })
202
+ });
203
+ const aiCatalogSchema = v.object({
204
+ models: v.array(aiModelSchema),
205
+ defaultModelID: v.pipe(v.string(), v.minLength(1))
206
+ });
207
+ const aiCreditBucketSchema = v.object({
208
+ kind: v.picklist([
209
+ "allowance",
210
+ "purchased",
211
+ "grant"
212
+ ]),
213
+ remaining: creditsSchema,
214
+ expiresAt: v.nullable(v.pipe(v.string(), v.isoTimestamp()))
215
+ });
216
+ /**
217
+ * A service records a request's charge before the request's answer ends, so a wallet read after
218
+ * an answer includes what it cost.
219
+ */
220
+ const aiWalletSchema = v.object({
221
+ /** Credits left to spend; `null` when the service sets no limit. */
222
+ balance: v.nullable(creditsSchema),
223
+ /** Spent first to last. */
224
+ buckets: v.array(aiCreditBucketSchema)
225
+ });
226
+ const aiUsageEntrySchema = v.object({
227
+ id: v.pipe(v.string(), v.minLength(1)),
228
+ createdAt: v.pipe(v.string(), v.isoTimestamp()),
229
+ kind: v.picklist([
230
+ "model",
231
+ "image",
232
+ "search"
233
+ ]),
234
+ modelID: v.nullable(v.string()),
235
+ userId: v.pipe(v.string(), v.minLength(1)),
236
+ credits: creditsSchema
237
+ });
238
+ v.object({ cursor: v.optional(v.pipe(v.string(), v.minLength(1))) });
239
+ v.object({
240
+ entries: v.array(aiUsageEntrySchema),
241
+ next: v.nullable(v.string())
242
+ });
243
+ /** Errors an AI service answers with, beside the upstream model's own. */
244
+ const aiErrorCodeSchema = v.picklist([
245
+ "unauthorized",
246
+ "insufficient_credits",
247
+ "model_not_allowed",
248
+ "rate_limited"
249
+ ]);
250
+ const aiErrorSchema = v.object({ error: v.object({
251
+ code: aiErrorCodeSchema,
252
+ message: v.optional(v.string()),
253
+ /** With `insufficient_credits`: when the workspace's allowance renews, if the service knows. */
254
+ resetsAt: v.optional(v.pipe(v.string(), v.isoTimestamp()))
255
+ }) });
256
+ //#endregion
257
+ //#region src/contract/workspaces.ts
258
+ const workspaceRoleSchema = v.picklist([
259
+ "viewer",
260
+ "editor",
261
+ "admin"
262
+ ]);
263
+ const workspaceSummarySchema = v.object({
264
+ id: v.pipe(v.string(), v.uuid()),
265
+ name: v.string(),
266
+ slug: v.string(),
267
+ role: workspaceRoleSchema,
268
+ createdAt: v.string(),
269
+ updatedAt: v.string()
270
+ });
271
+ v.object({
272
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)),
273
+ slug: v.optional(v.pipe(v.string(), v.trim(), v.minLength(3), v.maxLength(63), v.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)))
274
+ });
275
+ const workspaceListSchema = v.object({ workspaces: v.array(workspaceSummarySchema) });
276
+ v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)) });
277
+ /** Someone who belongs to a workspace, and what they may do in it. */
278
+ const workspaceMemberSchema = v.object({
279
+ userId: v.string(),
280
+ name: v.string(),
281
+ email: v.string(),
282
+ image: v.nullable(v.string()),
283
+ role: workspaceRoleSchema,
284
+ joinedAt: v.string()
285
+ });
286
+ /** An invitation to join a workspace that has not been accepted yet. */
287
+ const workspaceInvitationSchema = v.object({
288
+ id: v.pipe(v.string(), v.uuid()),
289
+ email: v.string(),
290
+ role: workspaceRoleSchema,
291
+ /** Who sent it; the name is null once their account is gone. */
292
+ invitedBy: v.object({
293
+ id: v.string(),
294
+ name: v.nullable(v.string())
295
+ }),
296
+ invitedAt: v.string(),
297
+ expiresAt: v.string()
298
+ });
299
+ const workspaceMembersSchema = v.object({
300
+ members: v.array(workspaceMemberSchema),
301
+ /** Only administrators see pending invitations. */
302
+ invitations: v.array(workspaceInvitationSchema)
303
+ });
304
+ v.object({
305
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
306
+ role: workspaceRoleSchema
307
+ });
308
+ /** A new invitation and its link, for an administrator to pass on when email is off. */
309
+ const createdWorkspaceInvitationSchema = v.object({
310
+ invitation: workspaceInvitationSchema,
311
+ acceptanceURL: v.string()
312
+ });
313
+ v.object({ role: workspaceRoleSchema });
314
+ //#endregion
315
+ //#region src/contract/admin/index.ts
316
+ const timestampSchema = v.pipe(v.string(), v.isoTimestamp());
317
+ const nullableTimestampSchema = v.nullable(timestampSchema);
318
+ const countSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
319
+ /**
320
+ * What every admin list answers besides its rows: how many rows match the search and filter
321
+ * across every page, and how many match the search under each filter.
322
+ */
323
+ function listTotals(filters) {
324
+ return {
325
+ total: countSchema,
326
+ counts: v.object(zipObject(filters, filters.map(() => countSchema)))
327
+ };
328
+ }
329
+ const adminErrorCodeSchema = v.picklist([
330
+ "bad_request",
331
+ "unauthorized",
332
+ "forbidden",
333
+ "not_found",
334
+ "rate_limited",
335
+ "invalid_enrollment_transition",
336
+ "last_admin_required",
337
+ "self_admin_action_forbidden",
338
+ "email_regeneration_unavailable",
339
+ "mfa_required"
340
+ ]);
341
+ const adminErrorResponseSchema = v.object({ error: v.object({ code: adminErrorCodeSchema }) });
342
+ const enrollmentStatusSchema = v.picklist([
343
+ "pending",
344
+ "approved",
345
+ "rejected",
346
+ "revoked"
347
+ ]);
348
+ const enrollmentSchema = v.object({
349
+ id: v.string(),
350
+ email: v.pipe(v.string(), v.email()),
351
+ name: v.nullable(v.string()),
352
+ reason: v.nullable(v.string()),
353
+ status: enrollmentStatusSchema,
354
+ requestedAt: timestampSchema,
355
+ reviewedAt: nullableTimestampSchema,
356
+ reviewedBy: v.nullable(v.string()),
357
+ /** The reviewer's name, in lists, while the server still knows them. */
358
+ reviewerName: v.optional(v.nullable(v.string())),
359
+ reviewNote: v.nullable(v.string()),
360
+ approvedUserId: v.nullable(v.string()),
361
+ requestRevision: v.pipe(v.number(), v.integer(), v.minValue(1))
362
+ });
363
+ const enrollmentsResponseSchema = v.object({
364
+ enrollments: v.array(enrollmentSchema),
365
+ ...listTotals(enrollmentStatusSchema.options)
366
+ });
367
+ const enrollmentReviewResponseSchema = v.object({ enrollment: enrollmentSchema });
368
+ const cloudAdminSessionResponseSchema = v.object({ user: cloudIdentitySchema });
369
+ const cloudAdminUserSchema = v.object({
370
+ ...cloudPersonSchema.entries,
371
+ role: v.optional(v.string()),
372
+ banned: v.nullable(v.boolean()),
373
+ banReason: v.optional(v.nullable(v.string())),
374
+ createdAt: timestampSchema,
375
+ /** An authenticator app or a passkey confirms this account's sign-ins. */
376
+ twoStep: v.boolean(),
377
+ /** When one of the account's sessions was last used, or null when none is left. */
378
+ lastActiveAt: nullableTimestampSchema,
379
+ workspaceCount: countSchema
380
+ });
381
+ /** Which accounts a list of people shows. */
382
+ const cloudAdminUserFilterSchema = v.picklist([
383
+ "all",
384
+ "administrators",
385
+ "suspended",
386
+ "without-two-step"
387
+ ]);
388
+ const cloudAdminUsersResponseSchema = v.object({
389
+ users: v.array(cloudAdminUserSchema),
390
+ ...listTotals(cloudAdminUserFilterSchema.options)
391
+ });
392
+ const cloudAdminUserDetailSchema = v.object({
393
+ user: v.object({
394
+ ...cloudAdminUserSchema.entries,
395
+ emailVerified: v.boolean()
396
+ }),
397
+ methods: v.array(v.object({
398
+ provider: v.string(),
399
+ createdAt: timestampSchema
400
+ })),
401
+ authenticator: v.boolean(),
402
+ passkeyCount: countSchema,
403
+ sessions: v.array(cloudAccountSessionSchema),
404
+ signIns: v.array(cloudSignInSchema),
405
+ workspaces: v.array(v.object({
406
+ id: v.string(),
407
+ name: v.string(),
408
+ role: workspaceRoleSchema,
409
+ memberCount: countSchema,
410
+ joinedAt: timestampSchema
411
+ }))
412
+ });
413
+ const adminMutationResponseSchema = v.object({ ok: v.literal(true) });
414
+ const transactionalEmailAdminSchema = v.object({
415
+ id: v.string(),
416
+ kind: v.string(),
417
+ recipientEmailNormalized: v.pipe(v.string(), v.email()),
418
+ status: v.string(),
419
+ attemptCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
420
+ nextAttemptAt: timestampSchema,
421
+ transport: v.nullable(v.string()),
422
+ transportMessageId: v.nullable(v.string()),
423
+ lastErrorCode: v.nullable(v.string()),
424
+ createdAt: timestampSchema,
425
+ acceptedAt: nullableTimestampSchema,
426
+ regeneratable: v.boolean()
427
+ });
428
+ /** Which messages a list of email shows, by how their delivery went. */
429
+ const cloudAdminEmailFilterSchema = v.picklist([
430
+ "all",
431
+ "sent",
432
+ "waiting",
433
+ "failed"
434
+ ]);
435
+ const adminEmailResponseSchema = v.object({
436
+ messages: v.array(transactionalEmailAdminSchema),
437
+ ...listTotals(cloudAdminEmailFilterSchema.options)
438
+ });
439
+ /** Who or what an event names; `name` is null once the server no longer knows it. */
440
+ const auditPartySchema = v.object({
441
+ id: v.string(),
442
+ name: v.nullable(v.string())
443
+ });
444
+ const adminAuditEventSchema = v.object({
445
+ id: v.string(),
446
+ actor: auditPartySchema,
447
+ action: v.string(),
448
+ /** What the event is about: an account, an access request, or an email. */
449
+ subject: v.object({
450
+ ...auditPartySchema.entries,
451
+ type: v.string()
452
+ }),
453
+ metadata: v.unknown(),
454
+ createdAt: timestampSchema
455
+ });
456
+ /** Which events a list of activity shows, by what they are about. */
457
+ const cloudAdminAuditFilterSchema = v.picklist([
458
+ "all",
459
+ "accounts",
460
+ "requests",
461
+ "email"
462
+ ]);
463
+ const adminAuditResponseSchema = v.object({
464
+ events: v.array(adminAuditEventSchema),
465
+ ...listTotals(cloudAdminAuditFilterSchema.options)
466
+ });
467
+ const adminOperationsResponseSchema = v.object({
468
+ deployment: v.picklist(["official", "self-hosted"]),
469
+ enrollmentMode: v.picklist([
470
+ "open",
471
+ "approval",
472
+ "closed"
473
+ ]),
474
+ emailTransport: v.picklist([
475
+ "none",
476
+ "smtp",
477
+ "cloudflare"
478
+ ]),
479
+ pendingEnrollment: v.pipe(v.number(), v.integer(), v.minValue(0)),
480
+ pendingEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
481
+ failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
482
+ accounts: countSchema,
483
+ workspaces: countSchema,
484
+ documents: countSchema,
485
+ storedBytes: countSchema
486
+ });
487
+ //#endregion
488
+ //#region src/contract/documents.ts
489
+ const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1073741824;
490
+ const checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/));
491
+ /** The most images one revision, or one request for image uploads, may name. */
492
+ const CLOUD_MAX_DOCUMENT_IMAGES = 1e4;
493
+ const imageNameSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9._-]{1,128}$/));
494
+ const objectDownloadSchema = v.object({
495
+ url: v.pipe(v.string(), v.url()),
496
+ method: v.literal("GET"),
497
+ headers: v.record(v.string(), v.string()),
498
+ expiresAt: v.string()
499
+ });
500
+ /** An image a stored revision uses, where to download it, and what to check it against. */
501
+ const documentImageDownloadSchema = v.object({
502
+ name: imageNameSchema,
503
+ checksum: checksumSchema,
504
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
505
+ download: objectDownloadSchema
506
+ });
507
+ /** Where to download an image a document uses, found by its checksum. */
508
+ const documentImageLinkSchema = v.object({
509
+ checksum: checksumSchema,
510
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
511
+ download: objectDownloadSchema
512
+ });
513
+ /** The images a live room names, by checksum, that a peer needs links for. */
514
+ const requestImageLinksSchema = v.object({ checksums: v.pipe(v.array(checksumSchema), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
515
+ const documentPermissionSchema = v.picklist([
516
+ "view",
517
+ "comment",
518
+ "edit"
519
+ ]);
520
+ const documentAccessSourceSchema = v.picklist([
521
+ "owner",
522
+ "workspace",
523
+ "direct-grant"
524
+ ]);
525
+ const documentAccessSchema = v.object({
526
+ permission: documentPermissionSchema,
527
+ canManageSharing: v.boolean(),
528
+ sources: v.array(documentAccessSourceSchema),
529
+ /**
530
+ * The revision the document holds now, null before its first save; servers from before snapshot
531
+ * links leave it out.
532
+ */
533
+ currentRevisionId: v.optional(v.nullable(v.pipe(v.string(), v.uuid())))
534
+ });
535
+ const documentSummarySchema = v.object({
536
+ id: v.pipe(v.string(), v.uuid()),
537
+ workspaceId: v.pipe(v.string(), v.uuid()),
538
+ name: v.string(),
539
+ currentRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
540
+ version: v.number(),
541
+ createdAt: v.string(),
542
+ updatedAt: v.string()
543
+ });
544
+ /** A document someone granted the person directly, in a workspace they are not a member of. */
545
+ const sharedDocumentSchema = v.object({
546
+ ...documentSummarySchema.entries,
547
+ workspaceName: v.string(),
548
+ permission: documentPermissionSchema,
549
+ sharedBy: v.nullable(v.object({ name: v.string() })),
550
+ sharedAt: v.string()
551
+ });
552
+ const documentDownloadSchema = v.object({
553
+ document: documentSummarySchema,
554
+ revisionId: v.pipe(v.string(), v.uuid()),
555
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
556
+ checksum: checksumSchema,
557
+ contentType: v.string(),
558
+ download: objectDownloadSchema,
559
+ /** The images the stored file leaves out, which a client puts back under their names. */
560
+ images: v.pipe(v.array(documentImageDownloadSchema), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES))
561
+ });
562
+ const cloudActorSchema = v.object({
563
+ userId: v.string(),
564
+ email: v.pipe(v.string(), v.email()),
565
+ name: v.string()
566
+ });
567
+ const cloudSessionSchema = v.object({ user: cloudActorSchema });
568
+ const workspaceUsageSchema = v.object({
569
+ bytesUsed: v.pipe(v.number(), v.integer(), v.minValue(0)),
570
+ objectCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
571
+ documentCount: v.pipe(v.number(), v.integer(), v.minValue(0))
572
+ });
573
+ const createDocumentSchema = v.object({
574
+ id: v.optional(v.pipe(v.string(), v.uuid())),
575
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255))
576
+ });
577
+ v.object({
578
+ baseRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
579
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)),
580
+ checksum: checksumSchema,
581
+ contentType: v.literal("application/octet-stream")
582
+ });
583
+ const imageSizeSchema = v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES));
584
+ /** Where a client puts an object: one presigned PUT, or the parts of a multipart upload. */
585
+ const objectUploadSchema = v.variant("kind", [v.object({
586
+ kind: v.literal("single"),
587
+ url: v.pipe(v.string(), v.url()),
588
+ method: v.literal("PUT"),
589
+ headers: v.record(v.string(), v.string()),
590
+ expiresAt: v.string()
591
+ }), v.object({
592
+ kind: v.literal("multipart"),
593
+ uploadId: v.string(),
594
+ partSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
595
+ parts: v.array(v.object({
596
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1)),
597
+ url: v.pipe(v.string(), v.url()),
598
+ method: v.literal("PUT"),
599
+ headers: v.record(v.string(), v.string())
600
+ })),
601
+ expiresAt: v.string()
602
+ })]);
603
+ /** An upload the server offers for an image the workspace lacks. */
604
+ const imageUploadOfferSchema = v.object({
605
+ checksum: checksumSchema,
606
+ uploadId: v.pipe(v.string(), v.uuid()),
607
+ upload: objectUploadSchema
608
+ });
609
+ v.object({ images: v.pipe(v.array(v.object({
610
+ checksum: checksumSchema,
611
+ byteSize: imageSizeSchema
612
+ })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
613
+ const completedUploadPartSchema = v.object({
614
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1e4)),
615
+ etag: v.pipe(v.string(), v.minLength(1), v.maxLength(255))
616
+ });
617
+ const commitUploadSchema = v.object({
618
+ checksum: checksumSchema,
619
+ /** The document title captured with this revision; omitted by older clients. */
620
+ name: v.optional(createDocumentSchema.entries.name),
621
+ multipart: v.optional(v.object({
622
+ uploadId: v.pipe(v.string(), v.minLength(1)),
623
+ parts: v.pipe(v.array(completedUploadPartSchema), v.minLength(1), v.maxLength(1e4))
624
+ })),
625
+ /** The images the uploaded file leaves out, each stored in the workspace or uploaded before. */
626
+ images: v.optional(v.pipe(v.array(v.object({
627
+ name: imageNameSchema,
628
+ checksum: checksumSchema
629
+ })), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)), [])
630
+ });
631
+ v.object({ uploads: v.pipe(v.array(v.object({
632
+ uploadId: v.pipe(v.string(), v.uuid()),
633
+ checksum: checksumSchema,
634
+ multipart: commitUploadSchema.entries.multipart
635
+ })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
636
+ //#endregion
637
+ //#region src/contract/collaboration.ts
638
+ const collaborationPrincipalSchema = v.variant("kind", [v.object({
639
+ kind: v.literal("user"),
640
+ userId: v.string(),
641
+ name: v.string(),
642
+ email: v.pipe(v.string(), v.email())
643
+ }), v.object({
644
+ kind: v.literal("guest"),
645
+ guestId: v.string(),
646
+ name: v.string()
647
+ })]);
648
+ v.object({
649
+ kind: v.picklist(["user", "guest"]),
650
+ id: v.string(),
651
+ name: v.string(),
652
+ permission: documentPermissionSchema
653
+ });
654
+ const collaborationTicketSchema = v.object({
655
+ token: v.string(),
656
+ provider: v.optional(v.picklist(["trystero", "relay"])),
657
+ serverURL: v.optional(v.pipe(v.string(), v.url())),
658
+ documentId: v.pipe(v.string(), v.uuid()),
659
+ roomId: v.string(),
660
+ roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),
661
+ principal: collaborationPrincipalSchema,
662
+ permission: documentPermissionSchema,
663
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
664
+ expiresAt: v.string(),
665
+ serverEnforcedWrites: v.boolean()
666
+ });
667
+ //#endregion
668
+ //#region src/contract/entitlements.ts
669
+ const workspaceEntitlementsSchema = v.object({
670
+ features: v.object({
671
+ links: v.boolean(),
672
+ guestView: v.boolean(),
673
+ guestEdit: v.boolean(),
674
+ guestPresence: v.boolean(),
675
+ collaboration: v.boolean(),
676
+ revisionHistory: v.boolean(),
677
+ cloudAI: v.optional(v.boolean(), false)
678
+ }),
679
+ limits: v.object({
680
+ maximumFileBytes: v.pipe(v.number(), v.integer(), v.minValue(1)),
681
+ maximumStorageBytes: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
682
+ maximumParticipants: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
683
+ monthlyCreditAllowance: v.optional(v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0))), null)
684
+ }),
685
+ usage: v.object({
686
+ committedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0)),
687
+ reservedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0))
688
+ })
689
+ });
690
+ const CLOUD_DISCOVERY_PATH = "/.well-known/pairdraw";
691
+ const cloudDeploymentSchema = v.picklist(["official", "self-hosted"]);
692
+ const cloudAuthenticationSchema = v.object({
693
+ emailPassword: v.optional(v.object({
694
+ signIn: v.boolean(),
695
+ signUp: v.boolean(),
696
+ minimumPasswordLength: v.pipe(v.number(), v.integer(), v.minValue(8)),
697
+ captcha: v.optional(v.object({
698
+ provider: v.literal("cloudflare-turnstile"),
699
+ siteKey: v.pipe(v.string(), v.trim(), v.minLength(1))
700
+ }))
701
+ })),
702
+ socialProviders: v.array(v.picklist(["apple", "google"])),
703
+ enterpriseSSO: v.boolean(),
704
+ enrollmentMode: v.optional(v.picklist([
705
+ "open",
706
+ "approval",
707
+ "closed"
708
+ ]), "open"),
709
+ mfa: v.optional(v.object({
710
+ deploymentAdminRequired: v.boolean(),
711
+ totp: v.boolean(),
712
+ passkeys: v.boolean(),
713
+ recoveryCodes: v.boolean()
714
+ }))
715
+ });
716
+ const cloudCapabilitiesSchema = v.object({
717
+ documents: v.boolean(),
718
+ workspaces: v.boolean(),
719
+ collaboration: v.boolean()
720
+ });
721
+ /** A released editor version, `major.minor.patch`. */
722
+ const cloudEditorVersionSchema = v.pipe(v.string(), v.regex(/^\d+\.\d+\.\d+$/));
723
+ /**
724
+ * Whether editors offer this server to everyone, and from which editor version on. Only the
725
+ * official server's listing is read: it turns the Cloud entry points on without an editor release,
726
+ * and an editor older than the minimum keeps them hidden.
727
+ */
728
+ const cloudListingSchema = v.object({ minimumEditorVersion: cloudEditorVersionSchema });
729
+ const cloudDiscoverySchema = v.object({
730
+ protocolVersion: v.literal("1"),
731
+ deployment: cloudDeploymentSchema,
732
+ apiURL: v.pipe(v.string(), v.url()),
733
+ authURL: v.pipe(v.string(), v.url()),
734
+ /** Whether the server's own editor works with files on this device without signing in. */
735
+ localEditor: v.optional(v.boolean(), true),
736
+ authentication: cloudAuthenticationSchema,
737
+ capabilities: cloudCapabilitiesSchema,
738
+ listing: v.optional(cloudListingSchema),
739
+ /** The AI service editors reach with Cloud-signed tokens; absent when the deployment has none. */
740
+ ai: v.optional(cloudAIDiscoverySchema),
741
+ /** Where people manage their plan and buy credits; absent when the deployment does not bill. */
742
+ billing: v.optional(cloudBillingDiscoverySchema)
743
+ });
744
+ /** The server's own address, where its editor and pages are, from its auth API's. */
745
+ function cloudServerOrigin(discovery) {
746
+ return new URL(discovery.authURL).origin;
747
+ }
748
+ //#endregion
749
+ //#region src/contract/sharing.ts
750
+ const documentShareSchema = v.object({
751
+ id: v.pipe(v.string(), v.uuid()),
752
+ documentId: v.pipe(v.string(), v.uuid()),
753
+ permission: documentPermissionSchema,
754
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
755
+ createdBy: v.string(),
756
+ createdAt: v.string(),
757
+ updatedAt: v.string(),
758
+ expiresAt: v.nullable(v.string()),
759
+ revokedAt: v.nullable(v.string()),
760
+ lastUsedAt: v.nullable(v.string()),
761
+ /**
762
+ * The revision a snapshot link shows, frozen as it was shared, or null for a live link that
763
+ * opens the document's room. Servers that predate snapshots leave it out.
764
+ */
765
+ revisionId: v.optional(v.nullable(v.pipe(v.string(), v.uuid())), null)
766
+ });
767
+ /**
768
+ * Which revision a snapshot link pins: the document's current one, or one of its revisions by ID.
769
+ * A snapshot link is always view-only and never opens the document's room.
770
+ */
771
+ const shareSnapshotSchema = v.union([v.literal("current"), v.pipe(v.string(), v.uuid())]);
772
+ /** When a link stops working, as an ISO timestamp; `null` keeps it working until revoked. */
773
+ const shareExpirySchema = v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp())));
774
+ v.pipe(v.object({
775
+ permission: documentPermissionSchema,
776
+ expiresAt: shareExpirySchema,
777
+ /** Makes a snapshot link to this revision instead of a live link. */
778
+ snapshot: v.optional(shareSnapshotSchema)
779
+ }), v.check((input) => input.snapshot === void 0 || input.permission === "view", "A snapshot link only lets people view"));
780
+ v.object({
781
+ permission: v.optional(documentPermissionSchema),
782
+ expiresAt: shareExpirySchema,
783
+ /** Pins a snapshot link to another revision, as Update snapshot does; live links refuse it. */
784
+ snapshot: v.optional(shareSnapshotSchema)
785
+ });
786
+ const resolveDocumentShareSchema = v.object({
787
+ secret: v.pipe(v.string(), v.minLength(32), v.maxLength(128)),
788
+ guestName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
789
+ guestId: v.optional(v.pipe(v.string(), v.minLength(16), v.maxLength(128)))
790
+ });
791
+ v.object({
792
+ ...resolveDocumentShareSchema.entries,
793
+ ...requestImageLinksSchema.entries
794
+ });
795
+ const resolvedDocumentShareSchema = v.object({
796
+ documentId: v.pipe(v.string(), v.uuid()),
797
+ permission: documentPermissionSchema,
798
+ principal: collaborationPrincipalSchema,
799
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
800
+ /** The revision a snapshot link shows; null for a live link. */
801
+ revisionId: v.optional(v.nullable(v.pipe(v.string(), v.uuid())), null)
802
+ });
803
+ const cloudUserProfileSchema = v.object({
804
+ id: v.string(),
805
+ name: v.string(),
806
+ email: v.pipe(v.string(), v.email()),
807
+ image: v.nullable(v.pipe(v.string(), v.url()))
808
+ });
809
+ const documentGrantSchema = v.object({
810
+ id: v.pipe(v.string(), v.uuid()),
811
+ documentId: v.pipe(v.string(), v.uuid()),
812
+ userId: v.string(),
813
+ permission: documentPermissionSchema,
814
+ createdBy: v.string(),
815
+ createdAt: v.string(),
816
+ updatedAt: v.string()
817
+ });
818
+ /** What accepting an invitation gave: access to a document, or a place in a workspace. */
819
+ const acceptedInvitationSchema = v.variant("kind", [v.object({
820
+ kind: v.literal("document"),
821
+ grant: documentGrantSchema
822
+ }), v.object({
823
+ kind: v.literal("workspace"),
824
+ workspaceId: v.pipe(v.string(), v.uuid()),
825
+ role: workspaceRoleSchema
826
+ })]);
827
+ v.object({ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()) });
828
+ v.object({ permission: documentPermissionSchema });
829
+ v.object({
830
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
831
+ permission: documentPermissionSchema
832
+ });
833
+ v.object({ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128)) });
834
+ const createInvitationContinuationSchema = v.object({
835
+ invitationId: v.pipe(v.string(), v.uuid()),
836
+ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))
837
+ });
838
+ const invitationContinuationSchema = v.object({ id: v.pipe(v.string(), v.minLength(16), v.maxLength(128)) });
839
+ const invitationPreviewFields = {
840
+ inviterName: v.string(),
841
+ expiresAt: v.string(),
842
+ recipientHint: v.string()
843
+ };
844
+ /** What an invitation link opens: one document, or a whole workspace. */
845
+ const invitationPreviewSchema = v.variant("kind", [v.object({
846
+ kind: v.literal("document"),
847
+ documentName: v.string(),
848
+ permission: documentPermissionSchema,
849
+ ...invitationPreviewFields
850
+ }), v.object({
851
+ kind: v.literal("workspace"),
852
+ workspaceName: v.string(),
853
+ role: workspaceRoleSchema,
854
+ ...invitationPreviewFields
855
+ })]);
856
+ const documentInvitationSchema = v.object({
857
+ id: v.pipe(v.string(), v.uuid()),
858
+ documentId: v.pipe(v.string(), v.uuid()),
859
+ email: v.pipe(v.string(), v.email()),
860
+ permission: documentPermissionSchema,
861
+ invitedBy: v.string(),
862
+ invitedAt: v.string(),
863
+ expiresAt: v.string(),
864
+ acceptedAt: v.nullable(v.string())
865
+ });
866
+ const handleSchema = v.pipe(v.string(), v.trim(), v.toLowerCase(), v.regex(/^[a-z0-9](?:[a-z0-9-]{1,30}[a-z0-9])$/));
867
+ /** A document a public workspace lists, which anyone may open read-only. */
868
+ const publicDocumentSummarySchema = v.object({
869
+ id: v.pipe(v.string(), v.uuid()),
870
+ name: v.string(),
871
+ updatedAt: v.string()
872
+ });
873
+ const publicWorkspaceSchema = v.object({
874
+ id: v.pipe(v.string(), v.uuid()),
875
+ name: v.string(),
876
+ slug: v.string(),
877
+ documents: v.array(publicDocumentSummarySchema)
878
+ });
879
+ /** What anyone sees at `/u/<handle>`: who the person is and the workspaces they made public. */
880
+ const publicProfileSchema = v.object({
881
+ handle: v.string(),
882
+ name: v.string(),
883
+ image: v.nullable(v.string()),
884
+ bio: v.nullable(v.string()),
885
+ workspaces: v.array(publicWorkspaceSchema)
886
+ });
887
+ /** A workspace the signed-in person administers, and whether it is on their public profile. */
888
+ const publicProfileWorkspaceSettingSchema = v.object({
889
+ id: v.pipe(v.string(), v.uuid()),
890
+ name: v.string(),
891
+ public: v.boolean()
892
+ });
893
+ /** The signed-in person's own public profile settings; a null handle means no public profile. */
894
+ const publicProfileSettingsSchema = v.object({
895
+ handle: v.nullable(v.string()),
896
+ bio: v.nullable(v.string()),
897
+ workspaces: v.array(publicProfileWorkspaceSettingSchema)
898
+ });
899
+ v.object({
900
+ handle: v.nullable(handleSchema),
901
+ bio: v.optional(v.nullable(v.pipe(v.string(), v.trim(), v.maxLength(280))))
902
+ });
903
+ v.object({ public: v.boolean() });
904
+ /** A public document as anyone may download it. */
905
+ const publicDocumentDownloadSchema = v.object({ document: documentDownloadSchema });
906
+ const DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH = 1e3;
907
+ /** A checkpoint the server kept on its own, or a version someone named. */
908
+ const documentVersionKindSchema = v.picklist(["checkpoint", "named"]);
909
+ const documentVersionSchema = v.object({
910
+ id: v.pipe(v.string(), v.uuid()),
911
+ revisionId: v.pipe(v.string(), v.uuid()),
912
+ kind: documentVersionKindSchema,
913
+ name: v.nullable(v.string()),
914
+ description: v.nullable(v.string()),
915
+ createdAt: v.string(),
916
+ /** Who made the version: the author of a checkpoint's save, or who named or restored it. */
917
+ createdBy: v.object({
918
+ id: v.string(),
919
+ name: v.nullable(v.string())
920
+ }),
921
+ /** The version this one restored, while that version is still in the history. */
922
+ restoredFromVersionId: v.nullable(v.pipe(v.string(), v.uuid())),
923
+ /** Whether the document holds this version now. */
924
+ current: v.boolean()
925
+ });
926
+ const documentVersionsSchema = v.object({
927
+ versions: v.array(documentVersionSchema),
928
+ /** Pass as `before` for the next, older page; null on the last one. */
929
+ nextCursor: v.nullable(v.pipe(v.string(), v.uuid()))
930
+ });
931
+ const versionNameSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100));
932
+ const versionDescriptionSchema = v.pipe(v.string(), v.trim(), v.maxLength(DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH));
933
+ v.object({
934
+ name: versionNameSchema,
935
+ description: v.optional(versionDescriptionSchema, "")
936
+ });
937
+ v.object({
938
+ name: v.nullable(versionNameSchema),
939
+ description: v.optional(versionDescriptionSchema, "")
940
+ });
941
+ v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255)) });
942
+ const documentVersionResponseSchema = v.object({ version: documentVersionSchema });
943
+ /** A version with where to download it, so a link to it can show it without the history. */
944
+ const documentVersionDownloadSchema = v.object({
945
+ document: documentDownloadSchema,
946
+ version: documentVersionSchema
947
+ });
948
+ const restoredDocumentSchema = v.object({
949
+ document: documentSummarySchema,
950
+ version: documentVersionSchema
951
+ });
952
+ //#endregion
953
+ //#region src/client/ai.ts
954
+ var CloudAIError = class extends Error {
955
+ status;
956
+ code;
957
+ name = "CloudAIError";
958
+ constructor(status, code) {
959
+ super(`Pairdraw AI request failed with HTTP ${status}`);
960
+ this.status = status;
961
+ this.code = code;
962
+ }
963
+ };
964
+ /** Whether a request can be sent twice: a stream, in `init` or a `Request`, is read by the first. */
965
+ function replayable(input, body) {
966
+ if (input instanceof Request && input.body) return false;
967
+ return !(body instanceof ReadableStream);
968
+ }
969
+ /**
970
+ * Sends each request with a current token. A token the service refuses, for instance one signed
971
+ * by a key Cloud has since replaced, is dropped and a request that can be replayed is sent once
972
+ * more with a new one.
973
+ */
974
+ function cloudAIFetch(tokens, fetch) {
975
+ const send = async (input, init, token) => {
976
+ const headers = new Headers(init?.headers);
977
+ headers.set("Authorization", `Bearer ${token}`);
978
+ return fetch(input, {
979
+ ...init,
980
+ headers
981
+ });
982
+ };
983
+ return async (input, init) => {
984
+ const token = await tokens.token();
985
+ const response = await send(input, init, token);
986
+ if (response.status !== 401) return response;
987
+ tokens.invalidate(token);
988
+ if (!replayable(input, init?.body)) return response;
989
+ return send(input, init, await tokens.token());
990
+ };
991
+ }
992
+ const errorBodySchema = v.pipe(v.string(), v.parseJson(), aiErrorSchema);
993
+ async function parsed(response, schema) {
994
+ const text = await response.text();
995
+ if (!response.ok) {
996
+ const error = v.safeParse(errorBodySchema, text);
997
+ throw new CloudAIError(response.status, error.success ? error.output.error.code : void 0);
998
+ }
999
+ return v.parse(v.pipe(v.string(), v.parseJson(), schema), text);
1000
+ }
1001
+ /** The AI service a Cloud advertises: its model API base URL, catalog, and the wallet. */
1002
+ function createCloudAIClient(options) {
1003
+ const endpoint = options.endpoint.replace(/\/+$/, "");
1004
+ const fetch = cloudAIFetch(options.tokens, options.fetch);
1005
+ return {
1006
+ /** The base URL an OpenAI-compatible client sends chat completions below. */
1007
+ modelBaseURL: `${endpoint}${CLOUD_AI_API_PATHS.base}`,
1008
+ fetch,
1009
+ async catalog() {
1010
+ return parsed(await fetch(`${endpoint}${CLOUD_AI_API_PATHS.catalog}`), aiCatalogSchema);
1011
+ },
1012
+ async wallet() {
1013
+ return parsed(await fetch(`${endpoint}${CLOUD_AI_API_PATHS.wallet}`), aiWalletSchema);
1014
+ }
1015
+ };
1016
+ }
1017
+ //#endregion
1018
+ //#region src/client/auth/navigation.ts
1019
+ /** The instance owns authentication; only its own editor may receive the return. */
1020
+ function cloudEditorReturnURL(discovery, value) {
1021
+ const destination = new URL(value);
1022
+ if (!["https:", "http:"].includes(destination.protocol) || destination.origin !== cloudServerOrigin(discovery) || destination.username || destination.password) throw new Error("Authentication return URL must belong to this instance editor");
1023
+ return withoutFragment(destination.href);
1024
+ }
1025
+ /**
1026
+ * The server's sign-in page, coming back to `returnURL` on its editor afterwards. A `provider`
1027
+ * starts that provider's sign-in at once, while the server's pages still handle two-step sign-in
1028
+ * and approval before the return.
1029
+ */
1030
+ function cloudSignInURL(discovery, returnURL, provider) {
1031
+ const offered = provider && discovery.authentication.socialProviders.includes(provider);
1032
+ return withQuery(new URL("/auth/sign-in", discovery.authURL).href, {
1033
+ redirect: withQuery("/auth/return", { editor: cloudEditorReturnURL(discovery, returnURL) }),
1034
+ provider: offered ? provider : void 0
1035
+ });
1036
+ }
1037
+ /** Accept only same-origin application paths for post-authentication navigation. */
1038
+ function cloudRedirectPath(value, fallback = "/app") {
1039
+ if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//")) return fallback;
1040
+ const origin = "https://redirect.invalid";
1041
+ const url = new URL(value, origin);
1042
+ if (url.origin !== origin) return fallback;
1043
+ return `${url.pathname}${url.search}${url.hash}`;
1044
+ }
1045
+ //#endregion
1046
+ //#region src/client/response.ts
1047
+ const cloudErrorResponseSchema = v.object({ error: v.object({ code: v.string() }) });
1048
+ var CloudAPIError = class extends Error {
1049
+ status;
1050
+ code;
1051
+ name = "CloudAPIError";
1052
+ constructor(message, status, code) {
1053
+ super(message);
1054
+ this.status = status;
1055
+ this.code = code;
1056
+ }
1057
+ };
1058
+ async function responseBody(response, onDiagnostic) {
1059
+ if (response.ok) return response.status === 204 ? null : response.json();
1060
+ let code;
1061
+ try {
1062
+ const body = v.safeParse(cloudErrorResponseSchema, await response.json());
1063
+ if (body.success) code = body.output.error.code;
1064
+ } catch (error) {
1065
+ onDiagnostic?.("Cloud API error response was not JSON", error);
1066
+ }
1067
+ throw new CloudAPIError(`Pairdraw Cloud request failed with HTTP ${response.status}`, response.status, code);
1068
+ }
1069
+ async function parseResponse(request, schema, onDiagnostic) {
1070
+ return v.parse(schema, await responseBody(await request, onDiagnostic));
1071
+ }
1072
+ //#endregion
1073
+ //#region src/client/images.ts
1074
+ const imageLinksResponseSchema = v.object({ images: v.array(documentImageLinkSchema) });
1075
+ const imageUploadsResponseSchema = v.object({ uploads: v.array(imageUploadOfferSchema) });
1076
+ /** The images a save uploads apart from the document, and the links a live room loads them by. */
1077
+ function createImageRequests(client, publicClient, onDiagnostic) {
1078
+ return {
1079
+ /** Uploads for the images a save will name that the document's workspace lacks. */
1080
+ async requestImageUploads(documentId, input) {
1081
+ return (await parseResponse(client.documents[":documentId"].images.$post({
1082
+ param: { documentId },
1083
+ json: input
1084
+ }), imageUploadsResponseSchema, onDiagnostic)).uploads;
1085
+ },
1086
+ /** Commits the image uploads a save asked for, once their bytes are in place. */
1087
+ async commitImageUploads(documentId, uploads) {
1088
+ await responseBody(await client.documents[":documentId"].images.commit.$post({
1089
+ param: { documentId },
1090
+ json: { uploads }
1091
+ }), onDiagnostic);
1092
+ },
1093
+ /** Links for images a document's live room names. */
1094
+ async getImageLinks(documentId, checksums) {
1095
+ return (await parseResponse(client.documents[":documentId"].images.links.$post({
1096
+ param: { documentId },
1097
+ json: { checksums }
1098
+ }), imageLinksResponseSchema, onDiagnostic)).images;
1099
+ },
1100
+ /** Links for images a shared document's live room names, as the share's guest. */
1101
+ async getSharedImageLinks(shareId, input, checksums) {
1102
+ return (await parseResponse(publicClient.shares[":shareId"].images.$post({
1103
+ param: { shareId },
1104
+ json: {
1105
+ ...input,
1106
+ checksums
1107
+ }
1108
+ }), imageLinksResponseSchema, onDiagnostic)).images;
1109
+ }
1110
+ };
1111
+ }
1112
+ //#endregion
1113
+ //#region src/client/profiles.ts
1114
+ const settingsResponseSchema = v.object({ profile: publicProfileSettingsSchema });
1115
+ const profileResponseSchema = v.object({ profile: publicProfileSchema });
1116
+ /** Public profiles: the signed-in person's own settings, and anyone's profile and documents. */
1117
+ function createProfileRequests(client, publicClient, onDiagnostic) {
1118
+ return {
1119
+ async getPublicProfileSettings() {
1120
+ return (await parseResponse(client.profile.$get(), settingsResponseSchema, onDiagnostic)).profile;
1121
+ },
1122
+ /** Claims or changes the handle and bio; a null handle removes the public profile. */
1123
+ async updatePublicProfile(input) {
1124
+ return (await parseResponse(client.profile.$put({ json: input }), settingsResponseSchema, onDiagnostic)).profile;
1125
+ },
1126
+ /** Lists a workspace on its administrators' public profiles, or takes it off. */
1127
+ async publishWorkspace(workspaceId, published) {
1128
+ return (await parseResponse(client.workspaces[":workspaceId"].public.$put({
1129
+ param: { workspaceId },
1130
+ json: { public: published }
1131
+ }), settingsResponseSchema, onDiagnostic)).profile;
1132
+ },
1133
+ /** Someone's public profile, or null when no profile has the handle. */
1134
+ async getPublicProfile(handle) {
1135
+ try {
1136
+ return (await parseResponse(publicClient.public.profiles[":handle"].$get({ param: { handle } }), profileResponseSchema, onDiagnostic)).profile;
1137
+ } catch (error) {
1138
+ if (error instanceof CloudAPIError && error.status === 404) return null;
1139
+ throw error;
1140
+ }
1141
+ },
1142
+ /** A document a public profile lists, as anyone may download it. */
1143
+ async getPublicDocument(documentId) {
1144
+ return (await parseResponse(publicClient.public.documents[":documentId"].document.$post({ param: { documentId } }), publicDocumentDownloadSchema, onDiagnostic)).document;
1145
+ }
1146
+ };
1147
+ }
1148
+ //#endregion
1149
+ //#region src/client/workspaces.ts
1150
+ const workspaceResponseSchema = v.object({ workspace: workspaceSummarySchema });
1151
+ const usageResponseSchema = v.object({ usage: workspaceUsageSchema });
1152
+ const entitlementResponseSchema = v.object({ entitlements: workspaceEntitlementsSchema });
1153
+ /** Workspaces, their members, invitations, entitlements, and storage use. */
1154
+ function createWorkspaceRequests(client, onDiagnostic) {
1155
+ return {
1156
+ async listWorkspaces() {
1157
+ return parseResponse(client.workspaces.$get(), workspaceListSchema, onDiagnostic);
1158
+ },
1159
+ async createWorkspace(name) {
1160
+ return (await parseResponse(client.workspaces.$post({ json: { name } }), workspaceResponseSchema, onDiagnostic)).workspace;
1161
+ },
1162
+ async renameWorkspace(workspaceId, name) {
1163
+ return (await parseResponse(client.workspaces[":workspaceId"].$patch({
1164
+ param: { workspaceId },
1165
+ json: { name }
1166
+ }), workspaceResponseSchema, onDiagnostic)).workspace;
1167
+ },
1168
+ /** Deletes an empty workspace; the server refuses one that still holds documents. */
1169
+ async deleteWorkspace(workspaceId) {
1170
+ await responseBody(await client.workspaces[":workspaceId"].$delete({ param: { workspaceId } }), onDiagnostic);
1171
+ },
1172
+ /** The workspace's members, and for administrators its pending invitations. */
1173
+ async listWorkspaceMembers(workspaceId) {
1174
+ return parseResponse(client.workspaces[":workspaceId"].members.$get({ param: { workspaceId } }), workspaceMembersSchema, onDiagnostic);
1175
+ },
1176
+ async inviteToWorkspace(workspaceId, input) {
1177
+ return parseResponse(client.workspaces[":workspaceId"].invitations.$post({
1178
+ param: { workspaceId },
1179
+ json: input
1180
+ }), createdWorkspaceInvitationSchema, onDiagnostic);
1181
+ },
1182
+ /** Sends a waiting invitation again; its earlier link stops working. */
1183
+ async resendWorkspaceInvitation(workspaceId, invitationId) {
1184
+ return parseResponse(client.workspaces[":workspaceId"].invitations[":invitationId"].resend.$post({ param: {
1185
+ workspaceId,
1186
+ invitationId
1187
+ } }), createdWorkspaceInvitationSchema, onDiagnostic);
1188
+ },
1189
+ async revokeWorkspaceInvitation(workspaceId, invitationId) {
1190
+ await responseBody(await client.workspaces[":workspaceId"].invitations[":invitationId"].$delete({ param: {
1191
+ workspaceId,
1192
+ invitationId
1193
+ } }), onDiagnostic);
1194
+ },
1195
+ async updateWorkspaceMember(workspaceId, userId, role) {
1196
+ await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$patch({
1197
+ param: {
1198
+ workspaceId,
1199
+ userId
1200
+ },
1201
+ json: { role }
1202
+ }), onDiagnostic);
1203
+ },
1204
+ /** Removes someone from the workspace; with the person's own id, leaves it. */
1205
+ async removeWorkspaceMember(workspaceId, userId) {
1206
+ await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$delete({ param: {
1207
+ workspaceId,
1208
+ userId
1209
+ } }), onDiagnostic);
1210
+ },
1211
+ async getWorkspaceEntitlements(workspaceId) {
1212
+ return (await parseResponse(client.workspaces[":workspaceId"].entitlements.$get({ param: { workspaceId } }), entitlementResponseSchema, onDiagnostic)).entitlements;
1213
+ },
1214
+ async getUsage(workspaceId) {
1215
+ return (await parseResponse(client.workspaces[":workspaceId"].usage.$get({ param: { workspaceId } }), usageResponseSchema, onDiagnostic)).usage;
1216
+ }
1217
+ };
1218
+ }
1219
+ //#endregion
1220
+ //#region src/client/api.ts
1221
+ const documentsResponseSchema = v.object({ documents: v.array(documentSummarySchema) });
1222
+ const sharedDocumentsResponseSchema = v.object({ documents: v.array(sharedDocumentSchema) });
1223
+ const documentResponseSchema = v.object({ document: documentSummarySchema });
1224
+ const downloadResponseSchema = v.object({ document: documentDownloadSchema });
1225
+ const accessResponseSchema = v.object({ access: documentAccessSchema });
1226
+ const sharesResponseSchema = v.object({ shares: v.array(documentShareSchema) });
1227
+ const shareResponseSchema = v.object({ share: documentShareSchema });
1228
+ const shareCapabilityResponseSchema = v.object({
1229
+ share: documentShareSchema,
1230
+ secret: v.string(),
1231
+ path: v.string()
1232
+ });
1233
+ const grantsResponseSchema = v.object({ grants: v.array(documentGrantSchema) });
1234
+ const grantResponseSchema = v.object({ grant: documentGrantSchema });
1235
+ const acceptedResponseSchema = v.object({ accepted: acceptedInvitationSchema });
1236
+ const invitationPreviewResponseSchema = v.object({ invitation: invitationPreviewSchema });
1237
+ const invitationsResponseSchema = v.object({ invitations: v.array(documentInvitationSchema) });
1238
+ const invitationCapabilityResponseSchema = v.object({
1239
+ invitation: documentInvitationSchema,
1240
+ token: v.string()
1241
+ });
1242
+ const collaborationTicketResponseSchema = v.object({ ticket: collaborationTicketSchema });
1243
+ const resolvedShareResponseSchema = v.object({ resolution: resolvedDocumentShareSchema });
1244
+ const sharedDocumentResponseSchema = v.object({
1245
+ resolution: resolvedDocumentShareSchema,
1246
+ document: documentDownloadSchema
1247
+ });
1248
+ const userLookupResponseSchema = v.object({ user: v.nullable(cloudUserProfileSchema) });
1249
+ const uploadResponseSchema = v.object({
1250
+ id: v.pipe(v.string(), v.uuid()),
1251
+ upload: objectUploadSchema
1252
+ });
1253
+ function apiURL(baseURL) {
1254
+ const url = new URL(baseURL);
1255
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudAPIError("Pairdraw Cloud API URL must use HTTP or HTTPS", 0);
1256
+ url.pathname = url.pathname.replace(/\/$/, "");
1257
+ url.search = "";
1258
+ url.hash = "";
1259
+ return url.href;
1260
+ }
1261
+ function createCloudAPIClient(baseURL, options = {}) {
1262
+ const headers = {
1263
+ "Content-Type": "application/json",
1264
+ ...options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {}
1265
+ };
1266
+ const client = hc(apiURL(baseURL), {
1267
+ fetch: options.fetch,
1268
+ init: {
1269
+ credentials: "include",
1270
+ signal: options.signal,
1271
+ headers
1272
+ }
1273
+ });
1274
+ const publicClient = hc(apiURL(baseURL), {
1275
+ fetch: options.fetch,
1276
+ init: {
1277
+ credentials: "include",
1278
+ signal: options.signal,
1279
+ headers
1280
+ }
1281
+ });
1282
+ return {
1283
+ async getSession() {
1284
+ const response = await client.session.$get();
1285
+ if (response.status === 401) return null;
1286
+ return v.parse(cloudSessionSchema, await responseBody(response, options.onDiagnostic));
1287
+ },
1288
+ /** A short-lived token for the deployment's AI service, on the workspace's behalf. */
1289
+ async requestAIToken(workspaceId) {
1290
+ return parseResponse(client.ai.token.$post({ json: { workspaceId } }), aiTokenSchema, options.onDiagnostic);
1291
+ },
1292
+ async lookupUser(documentId, input) {
1293
+ return (await parseResponse(client.documents[":documentId"].users.lookup.$post({
1294
+ param: { documentId },
1295
+ json: input
1296
+ }), userLookupResponseSchema, options.onDiagnostic)).user;
1297
+ },
1298
+ async getUserProfile(documentId, userId) {
1299
+ return (await parseResponse(client.documents[":documentId"].users[":userId"].$get({ param: {
1300
+ documentId,
1301
+ userId
1302
+ } }), userLookupResponseSchema, options.onDiagnostic)).user;
1303
+ },
1304
+ ...createWorkspaceRequests(client, options.onDiagnostic),
1305
+ ...createProfileRequests(client, publicClient, options.onDiagnostic),
1306
+ ...createImageRequests(client, publicClient, options.onDiagnostic),
1307
+ /** Documents shared with the person directly, outside their workspaces. */
1308
+ async listSharedDocuments() {
1309
+ return (await parseResponse(client["shared-documents"].$get(), sharedDocumentsResponseSchema, options.onDiagnostic)).documents;
1310
+ },
1311
+ async listDocuments(workspaceId) {
1312
+ return (await parseResponse(client.workspaces[":workspaceId"].documents.$get({ param: { workspaceId } }), documentsResponseSchema, options.onDiagnostic)).documents;
1313
+ },
1314
+ async createDocument(workspaceId, input) {
1315
+ return (await parseResponse(client.workspaces[":workspaceId"].documents.$post({
1316
+ param: { workspaceId },
1317
+ json: input
1318
+ }), documentResponseSchema, options.onDiagnostic)).document;
1319
+ },
1320
+ async deleteDocument(documentId) {
1321
+ await responseBody(await client.documents[":documentId"].$delete({ param: { documentId } }), options.onDiagnostic);
1322
+ },
1323
+ async getDocument(documentId) {
1324
+ return (await parseResponse(client.documents[":documentId"].$get({ param: { documentId } }), downloadResponseSchema, options.onDiagnostic)).document;
1325
+ },
1326
+ async getDocumentAccess(documentId) {
1327
+ return (await parseResponse(client.documents[":documentId"].access.$get({ param: { documentId } }), accessResponseSchema, options.onDiagnostic)).access;
1328
+ },
1329
+ async listDocumentShares(documentId) {
1330
+ return (await parseResponse(client.documents[":documentId"].shares.$get({ param: { documentId } }), sharesResponseSchema, options.onDiagnostic)).shares;
1331
+ },
1332
+ async createDocumentShare(documentId, input) {
1333
+ return parseResponse(client.documents[":documentId"].shares.$post({
1334
+ param: { documentId },
1335
+ json: input
1336
+ }), shareCapabilityResponseSchema, options.onDiagnostic);
1337
+ },
1338
+ async updateDocumentShare(documentId, shareId, input) {
1339
+ return (await parseResponse(client.documents[":documentId"].shares[":shareId"].$patch({
1340
+ param: {
1341
+ documentId,
1342
+ shareId
1343
+ },
1344
+ json: input
1345
+ }), shareResponseSchema, options.onDiagnostic)).share;
1346
+ },
1347
+ async rotateDocumentShare(documentId, shareId) {
1348
+ return parseResponse(client.documents[":documentId"].shares[":shareId"].rotate.$post({ param: {
1349
+ documentId,
1350
+ shareId
1351
+ } }), shareCapabilityResponseSchema, options.onDiagnostic);
1352
+ },
1353
+ async revokeDocumentShare(documentId, shareId) {
1354
+ await responseBody(await client.documents[":documentId"].shares[":shareId"].$delete({ param: {
1355
+ documentId,
1356
+ shareId
1357
+ } }), options.onDiagnostic);
1358
+ },
1359
+ async listDocumentGrants(documentId) {
1360
+ return (await parseResponse(client.documents[":documentId"].grants.$get({ param: { documentId } }), grantsResponseSchema, options.onDiagnostic)).grants;
1361
+ },
1362
+ async putDocumentGrant(documentId, userId, input) {
1363
+ return (await parseResponse(client.documents[":documentId"].grants[":userId"].$put({
1364
+ param: {
1365
+ documentId,
1366
+ userId
1367
+ },
1368
+ json: input
1369
+ }), grantResponseSchema, options.onDiagnostic)).grant;
1370
+ },
1371
+ async revokeDocumentGrant(documentId, userId) {
1372
+ await responseBody(await client.documents[":documentId"].grants[":userId"].$delete({ param: {
1373
+ documentId,
1374
+ userId
1375
+ } }), options.onDiagnostic);
1376
+ },
1377
+ async listDocumentInvitations(documentId) {
1378
+ return (await parseResponse(client.documents[":documentId"].invitations.$get({ param: { documentId } }), invitationsResponseSchema, options.onDiagnostic)).invitations;
1379
+ },
1380
+ async createDocumentInvitation(documentId, input) {
1381
+ return parseResponse(client.documents[":documentId"].invitations.$post({
1382
+ param: { documentId },
1383
+ json: input
1384
+ }), invitationCapabilityResponseSchema, options.onDiagnostic);
1385
+ },
1386
+ async createInvitationContinuation(input) {
1387
+ return parseResponse(publicClient.invitations.continuations.$post({ json: input }), invitationContinuationSchema, options.onDiagnostic);
1388
+ },
1389
+ async consumeInvitationContinuation(id) {
1390
+ return parseResponse(publicClient.invitations.continuations[":continuationId"].consume.$post({ param: { continuationId: id } }), createInvitationContinuationSchema, options.onDiagnostic);
1391
+ },
1392
+ async previewInvitation(invitationId, input) {
1393
+ return (await parseResponse(publicClient.invitations[":invitationId"].preview.$post({
1394
+ param: { invitationId },
1395
+ json: input
1396
+ }), invitationPreviewResponseSchema, options.onDiagnostic)).invitation;
1397
+ },
1398
+ /** Accepts a document or workspace invitation, and says which it was. */
1399
+ async acceptInvitation(invitationId, input) {
1400
+ return (await parseResponse(client.invitations[":invitationId"].accept.$post({
1401
+ param: { invitationId },
1402
+ json: input
1403
+ }), acceptedResponseSchema, options.onDiagnostic)).accepted;
1404
+ },
1405
+ async revokeDocumentInvitation(documentId, invitationId) {
1406
+ await responseBody(await client.documents[":documentId"].invitations[":invitationId"].$delete({ param: {
1407
+ documentId,
1408
+ invitationId
1409
+ } }), options.onDiagnostic);
1410
+ },
1411
+ async resolveDocumentShare(shareId, input) {
1412
+ return (await parseResponse(publicClient.shares[":shareId"].resolve.$post({
1413
+ param: { shareId },
1414
+ json: input
1415
+ }), resolvedShareResponseSchema, options.onDiagnostic)).resolution;
1416
+ },
1417
+ async getSharedDocument(shareId, input) {
1418
+ return parseResponse(publicClient.shares[":shareId"].document.$post({
1419
+ param: { shareId },
1420
+ json: input
1421
+ }), sharedDocumentResponseSchema, options.onDiagnostic);
1422
+ },
1423
+ async getSharedCollaborationTicket(shareId, input) {
1424
+ return (await parseResponse(publicClient.shares[":shareId"]["collaboration-ticket"].$post({
1425
+ param: { shareId },
1426
+ json: input
1427
+ }), collaborationTicketResponseSchema, options.onDiagnostic)).ticket;
1428
+ },
1429
+ async getCollaborationTicket(documentId) {
1430
+ return (await parseResponse(client.documents[":documentId"]["collaboration-ticket"].$post({ param: { documentId } }), collaborationTicketResponseSchema, options.onDiagnostic)).ticket;
1431
+ },
1432
+ async createUpload(documentId, input) {
1433
+ return parseResponse(client.documents[":documentId"].uploads.$post({
1434
+ param: { documentId },
1435
+ json: input
1436
+ }), uploadResponseSchema, options.onDiagnostic);
1437
+ },
1438
+ async commitUpload(uploadId, input) {
1439
+ return (await parseResponse(client.uploads[":uploadId"].commit.$post({
1440
+ param: { uploadId },
1441
+ json: {
1442
+ ...input,
1443
+ images: input.images ?? []
1444
+ }
1445
+ }), documentResponseSchema, options.onDiagnostic)).document;
1446
+ },
1447
+ /** A page of the document's version history, newest first. */
1448
+ async listDocumentVersions(documentId, page = {}) {
1449
+ return parseResponse(client.documents[":documentId"].versions.$get({
1450
+ param: { documentId },
1451
+ query: pickBy(page, (value) => value !== void 0)
1452
+ }), documentVersionsSchema, options.onDiagnostic);
1453
+ },
1454
+ async saveDocumentVersion(documentId, input) {
1455
+ return (await parseResponse(client.documents[":documentId"].versions.$post({
1456
+ param: { documentId },
1457
+ json: input
1458
+ }), documentVersionResponseSchema, options.onDiagnostic)).version;
1459
+ },
1460
+ async updateDocumentVersion(documentId, versionId, input) {
1461
+ return (await parseResponse(client.documents[":documentId"].versions[":versionId"].$patch({
1462
+ param: {
1463
+ documentId,
1464
+ versionId
1465
+ },
1466
+ json: input
1467
+ }), documentVersionResponseSchema, options.onDiagnostic)).version;
1468
+ },
1469
+ async getDocumentVersion(documentId, versionId) {
1470
+ return parseResponse(client.documents[":documentId"].versions[":versionId"].$get({ param: {
1471
+ documentId,
1472
+ versionId
1473
+ } }), documentVersionDownloadSchema, options.onDiagnostic);
1474
+ },
1475
+ async restoreDocumentVersion(documentId, versionId) {
1476
+ return parseResponse(client.documents[":documentId"].versions[":versionId"].restore.$post({ param: {
1477
+ documentId,
1478
+ versionId
1479
+ } }), restoredDocumentSchema, options.onDiagnostic);
1480
+ },
1481
+ async duplicateDocumentVersion(documentId, versionId, input) {
1482
+ return (await parseResponse(client.documents[":documentId"].versions[":versionId"].duplicate.$post({
1483
+ param: {
1484
+ documentId,
1485
+ versionId
1486
+ },
1487
+ json: input
1488
+ }), documentResponseSchema, options.onDiagnostic)).document;
1489
+ }
1490
+ };
1491
+ }
1492
+ //#endregion
1493
+ //#region src/client/auth/failure.ts
1494
+ /** The failure a Better Auth error stands for; anything unknown can only be retried later. */
1495
+ function cloudAuthFailure(error) {
1496
+ if (error?.status === 429) return {
1497
+ ok: false,
1498
+ failure: "rate-limited"
1499
+ };
1500
+ switch (error?.code ?? "") {
1501
+ case "INVALID_EMAIL_OR_PASSWORD": return {
1502
+ ok: false,
1503
+ failure: "invalid-credentials"
1504
+ };
1505
+ case "EMAIL_NOT_VERIFIED": return {
1506
+ ok: false,
1507
+ failure: "email-not-verified"
1508
+ };
1509
+ case "PASSWORD_TOO_SHORT": return {
1510
+ ok: false,
1511
+ failure: "password-too-short"
1512
+ };
1513
+ case "PASSWORD_TOO_LONG": return {
1514
+ ok: false,
1515
+ failure: "password-too-long"
1516
+ };
1517
+ case "INVALID_TOKEN": return {
1518
+ ok: false,
1519
+ failure: "invalid-link"
1520
+ };
1521
+ case "SESSION_NOT_FRESH": return {
1522
+ ok: false,
1523
+ failure: "session-not-fresh"
1524
+ };
1525
+ case "AUTH_CANCELLED":
1526
+ case "ERROR_CEREMONY_ABORTED": return {
1527
+ ok: false,
1528
+ failure: "passkey-cancelled"
1529
+ };
1530
+ case "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED": return {
1531
+ ok: false,
1532
+ failure: "passkey-exists"
1533
+ };
1534
+ case "INVALID_CODE":
1535
+ case "INVALID_TWO_FACTOR_CODE":
1536
+ case "INVALID_BACKUP_CODE": return {
1537
+ ok: false,
1538
+ failure: "invalid-code"
1539
+ };
1540
+ default: return {
1541
+ ok: false,
1542
+ failure: error?.code?.startsWith("ERROR_") ? "passkey-unavailable" : "unavailable"
1543
+ };
1544
+ }
1545
+ }
1546
+ //#endregion
1547
+ //#region src/client/auth/client.ts
1548
+ function returnURL() {
1549
+ return withoutFragment(globalThis.location.href);
1550
+ }
1551
+ function authHeaders(options) {
1552
+ const headers = {};
1553
+ if (options.accessToken) headers.Authorization = `Bearer ${options.accessToken}`;
1554
+ if (options.captchaResponse) headers["x-captcha-response"] = options.captchaResponse;
1555
+ return Object.keys(headers).length > 0 ? headers : void 0;
1556
+ }
1557
+ function createCloudAuthClient(discovery, options = {}) {
1558
+ return createAuthClient({
1559
+ baseURL: discovery.authURL,
1560
+ plugins: [
1561
+ deviceAuthorizationClient(),
1562
+ twoFactorClient({ twoFactorPage: "/auth/two-factor" }),
1563
+ passkeyClient()
1564
+ ],
1565
+ fetchOptions: {
1566
+ credentials: "include",
1567
+ customFetchImpl: options.fetch,
1568
+ headers: authHeaders(options)
1569
+ }
1570
+ });
1571
+ }
1572
+ async function signInToCloud(discovery, provider, options = {}) {
1573
+ const callbackURL = options.callbackURL ?? returnURL();
1574
+ if (!discovery.authentication.socialProviders.includes(provider)) throw new Error(`Cloud sign-in provider is unavailable: ${provider}`);
1575
+ const result = await createCloudAuthClient(discovery, { fetch: options.fetch }).signIn.social({
1576
+ provider,
1577
+ callbackURL,
1578
+ errorCallbackURL: callbackURL,
1579
+ disableRedirect: true
1580
+ });
1581
+ if (result.error) throw new Error(result.error.message ?? "Cloud sign-in failed");
1582
+ if (typeof result.data.url !== "string") throw new TypeError("Cloud sign-in response did not include a URL");
1583
+ (options.navigate ?? ((url) => globalThis.location.assign(url)))(result.data.url);
1584
+ }
1585
+ async function signOutFromCloud(discovery, options = {}) {
1586
+ const result = await createCloudAuthClient(discovery, options).signOut();
1587
+ if (result.error) throw new Error(result.error.message ?? "Cloud sign-out failed");
1588
+ }
1589
+ /**
1590
+ * Signs in with an email and password without leaving the app. The token goes on every later
1591
+ * request, so no cookie has to cross from the server to the editor.
1592
+ */
1593
+ async function signInToCloudWithEmail(discovery, input, options = {}) {
1594
+ const result = await createCloudAuthClient(discovery, options).signIn.email({
1595
+ ...input,
1596
+ rememberMe: true
1597
+ }).catch(() => null);
1598
+ if (!result) return cloudAuthFailure(null);
1599
+ if (result.error) return cloudAuthFailure(result.error);
1600
+ if ("twoFactorRedirect" in result.data && result.data.twoFactorRedirect === true) return {
1601
+ ok: true,
1602
+ value: { status: "two-step" }
1603
+ };
1604
+ if (!("token" in result.data) || typeof result.data.token !== "string") return cloudAuthFailure(null);
1605
+ return {
1606
+ ok: true,
1607
+ value: {
1608
+ status: "signed-in",
1609
+ token: result.data.token
1610
+ }
1611
+ };
1612
+ }
1613
+ /** Creates an account; the server emails a link that opens `verifiedURL` once it is confirmed. */
1614
+ async function signUpToCloudWithEmail(discovery, input, options = {}) {
1615
+ const result = await createCloudAuthClient(discovery, options).signUp.email({
1616
+ name: input.name,
1617
+ email: input.email,
1618
+ password: input.password,
1619
+ callbackURL: input.verifiedURL
1620
+ }).catch(() => null);
1621
+ if (!result) return cloudAuthFailure(null);
1622
+ return result.error ? cloudAuthFailure(result.error) : {
1623
+ ok: true,
1624
+ value: void 0
1625
+ };
1626
+ }
1627
+ async function resendCloudVerification(discovery, input, options = {}) {
1628
+ const result = await createCloudAuthClient(discovery, options).sendVerificationEmail({
1629
+ email: input.email,
1630
+ callbackURL: input.verifiedURL
1631
+ }).catch(() => null);
1632
+ if (!result) return cloudAuthFailure(null);
1633
+ return result.error ? cloudAuthFailure(result.error) : {
1634
+ ok: true,
1635
+ value: void 0
1636
+ };
1637
+ }
1638
+ //#endregion
1639
+ //#region src/client/device-authorization.ts
1640
+ const deviceCodeSchema = v.object({
1641
+ device_code: v.string(),
1642
+ user_code: v.string(),
1643
+ verification_uri: v.pipe(v.string(), v.url()),
1644
+ verification_uri_complete: v.pipe(v.string(), v.url()),
1645
+ expires_in: v.pipe(v.number(), v.integer(), v.minValue(1)),
1646
+ interval: v.pipe(v.number(), v.integer(), v.minValue(1))
1647
+ });
1648
+ const deviceTokenSchema = v.object({
1649
+ access_token: v.string(),
1650
+ token_type: v.literal("Bearer"),
1651
+ expires_in: v.pipe(v.number(), v.integer(), v.minValue(1)),
1652
+ scope: v.string()
1653
+ });
1654
+ const deviceErrorSchema = v.object({
1655
+ error: v.string(),
1656
+ error_description: v.optional(v.string())
1657
+ });
1658
+ /** RFC 8628: each `slow_down` adds five seconds to the polling interval. */
1659
+ const SLOW_DOWN_MS = 5e3;
1660
+ var CloudDeviceAuthorizationError = class extends Error {
1661
+ code;
1662
+ name = "CloudDeviceAuthorizationError";
1663
+ constructor(code) {
1664
+ super(`Cloud device authorization ${code}`);
1665
+ this.code = code;
1666
+ }
1667
+ };
1668
+ function abortableSleep(milliseconds, signal) {
1669
+ return new Promise((resolve, reject) => {
1670
+ const timeout = setTimeout(resolve, milliseconds);
1671
+ signal?.addEventListener("abort", () => {
1672
+ clearTimeout(timeout);
1673
+ reject(signal.reason instanceof Error ? signal.reason : new DOMException("Authorization cancelled", "AbortError"));
1674
+ }, { once: true });
1675
+ });
1676
+ }
1677
+ function authEndpoint(discovery, path) {
1678
+ return joinURL(discovery.authURL, path);
1679
+ }
1680
+ async function requestCloudDeviceAuthorization(discovery, connectionId, options = {}) {
1681
+ const response = await (options.fetch ?? globalThis.fetch)(authEndpoint(discovery, "device/code"), {
1682
+ method: "POST",
1683
+ headers: { "Content-Type": "application/json" },
1684
+ body: JSON.stringify({
1685
+ client_id: `pairdraw-desktop:${connectionId}`,
1686
+ scope: "openid profile"
1687
+ })
1688
+ });
1689
+ if (!response.ok) throw new CloudDeviceAuthorizationError("unavailable");
1690
+ return v.parse(deviceCodeSchema, await response.json());
1691
+ }
1692
+ async function pollCloudDeviceToken(discovery, connectionId, authorization, options = {}) {
1693
+ const request = options.fetch ?? globalThis.fetch;
1694
+ const now = options.now ?? Date.now;
1695
+ const sleep = options.sleep ?? abortableSleep;
1696
+ const expiresAt = now() + authorization.expires_in * 1e3;
1697
+ let interval = authorization.interval * 1e3;
1698
+ while (now() < expiresAt) {
1699
+ options.signal?.throwIfAborted();
1700
+ await sleep(interval, options.signal);
1701
+ if (now() >= expiresAt) break;
1702
+ const response = await request(authEndpoint(discovery, "device/token"), {
1703
+ method: "POST",
1704
+ headers: { "Content-Type": "application/json" },
1705
+ body: JSON.stringify({
1706
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1707
+ device_code: authorization.device_code,
1708
+ client_id: `pairdraw-desktop:${connectionId}`
1709
+ }),
1710
+ signal: options.signal
1711
+ });
1712
+ const body = await response.text();
1713
+ if (response.ok) return v.parse(v.pipe(v.string(), v.parseJson(), deviceTokenSchema), body);
1714
+ if (response.status === 429) {
1715
+ interval += SLOW_DOWN_MS;
1716
+ continue;
1717
+ }
1718
+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), deviceErrorSchema), body);
1719
+ if (!parsed.success) throw new CloudDeviceAuthorizationError("unavailable");
1720
+ const error = parsed.output;
1721
+ if (error.error === "authorization_pending") continue;
1722
+ if (error.error === "slow_down") {
1723
+ interval += SLOW_DOWN_MS;
1724
+ continue;
1725
+ }
1726
+ let code = "unavailable";
1727
+ if (error.error === "access_denied") code = "denied";
1728
+ else if (error.error === "expired_token") code = "expired";
1729
+ throw new CloudDeviceAuthorizationError(code);
1730
+ }
1731
+ throw new CloudDeviceAuthorizationError("expired");
1732
+ }
1733
+ //#endregion
1734
+ //#region src/client/discovery.ts
1735
+ const DISCOVERY_TIMEOUT_MS = 1e4;
1736
+ var CloudClientError = class extends Error {
1737
+ cause;
1738
+ reason;
1739
+ constructor(message, cause, reason = "unreachable") {
1740
+ super(message);
1741
+ this.cause = cause;
1742
+ this.reason = reason;
1743
+ this.name = "CloudClientError";
1744
+ }
1745
+ };
1746
+ const discoveryBodySchema = v.pipe(v.string(), v.parseJson(), v.looseObject({}));
1747
+ const protocolSchema = v.looseObject({ protocolVersion: v.string() });
1748
+ function discoveryURL(serverURL) {
1749
+ let url;
1750
+ try {
1751
+ url = new URL(serverURL);
1752
+ } catch (error) {
1753
+ throw new CloudClientError("Pairdraw server URL is invalid", error, "invalid-address");
1754
+ }
1755
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudClientError("Pairdraw server URL must use HTTP or HTTPS", void 0, "invalid-address");
1756
+ url.pathname = CLOUD_DISCOVERY_PATH;
1757
+ url.search = "";
1758
+ url.hash = "";
1759
+ return url;
1760
+ }
1761
+ function parseDiscoveryBody(text) {
1762
+ const body = v.safeParse(discoveryBodySchema, text);
1763
+ if (!body.success) throw new CloudClientError("Pairdraw server discovery is not JSON", body.issues, "not-cloud");
1764
+ const discovery = v.safeParse(cloudDiscoverySchema, body.output);
1765
+ if (discovery.success) return discovery.output;
1766
+ const protocol = v.safeParse(protocolSchema, body.output);
1767
+ const outdated = protocol.success && protocol.output.protocolVersion !== "1";
1768
+ throw new CloudClientError(outdated ? `Pairdraw server speaks protocol ${protocol.output.protocolVersion}` : "Pairdraw server discovery is invalid", discovery.issues, outdated ? "outdated" : "not-cloud");
1769
+ }
1770
+ async function discoverCloud(serverURL, options = {}) {
1771
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
1772
+ const timeoutSignal = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS);
1773
+ const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
1774
+ try {
1775
+ const response = await fetchImplementation(discoveryURL(serverURL), {
1776
+ headers: { Accept: "application/json" },
1777
+ redirect: "follow",
1778
+ signal
1779
+ });
1780
+ if (!response.ok) throw new CloudClientError(`Pairdraw server discovery failed with HTTP ${response.status}`, void 0, response.status >= 500 ? "unreachable" : "not-cloud");
1781
+ return parseDiscoveryBody(await response.text());
1782
+ } catch (error) {
1783
+ if (error instanceof CloudClientError) throw error;
1784
+ if (signal.aborted) throw new CloudClientError("Pairdraw server discovery was cancelled or timed out", error);
1785
+ throw new CloudClientError("Pairdraw server discovery failed", error);
1786
+ }
1787
+ }
1788
+ //#endregion
1789
+ //#region src/client/portal/account.ts
1790
+ function createAccountAPI(call, { account }) {
1791
+ return {
1792
+ accountStatus(signal) {
1793
+ return call((options) => account.status.$get(void 0, options), cloudAccountStatusResponseSchema, signal);
1794
+ },
1795
+ authenticationMethods(signal) {
1796
+ return call((options) => account.authentication.$get(void 0, options), cloudAuthenticationMethodsResponseSchema, signal);
1797
+ },
1798
+ mfaStatus(signal) {
1799
+ return call((options) => account.mfa.$get(void 0, options), cloudMFAStatusResponseSchema, signal);
1800
+ },
1801
+ enableTOTP(password, signal) {
1802
+ return call((options) => account.mfa.totp.enable.$post({ json: { password } }, options), cloudMFAEnableResponseSchema, signal);
1803
+ },
1804
+ verifyTOTP(code, signal) {
1805
+ return call((options) => account.mfa.totp.verify.$post({ json: { code } }, options), cloudMFAVerifyResponseSchema, signal);
1806
+ },
1807
+ verifyRecoveryCode(code, signal) {
1808
+ return call((options) => account.mfa.recovery.verify.$post({ json: { code } }, options), cloudMFAVerifyResponseSchema, signal);
1809
+ },
1810
+ regenerateRecoveryCodes(password, signal) {
1811
+ return call((options) => account.mfa.recovery.regenerate.$post({ json: { password } }, options), cloudMFARecoveryCodesResponseSchema, signal);
1812
+ },
1813
+ disableTOTP(password, signal) {
1814
+ return call((options) => account.mfa.totp.disable.$post({ json: { password } }, options), cloudAccountMutationResponseSchema, signal);
1815
+ },
1816
+ passkeys(signal) {
1817
+ return call((options) => account.mfa.passkeys.$get(void 0, options), cloudPasskeysResponseSchema, signal);
1818
+ },
1819
+ deletePasskey(id, signal) {
1820
+ return call((options) => account.mfa.passkeys.delete.$post({ json: { id } }, options), cloudAccountMutationResponseSchema, signal);
1821
+ },
1822
+ changePassword(currentPassword, newPassword, signal) {
1823
+ return call((options) => account.authentication["change-password"].$post({ json: {
1824
+ currentPassword,
1825
+ newPassword
1826
+ } }, options), cloudAccountMutationResponseSchema, signal);
1827
+ },
1828
+ linkSocial(provider, callbackURL, signal) {
1829
+ return call((options) => account.authentication["link-social"].$post({ json: {
1830
+ provider,
1831
+ callbackURL
1832
+ } }, options), cloudSocialLinkResponseSchema, signal);
1833
+ },
1834
+ profile(signal) {
1835
+ return call((options) => account.profile.$get(void 0, options), cloudProfileResponseSchema, signal);
1836
+ },
1837
+ updateProfile(name, signal) {
1838
+ return call((options) => account.profile.$post({ json: { name } }, options), cloudAccountMutationResponseSchema, signal);
1839
+ },
1840
+ /** Shows `data`, a Base64 PNG or JPEG the page cropped and shrank, as the account's picture. */
1841
+ uploadPicture(data, signal) {
1842
+ return call((options) => account.profile.picture.$put({ json: { data } }, options), cloudPictureResponseSchema, signal);
1843
+ },
1844
+ removePicture(signal) {
1845
+ return call((options) => account.profile.picture.$delete(void 0, options), cloudAccountMutationResponseSchema, signal);
1846
+ },
1847
+ /** Sends a confirmation to the new address; the email changes once it is followed. */
1848
+ changeEmail(newEmail, callbackURL, signal) {
1849
+ return call((options) => account.profile.email.$post({ json: {
1850
+ newEmail,
1851
+ callbackURL
1852
+ } }, options), cloudAccountMutationResponseSchema, signal);
1853
+ },
1854
+ sessions(signal) {
1855
+ return call((options) => account.sessions.$get(void 0, options), cloudAccountSessionsResponseSchema, signal);
1856
+ },
1857
+ revokeSession(sessionId, signal) {
1858
+ return call((options) => account.sessions.revoke.$post({ json: { sessionId } }, options), cloudAccountMutationResponseSchema, signal);
1859
+ },
1860
+ revokeOtherSessions(signal) {
1861
+ return call((options) => account.sessions["revoke-others"].$post(void 0, options), cloudAccountMutationResponseSchema, signal);
1862
+ },
1863
+ signIns(signal) {
1864
+ return call((options) => account["sign-ins"].$get(void 0, options), cloudSignInsResponseSchema, signal);
1865
+ },
1866
+ unlinkAuthenticationMethod(methodId, signal) {
1867
+ return call((options) => account.authentication.unlink.$post({ json: { methodId } }, options), cloudAccountMutationResponseSchema, signal);
1868
+ }
1869
+ };
1870
+ }
1871
+ //#endregion
1872
+ //#region src/client/portal/administration.ts
1873
+ /** The query string for `request`; an empty search asks for everything. */
1874
+ function listQuery(request) {
1875
+ return { query: {
1876
+ search: request.search || void 0,
1877
+ filter: request.filter,
1878
+ limit: request.limit,
1879
+ offset: request.offset
1880
+ } };
1881
+ }
1882
+ function createAdministrationAPI(call, { admin, api }) {
1883
+ return {
1884
+ session(signal) {
1885
+ return call((options) => api.session.$get(void 0, options), cloudAdminSessionResponseSchema, signal);
1886
+ },
1887
+ enrollments(request, signal) {
1888
+ return call((options) => admin.enrollments.$get(listQuery(request), options), enrollmentsResponseSchema, signal);
1889
+ },
1890
+ reviewEnrollment(id, action, note, signal) {
1891
+ return call((options) => admin.enrollments[":id"][action].$post({
1892
+ param: { id },
1893
+ json: { note }
1894
+ }, options), enrollmentReviewResponseSchema, signal);
1895
+ },
1896
+ users(request, signal) {
1897
+ return call((options) => admin.users.$get(listQuery(request), options), cloudAdminUsersResponseSchema, signal);
1898
+ },
1899
+ user(id, signal) {
1900
+ return call((options) => admin.users[":id"].$get({ param: { id } }, options), cloudAdminUserDetailSchema, signal);
1901
+ },
1902
+ userAction(action, userId, reason, signal) {
1903
+ return call((options) => admin.users[action].$post({ json: {
1904
+ userId,
1905
+ reason
1906
+ } }, options), adminMutationResponseSchema, signal);
1907
+ },
1908
+ setAdmin(userId, enabled, signal) {
1909
+ return call((options) => admin.users["set-admin"].$post({ json: {
1910
+ userId,
1911
+ enabled
1912
+ } }, options), adminMutationResponseSchema, signal);
1913
+ },
1914
+ email(request, signal) {
1915
+ return call((options) => admin.email.$get(listQuery(request), options), adminEmailResponseSchema, signal);
1916
+ },
1917
+ regenerateEmail(id, signal) {
1918
+ return call((options) => admin.email[":id"].regenerate.$post({ param: { id } }, options), adminMutationResponseSchema, signal);
1919
+ },
1920
+ audit(request, signal) {
1921
+ return call((options) => admin.audit.$get(listQuery(request), options), adminAuditResponseSchema, signal);
1922
+ },
1923
+ operations(signal) {
1924
+ return call((options) => admin.operations.$get(void 0, options), adminOperationsResponseSchema, signal);
1925
+ }
1926
+ };
1927
+ }
1928
+ //#endregion
1929
+ //#region src/client/portal/request.ts
1930
+ var CloudPortalAPIError = class extends Error {
1931
+ kind;
1932
+ code;
1933
+ name = "CloudPortalAPIError";
1934
+ constructor(kind, code, options) {
1935
+ super(kind, options);
1936
+ this.kind = kind;
1937
+ this.code = code;
1938
+ }
1939
+ };
1940
+ /**
1941
+ * Sends a request and reads its answer the same way for every portal route: transport failures,
1942
+ * missing sessions and permissions, and domain errors become `CloudPortalAPIError`, and a success
1943
+ * body is checked against the contract.
1944
+ */
1945
+ function createCloudCall(options = {}) {
1946
+ const timeoutMs = options.timeoutMs ?? 1e4;
1947
+ return async (send, schema, callerSignal) => {
1948
+ const timeout = AbortSignal.timeout(timeoutMs);
1949
+ const signal = callerSignal ? AbortSignal.any([callerSignal, timeout]) : timeout;
1950
+ let response;
1951
+ try {
1952
+ response = await send({ init: { signal } });
1953
+ } catch (cause) {
1954
+ if (callerSignal?.aborted) throw new CloudPortalAPIError("cancelled", void 0, { cause });
1955
+ if (timeout.aborted) throw new CloudPortalAPIError("timeout", void 0, { cause });
1956
+ throw new CloudPortalAPIError("network", void 0, { cause });
1957
+ }
1958
+ if (response.status === 401) throw new CloudPortalAPIError("authentication-required");
1959
+ let body;
1960
+ try {
1961
+ body = await response.json();
1962
+ } catch (cause) {
1963
+ if (response.status === 403) throw new CloudPortalAPIError("authorization-required");
1964
+ throw new CloudPortalAPIError("protocol", void 0, { cause });
1965
+ }
1966
+ if (!response.ok) {
1967
+ const accountError = v.safeParse(accountSecurityErrorResponseSchema, body);
1968
+ const adminError = v.safeParse(adminErrorResponseSchema, body);
1969
+ let code;
1970
+ if (accountError.success) code = accountError.output.error.code;
1971
+ else if (adminError.success) code = adminError.output.error.code;
1972
+ if (response.status === 403 && (!code || code === "forbidden")) throw new CloudPortalAPIError("authorization-required");
1973
+ throw new CloudPortalAPIError("domain", code);
1974
+ }
1975
+ const parsed = v.safeParse(schema, body);
1976
+ if (!parsed.success) throw new CloudPortalAPIError("protocol", void 0, { cause: parsed.issues });
1977
+ return parsed.output;
1978
+ };
1979
+ }
1980
+ /** Typed clients for the routes the portal calls, all on the server's own address. */
1981
+ function createPortalRouteClients(options = {}) {
1982
+ const origin = options.baseURL ?? globalThis.location.origin;
1983
+ const clientOptions = {
1984
+ fetch: options.fetch,
1985
+ headers: { Accept: "application/json" },
1986
+ init: { credentials: "include" }
1987
+ };
1988
+ return {
1989
+ account: hc(origin, clientOptions).api.account,
1990
+ admin: hc(new URL("/api/admin", origin).href, clientOptions),
1991
+ api: hc(new URL("/api", origin).href, clientOptions)
1992
+ };
1993
+ }
1994
+ //#endregion
1995
+ //#region src/client/portal/client.ts
1996
+ /** The account and administration routes Cloud's own web pages use, validated against the contract. */
1997
+ function createCloudPortalClient(options = {}) {
1998
+ const call = createCloudCall(options);
1999
+ const routes = createPortalRouteClients(options);
2000
+ return {
2001
+ ...createAccountAPI(call, routes),
2002
+ ...createAdministrationAPI(call, routes)
2003
+ };
2004
+ }
2005
+ //#endregion
2006
+ export { CloudAIError, CloudAPIError, CloudClientError, CloudDeviceAuthorizationError, CloudPortalAPIError, cloudAIFetch, cloudAuthFailure, cloudEditorReturnURL, cloudRedirectPath, cloudSignInURL, createCloudAIClient, createCloudAPIClient, createCloudAuthClient, createCloudPortalClient, discoverCloud, pollCloudDeviceToken, requestCloudDeviceAuthorization, resendCloudVerification, signInToCloud, signInToCloudWithEmail, signOutFromCloud, signUpToCloudWithEmail };
2007
+
2008
+ //# sourceMappingURL=client.js.map