@open-pencil/cloud 0.17.0-beta.2 → 0.17.0-beta.5

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 (339) hide show
  1. package/README.md +3 -2
  2. package/dist/bin/server.mjs +1 -1
  3. package/dist/bin/server.mjs.map +1 -1
  4. package/dist/bin/{ai-relay.mjs → services.mjs} +9 -9
  5. package/dist/bin/services.mjs.map +1 -0
  6. package/dist/client.d.ts +525 -66
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +1257 -654
  9. package/dist/client.js.map +1 -1
  10. package/dist/contract.d.ts +2 -2
  11. package/dist/contract.js +2 -2
  12. package/dist/contract2.js +1028 -481
  13. package/dist/contract2.js.map +1 -1
  14. package/dist/email.d.ts +1780 -31
  15. package/dist/email.d.ts.map +1 -1
  16. package/dist/email.js +3556 -325
  17. package/dist/email.js.map +1 -1
  18. package/dist/errors.d.ts +2 -0
  19. package/dist/errors.js +48 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/index.d.ts +929 -72
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index2.d.ts +35 -0
  24. package/dist/index2.d.ts.map +1 -0
  25. package/dist/listen.mjs +802 -927
  26. package/dist/listen.mjs.map +1 -1
  27. package/dist/runtime-cloudflare.d.ts +89 -0
  28. package/dist/runtime-cloudflare.d.ts.map +1 -0
  29. package/dist/runtime-cloudflare.js +15667 -0
  30. package/dist/runtime-cloudflare.js.map +1 -0
  31. package/dist/runtime-node.d.mts +7166 -3101
  32. package/dist/runtime-node.d.mts.map +1 -1
  33. package/dist/runtime-node.mjs +6 -5
  34. package/dist/runtime-node.mjs.map +1 -1
  35. package/dist/server.d.ts +6525 -2205
  36. package/dist/server.d.ts.map +1 -1
  37. package/dist/server.js +12500 -7613
  38. package/dist/server.js.map +1 -1
  39. package/dist/server.mjs +8625 -2878
  40. package/dist/server.mjs.map +1 -1
  41. package/dist/server2.mjs +101 -79
  42. package/dist/server2.mjs.map +1 -1
  43. package/package.json +27 -9
  44. package/src/admin/api/routes.ts +59 -0
  45. package/src/admin/audit/service.ts +27 -8
  46. package/src/admin/documents/service.ts +431 -0
  47. package/src/admin/errors.ts +9 -1
  48. package/src/admin/index.ts +6 -0
  49. package/src/admin/operations/service.ts +7 -0
  50. package/src/admin/reports/service.ts +153 -0
  51. package/src/admin/schema.ts +6 -0
  52. package/src/client/api.ts +28 -461
  53. package/src/client/auth/client.ts +22 -3
  54. package/src/client/auth/navigation.ts +6 -5
  55. package/src/client/billing.ts +80 -0
  56. package/src/client/community.ts +40 -0
  57. package/src/client/discovery.ts +35 -9
  58. package/src/client/documents.ts +160 -0
  59. package/src/client/index.ts +14 -7
  60. package/src/client/portal/account.ts +79 -2
  61. package/src/client/portal/administration.ts +56 -0
  62. package/src/client/portal/request.ts +2 -0
  63. package/src/client/response.ts +21 -0
  64. package/src/client/schema.ts +8 -0
  65. package/src/client/services.ts +118 -0
  66. package/src/client/sharing.ts +262 -0
  67. package/src/client/versions.ts +104 -0
  68. package/src/contract/account.ts +108 -2
  69. package/src/contract/admin/index.ts +67 -3
  70. package/src/contract/billing.ts +166 -0
  71. package/src/contract/collaboration.ts +11 -1
  72. package/src/contract/community.ts +60 -0
  73. package/src/contract/discovery.ts +83 -4
  74. package/src/contract/documents.ts +27 -0
  75. package/src/contract/entitlements.ts +12 -2
  76. package/src/contract/index.ts +114 -39
  77. package/src/contract/links.ts +57 -4
  78. package/src/contract/locale.ts +27 -0
  79. package/src/contract/portal.ts +12 -1
  80. package/src/contract/relay.ts +6 -0
  81. package/src/contract/reports.ts +42 -0
  82. package/src/contract/routes.ts +10 -0
  83. package/src/contract/services.ts +235 -0
  84. package/src/contract/sharing.ts +3 -9
  85. package/src/email/i18n.ts +174 -0
  86. package/src/email/index.ts +13 -2
  87. package/src/email/locales/ar.json +141 -0
  88. package/src/email/locales/de.json +141 -0
  89. package/src/email/locales/es.json +141 -0
  90. package/src/email/locales/fr.json +141 -0
  91. package/src/email/locales/it.json +141 -0
  92. package/src/email/locales/ja.json +141 -0
  93. package/src/email/locales/pl.json +141 -0
  94. package/src/email/locales/pt-br.json +141 -0
  95. package/src/email/locales/ru.json +141 -0
  96. package/src/email/locales/zh-cn.json +141 -0
  97. package/src/email/messages.ts +200 -0
  98. package/src/email/render.ts +138 -246
  99. package/src/email/samples.ts +115 -0
  100. package/src/email/schema.ts +79 -5
  101. package/src/email/templates/BrandEmail.vue +54 -0
  102. package/src/email/templates/DocumentBlocked.vue +45 -0
  103. package/src/email/templates/DocumentInvitation.vue +24 -0
  104. package/src/email/templates/DocumentReport.vue +32 -0
  105. package/src/email/templates/DocumentReportDecided.vue +36 -0
  106. package/src/email/templates/DocumentReportReceived.vue +18 -0
  107. package/src/email/templates/DocumentRestored.vue +24 -0
  108. package/src/email/templates/EmailChangeRequested.vue +24 -0
  109. package/src/email/templates/EmailRoot.vue +19 -0
  110. package/src/email/templates/EmailText.vue +9 -0
  111. package/src/email/templates/EmailVerification.vue +38 -0
  112. package/src/email/templates/EnrollmentNotification.vue +24 -0
  113. package/src/email/templates/EnrollmentUpdate.vue +52 -0
  114. package/src/email/templates/NewSignIn.vue +37 -0
  115. package/src/email/templates/PasswordChanged.vue +22 -0
  116. package/src/email/templates/PasswordReset.vue +23 -0
  117. package/src/email/templates/StorageLimitReached.vue +28 -0
  118. package/src/email/templates/TwoStepChanged.vue +32 -0
  119. package/src/email/templates/WaitlistConfirmation.vue +29 -0
  120. package/src/email/templates/WorkspaceInvitation.vue +28 -0
  121. package/src/email/templates/brand.ts +9 -61
  122. package/src/email/templates/localization.ts +17 -0
  123. package/src/errors/index.ts +6 -0
  124. package/src/errors/posthog.ts +80 -0
  125. package/src/global.d.ts +7 -0
  126. package/src/runtime/cloudflare/environment.ts +22 -11
  127. package/src/runtime/cloudflare/index.ts +1 -1
  128. package/src/runtime/cloudflare/logging.ts +15 -0
  129. package/src/runtime/cloudflare/maintenance.ts +31 -0
  130. package/src/runtime/cloudflare/relay/index.ts +69 -15
  131. package/src/runtime/cloudflare/tsconfig.json +2 -1
  132. package/src/runtime/cloudflare/worker.ts +46 -13
  133. package/src/runtime/node/application.ts +5 -3
  134. package/src/runtime/node/bootstrap.ts +15 -4
  135. package/src/runtime/node/cleanup.ts +20 -3
  136. package/src/runtime/node/email/transport.ts +13 -10
  137. package/src/runtime/node/entitlements/main.ts +14 -11
  138. package/src/runtime/node/index.ts +1 -1
  139. package/src/runtime/node/main.ts +1 -1
  140. package/src/runtime/node/migrate.ts +5 -1
  141. package/src/runtime/node/relay.ts +8 -2
  142. package/src/runtime/node/request-id.ts +13 -0
  143. package/src/runtime/node/server.ts +50 -16
  144. package/src/runtime/node/{ai-relay → services}/main.ts +7 -7
  145. package/src/runtime/node/{ai-relay → services}/server.ts +18 -18
  146. package/src/runtime/postgres/database.ts +20 -1
  147. package/src/runtime/posthog/errors.ts +15 -30
  148. package/src/runtime/s3/objects.ts +41 -1
  149. package/src/runtime/site/community.ts +101 -0
  150. package/src/runtime/site/server.ts +49 -6
  151. package/src/server/account/actions.ts +5 -0
  152. package/src/server/account/deletion.ts +304 -0
  153. package/src/server/account/routes.ts +281 -206
  154. package/src/server/account/terms.ts +42 -0
  155. package/src/server/account/tokens.ts +57 -0
  156. package/src/server/api/router.ts +32 -5
  157. package/src/server/api/types.ts +2 -0
  158. package/src/server/app/checks.ts +84 -0
  159. package/src/server/app/editors.ts +20 -0
  160. package/src/server/app/index.ts +128 -0
  161. package/src/server/app/indexing.ts +40 -0
  162. package/src/server/app/limiters.ts +53 -0
  163. package/src/server/app/routes.ts +114 -0
  164. package/src/server/app/services.ts +185 -0
  165. package/src/server/auth/access-control.ts +63 -0
  166. package/src/server/auth/access-tokens.ts +62 -0
  167. package/src/server/auth/adapter.ts +32 -1
  168. package/src/server/auth/email.ts +4 -1
  169. package/src/server/auth/endpoints.ts +5 -1
  170. package/src/server/auth/enrollment.ts +116 -0
  171. package/src/server/auth/factory.ts +116 -132
  172. package/src/server/auth/index.ts +10 -1
  173. package/src/server/auth/logger.ts +23 -0
  174. package/src/server/auth/mfa-assurance.ts +51 -0
  175. package/src/server/auth/passwords.ts +43 -0
  176. package/src/server/auth/session.ts +2 -0
  177. package/src/server/billing/index.ts +6 -0
  178. package/src/server/billing/routes.ts +27 -0
  179. package/src/server/billing/tokens.ts +37 -0
  180. package/src/server/cleanup/configured.ts +27 -7
  181. package/src/server/cleanup/documents.ts +165 -71
  182. package/src/server/cleanup/revisions.ts +16 -5
  183. package/src/server/cleanup/uploads.ts +8 -2
  184. package/src/server/cleanup/worker.ts +15 -3
  185. package/src/server/collaboration/relay/connection.ts +4 -3
  186. package/src/server/collaboration/relay/documents.ts +13 -10
  187. package/src/server/collaboration/relay/hub.ts +77 -122
  188. package/src/server/collaboration/relay/log.ts +5 -2
  189. package/src/server/collaboration/relay/room.ts +154 -0
  190. package/src/server/collaboration/service.ts +48 -33
  191. package/src/server/community/index.ts +2 -0
  192. package/src/server/community/routes.ts +93 -0
  193. package/src/server/community/service.ts +134 -0
  194. package/src/server/config/deployment.ts +41 -9
  195. package/src/server/config/index.ts +1 -1
  196. package/src/server/config/public.ts +11 -4
  197. package/src/server/config/schema.ts +91 -277
  198. package/src/server/config/toml/schema.ts +307 -0
  199. package/src/server/db/expressions.ts +15 -1
  200. package/src/server/db/index.ts +1 -0
  201. package/src/server/db/migrate.ts +46 -116
  202. package/src/server/db/migrations/001_accounts.ts +79 -0
  203. package/src/server/db/migrations/002_workspaces.ts +48 -0
  204. package/src/server/db/migrations/003_storage.ts +44 -0
  205. package/src/server/db/migrations/004_documents.ts +193 -0
  206. package/src/server/db/migrations/005_sharing.ts +95 -0
  207. package/src/server/db/migrations/006_operations.ts +110 -0
  208. package/src/server/db/migrations/007_trash.ts +33 -0
  209. package/src/server/db/migrations/008_terms.ts +18 -0
  210. package/src/server/db/migrations/009_access_tokens.ts +47 -0
  211. package/src/server/db/migrations/010_storage_limit_notices.ts +50 -0
  212. package/src/server/db/migrations/011_account_ids.ts +30 -0
  213. package/src/server/db/migrations/012_email_locales.ts +34 -0
  214. package/src/server/db/migrations/013_document_block_emails.ts +40 -0
  215. package/src/server/db/migrations/014_report_replies.ts +28 -0
  216. package/src/server/db/migrations/schema.ts +96 -0
  217. package/src/server/db/tables.ts +82 -4
  218. package/src/server/db/users.ts +22 -0
  219. package/src/server/documents/access.ts +66 -55
  220. package/src/server/documents/errors.ts +7 -0
  221. package/src/server/documents/images.ts +2 -1
  222. package/src/server/documents/index.ts +1 -1
  223. package/src/server/documents/limits.ts +14 -8
  224. package/src/server/documents/purge.ts +75 -0
  225. package/src/server/documents/repository.ts +2 -0
  226. package/src/server/documents/routes.ts +26 -0
  227. package/src/server/documents/service.ts +30 -406
  228. package/src/server/documents/summary.ts +1 -0
  229. package/src/server/documents/trash.ts +203 -0
  230. package/src/server/documents/uploads.ts +450 -0
  231. package/src/server/documents/versions/checkpoint.ts +2 -1
  232. package/src/server/documents/versions/history.ts +11 -7
  233. package/src/server/documents/versions/service.ts +94 -28
  234. package/src/server/email/invitations.ts +1 -0
  235. package/src/server/email/service.ts +31 -4
  236. package/src/server/email/types.ts +12 -0
  237. package/src/server/errors/index.ts +51 -16
  238. package/src/server/index.ts +52 -16
  239. package/src/server/internal/index.ts +3 -3
  240. package/src/server/internal/routes.ts +7 -10
  241. package/src/server/internal/schema.ts +1 -1
  242. package/src/server/internal/service.ts +17 -23
  243. package/src/server/invitations/budget.ts +66 -0
  244. package/src/server/invitations/index.ts +1 -0
  245. package/src/server/invitations/types.ts +5 -1
  246. package/src/server/logging.ts +76 -0
  247. package/src/server/objects/types.ts +5 -0
  248. package/src/server/pictures/service.ts +2 -1
  249. package/src/server/policy/configured.ts +9 -3
  250. package/src/server/policy/database.ts +52 -27
  251. package/src/server/policy/index.ts +2 -1
  252. package/src/server/policy/keys.ts +5 -2
  253. package/src/server/policy/policy.ts +40 -12
  254. package/src/server/policy/schema.ts +2 -2
  255. package/src/server/policy/service.ts +78 -56
  256. package/src/server/policy/static.ts +5 -5
  257. package/src/server/policy/storage.ts +33 -0
  258. package/src/server/policy/workspace.ts +41 -0
  259. package/src/server/quota/index.ts +6 -0
  260. package/src/server/quota/notices.ts +121 -0
  261. package/src/server/quota/reconcile.ts +2 -0
  262. package/src/server/quota/storage.ts +74 -31
  263. package/src/server/rate-limit/cleanup.ts +17 -5
  264. package/src/server/rate-limit/middleware.ts +6 -2
  265. package/src/server/reports/index.ts +9 -0
  266. package/src/server/reports/replies.ts +55 -0
  267. package/src/server/reports/routes.ts +39 -0
  268. package/src/server/reports/service.ts +145 -0
  269. package/src/server/services/errors.ts +7 -0
  270. package/src/server/services/index.ts +8 -0
  271. package/src/server/{ai → services}/keys.ts +11 -11
  272. package/src/server/services/routes.ts +47 -0
  273. package/src/server/{ai/service.ts → services/tokens.ts} +23 -20
  274. package/src/server/sharing/capabilities/service.ts +68 -23
  275. package/src/server/sharing/grants/service.ts +11 -18
  276. package/src/server/sharing/http.ts +4 -0
  277. package/src/server/sharing/invitations/service.ts +35 -15
  278. package/src/server/sharing/policy.ts +9 -14
  279. package/src/server/sharing/routes.ts +0 -16
  280. package/src/server/sharing/service.ts +1 -17
  281. package/src/server/validation.ts +4 -0
  282. package/src/server/workspaces/index.ts +1 -0
  283. package/src/server/workspaces/members.ts +91 -52
  284. package/src/server/workspaces/repository.ts +2 -1
  285. package/src/server/workspaces/routes.ts +4 -0
  286. package/src/{ai-relay → services}/app.ts +46 -44
  287. package/src/{ai-relay → services}/config.ts +26 -19
  288. package/src/services/db/index.ts +10 -0
  289. package/src/services/db/migrate.ts +37 -0
  290. package/src/{ai-relay/db/migrations/001_usage.ts → services/db/migrations/001_baseline.ts} +18 -7
  291. package/src/services/db/schema.ts +22 -0
  292. package/src/services/index.ts +18 -0
  293. package/src/{ai-relay → services}/metering.ts +2 -2
  294. package/src/{ai-relay → services}/usage.ts +35 -19
  295. package/dist/bin/ai-relay.mjs.map +0 -1
  296. package/src/ai-relay/db/index.ts +0 -10
  297. package/src/ai-relay/db/migrate.ts +0 -32
  298. package/src/ai-relay/db/schema.ts +0 -20
  299. package/src/ai-relay/index.ts +0 -18
  300. package/src/client/ai.ts +0 -96
  301. package/src/contract/ai.ts +0 -150
  302. package/src/email/templates/document-invitation.ts +0 -35
  303. package/src/email/templates/enrollment.ts +0 -27
  304. package/src/email/templates/layout.ts +0 -18
  305. package/src/server/ai/errors.ts +0 -7
  306. package/src/server/ai/index.ts +0 -4
  307. package/src/server/ai/routes.ts +0 -43
  308. package/src/server/app.ts +0 -379
  309. package/src/server/auth/workspace-access.ts +0 -23
  310. package/src/server/db/migrations/001_foundation.ts +0 -164
  311. package/src/server/db/migrations/002_upload_cleanup_claims.ts +0 -34
  312. package/src/server/db/migrations/003_document_cleanup_claims.ts +0 -23
  313. package/src/server/db/migrations/004_document_sharing.ts +0 -82
  314. package/src/server/db/migrations/005_document_collaboration_epoch.ts +0 -13
  315. package/src/server/db/migrations/006_invitation_continuation.ts +0 -27
  316. package/src/server/db/migrations/007_collaboration_state.ts +0 -25
  317. package/src/server/db/migrations/008_storage_reservations.ts +0 -37
  318. package/src/server/db/migrations/009_workspace_entitlements.ts +0 -22
  319. package/src/server/db/migrations/010_upload_finalization.ts +0 -22
  320. package/src/server/db/migrations/011_upload_finalization_lease.ts +0 -12
  321. package/src/server/db/migrations/012_transactional_email.ts +0 -48
  322. package/src/server/db/migrations/013_admin_enrollment.ts +0 -54
  323. package/src/server/db/migrations/014_enrollment_email_kinds.ts +0 -30
  324. package/src/server/db/migrations/015_cloud_rate_limit.ts +0 -22
  325. package/src/server/db/migrations/016_auth_schema.ts +0 -16
  326. package/src/server/db/migrations/017_authentication_email_kinds.ts +0 -32
  327. package/src/server/db/migrations/018_authentication_mfa.ts +0 -78
  328. package/src/server/db/migrations/019_better_auth_account_issuer.ts +0 -42
  329. package/src/server/db/migrations/020_workspace_invitations.ts +0 -57
  330. package/src/server/db/migrations/021_document_versions.ts +0 -66
  331. package/src/server/db/migrations/022_entitlement_external_version.ts +0 -17
  332. package/src/server/db/migrations/023_document_images.ts +0 -61
  333. package/src/server/db/migrations/024_account_activity.ts +0 -66
  334. package/src/server/db/migrations/025_table_names.ts +0 -58
  335. package/src/server/db/migrations/026_user_picture.ts +0 -30
  336. package/src/server/db/migrations/027_document_kind.ts +0 -19
  337. package/src/server/db/migrations/028_collaboration_updates.ts +0 -84
  338. package/src/server/db/migrations/helpers.ts +0 -78
  339. /package/dist/bin/{ai-relay.d.mts → services.d.mts} +0 -0
package/dist/client.js CHANGED
@@ -1,18 +1,65 @@
1
- import { isValid } from "js-base64";
2
1
  import * as v from "valibot";
2
+ import { isValid } from "js-base64";
3
3
  import { zipObject } from "es-toolkit";
4
- import { joinURL, withQuery, withoutFragment } from "ufo";
5
- import { pickBy } from "es-toolkit/object";
4
+ import { joinURL, withQuery, withoutFragment, withoutTrailingSlash } from "ufo";
6
5
  import { hc } from "hono/client";
6
+ import { pickBy } from "es-toolkit/object";
7
7
  import { passkeyClient } from "@better-auth/passkey/client";
8
8
  import { createAuthClient } from "better-auth/client";
9
9
  import { deviceAuthorizationClient, twoFactorClient } from "better-auth/client/plugins";
10
+ //#region src/client/response.ts
11
+ const cloudErrorResponseSchema = v.object({ error: v.object({ code: v.string() }) });
12
+ var CloudAPIError = class extends Error {
13
+ status;
14
+ code;
15
+ name = "CloudAPIError";
16
+ constructor(message, status, code) {
17
+ super(message);
18
+ this.status = status;
19
+ this.code = code;
20
+ }
21
+ };
22
+ async function responseBody(response, onDiagnostic) {
23
+ if (response.ok) return response.status === 204 ? null : response.json();
24
+ let code;
25
+ try {
26
+ const body = v.safeParse(cloudErrorResponseSchema, await response.json());
27
+ if (body.success) code = body.output.error.code;
28
+ } catch (error) {
29
+ onDiagnostic?.("Cloud API error response was not JSON", error);
30
+ }
31
+ throw new CloudAPIError(`OpenPencil Cloud request failed with HTTP ${response.status}`, response.status, code);
32
+ }
33
+ async function parseResponse(request, schema, onDiagnostic) {
34
+ return v.parse(schema, await responseBody(await request, onDiagnostic));
35
+ }
36
+ /**
37
+ * The JSON a service deployed apart from Cloud answered, parsed with `schema` rather than trusted;
38
+ * a refusal throws what `refused` makes of its status and body.
39
+ */
40
+ async function serviceJSON(response, schema, refused) {
41
+ if (!response.ok) {
42
+ const body = await response.text().catch((failure) => {
43
+ const error = refused(response.status, "");
44
+ error.cause = failure;
45
+ throw error;
46
+ });
47
+ throw refused(response.status, body);
48
+ }
49
+ return v.parse(v.pipe(v.string(), v.parseJson(), schema), await response.text());
50
+ }
51
+ //#endregion
10
52
  //#region src/contract/account.ts
53
+ /**
54
+ * Where an account stands: it may use the server, waits for an administrator, was refused or had
55
+ * its access taken back, or has to accept the server's current terms first.
56
+ */
11
57
  const cloudAccountStateSchema = v.picklist([
12
58
  "active",
13
59
  "pending",
14
60
  "rejected",
15
- "revoked"
61
+ "revoked",
62
+ "terms"
16
63
  ]);
17
64
  const cloudIdentitySchema = v.object({
18
65
  userId: v.string(),
@@ -26,6 +73,7 @@ const cloudAccountStatusResponseSchema = v.object({
26
73
  user: cloudIdentitySchema,
27
74
  state: cloudAccountStateSchema
28
75
  });
76
+ v.object({ version: v.pipe(v.string(), v.minLength(1)) });
29
77
  const cloudAuthenticationProviderSchema = v.picklist([
30
78
  "credential",
31
79
  "google",
@@ -61,7 +109,10 @@ const accountSecurityErrorCodeSchema = v.picklist([
61
109
  "email_unchanged",
62
110
  "email_change_unavailable",
63
111
  "current_session",
64
- "picture_invalid"
112
+ "picture_invalid",
113
+ "account_sole_admin",
114
+ "last_admin_required",
115
+ "terms_changed"
65
116
  ]);
66
117
  const accountSecurityErrorResponseSchema = v.object({ error: v.object({ code: accountSecurityErrorCodeSchema }) });
67
118
  const cloudMFAStatusSchema = v.object({
@@ -89,6 +140,32 @@ const cloudPasskeySchema = v.object({
89
140
  });
90
141
  const cloudPasskeysResponseSchema = v.object({ passkeys: v.array(cloudPasskeySchema) });
91
142
  v.object({ id: v.string() });
143
+ /**
144
+ * Personal access tokens: an account's own credentials for scripts and CI, sent as
145
+ * `Authorization: Bearer <token>`. A token acts as its account on the document API only; it never
146
+ * changes how the account is reached, makes other tokens, or reaches administration.
147
+ */
148
+ const CLOUD_ACCESS_TOKEN_PREFIX = "opc_";
149
+ const cloudAccessTokenSchema = v.object({
150
+ id: v.string(),
151
+ name: v.string(),
152
+ /** The token's first characters, prefix included, to tell tokens apart; never the whole token. */
153
+ start: v.nullable(v.string()),
154
+ createdAt: v.string(),
155
+ expiresAt: v.nullable(v.string()),
156
+ lastUsedAt: v.nullable(v.string())
157
+ });
158
+ const cloudAccessTokensResponseSchema = v.object({ tokens: v.array(cloudAccessTokenSchema) });
159
+ v.object({
160
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64)),
161
+ expiresInDays: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(365))
162
+ });
163
+ /** A new token, the only time the whole of it is shown. */
164
+ const cloudAccessTokenCreatedResponseSchema = v.object({
165
+ token: v.pipe(v.string(), v.startsWith(CLOUD_ACCESS_TOKEN_PREFIX)),
166
+ accessToken: cloudAccessTokenSchema
167
+ });
168
+ v.object({ id: v.pipe(v.string(), v.minLength(1)) });
92
169
  const cloudAccountMutationResponseSchema = v.object({ ok: v.literal(true) });
93
170
  /** Who an account belongs to, as the portal shows it. */
94
171
  const cloudPersonSchema = v.object({
@@ -152,47 +229,79 @@ const cloudSignInSchema = v.object({
152
229
  createdAt: v.string()
153
230
  });
154
231
  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 = "openpencil-ai";
232
+ /** A workspace an account deletion reads: one it would delete, or one that stops it. */
233
+ const cloudAccountDeletionWorkspaceSchema = v.object({
234
+ id: v.pipe(v.string(), v.uuid()),
235
+ name: v.string()
236
+ });
237
+ /** A document the account would lose, which Download all saves first. */
238
+ const cloudAccountDeletionDocumentSchema = v.object({
239
+ id: v.pipe(v.string(), v.uuid()),
240
+ name: v.string(),
241
+ workspaceName: v.string()
242
+ });
243
+ /**
244
+ * What deleting the account takes: the workspaces only it belongs to, which go with their
245
+ * documents; the ones it leaves to their other members; the ones it alone administers for other
246
+ * members, which stop the deletion until it makes someone else an admin; and the documents it
247
+ * would lose, those workspaces' and the ones it created in workspaces it leaves.
248
+ */
249
+ const cloudAccountDeletionSchema = v.object({
250
+ /** The account is the deployment's only administrator, which also stops the deletion. */
251
+ lastAdministrator: v.boolean(),
252
+ blockedBy: v.array(cloudAccountDeletionWorkspaceSchema),
253
+ deletes: v.array(cloudAccountDeletionWorkspaceSchema),
254
+ leaves: v.array(cloudAccountDeletionWorkspaceSchema),
255
+ documents: v.array(cloudAccountDeletionDocumentSchema)
256
+ });
257
+ const cloudAccountDeletionResponseSchema = v.object({ deletion: cloudAccountDeletionSchema });
258
+ v.object({ password: v.optional(v.pipe(v.string(), v.minLength(1))) });
259
+ /** The `aud` of every token Cloud signs for its services. */
260
+ const CLOUD_SERVICES_TOKEN_AUDIENCE = "openpencil-services";
157
261
  /**
158
262
  * Where a service answers, below the discovered `endpoint`. Model requests follow the OpenAI chat
159
263
  * completions API, so an OpenAI-compatible client takes `${endpoint}${base}` as its base URL.
160
264
  */
161
- const CLOUD_AI_API_PATHS = {
265
+ const CLOUD_SERVICES_API_PATHS = {
162
266
  base: "/v1",
163
267
  chatCompletions: "/v1/chat/completions",
164
268
  catalog: "/v1/catalog",
165
269
  wallet: "/v1/wallet",
166
- usage: "/v1/usage"
270
+ usage: "/v1/usage",
271
+ search: "/v1/search"
167
272
  };
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,
273
+ const urlSchema$1 = v.pipe(v.string(), v.url());
274
+ const creditsSchema$1 = v.pipe(v.number(), v.integer(), v.minValue(0));
275
+ const cloudServicesDiscoverySchema = v.object({
276
+ endpoint: urlSchema$1,
172
277
  contractVersion: v.literal("1")
173
278
  });
174
- const cloudBillingDiscoverySchema = v.object({ portalURL: urlSchema });
175
279
  v.object({ workspaceId: v.pipe(v.string(), v.uuid()) });
176
- const aiTokenSchema = v.object({
280
+ const servicesTokenSchema = v.object({
177
281
  token: v.pipe(v.string(), v.minLength(1)),
178
282
  expiresAt: v.pipe(v.string(), v.isoTimestamp())
179
283
  });
180
284
  v.object({
181
- iss: urlSchema,
182
- aud: v.literal(CLOUD_AI_TOKEN_AUDIENCE),
285
+ iss: urlSchema$1,
286
+ aud: v.literal(CLOUD_SERVICES_TOKEN_AUDIENCE),
183
287
  sub: v.pipe(v.string(), v.minLength(1)),
184
288
  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),
289
+ /**
290
+ * The account whose credits the request spends: the workspace's owner, whose allowance every
291
+ * workspace they own shares.
292
+ */
293
+ accountId: v.pipe(v.string(), v.minLength(1)),
294
+ /** Credits the owner's plan grants each month; `null` when Cloud sets no allowance. */
295
+ monthlyCreditAllowance: v.nullable(creditsSchema$1),
187
296
  iat: v.pipe(v.number(), v.integer()),
188
297
  exp: v.pipe(v.number(), v.integer())
189
298
  });
190
- const aiModelSchema = v.object({
299
+ const chatModelSchema = v.object({
191
300
  id: v.pipe(v.string(), v.minLength(1)),
192
301
  label: v.pipe(v.string(), v.minLength(1)),
193
302
  /** Credits per million input and output tokens. */
194
- creditsPerMillionInputTokens: creditsSchema,
195
- creditsPerMillionOutputTokens: creditsSchema,
303
+ creditsPerMillionInputTokens: creditsSchema$1,
304
+ creditsPerMillionOutputTokens: creditsSchema$1,
196
305
  contextTokens: v.pipe(v.number(), v.integer(), v.minValue(1)),
197
306
  capabilities: v.object({
198
307
  reasoning: v.boolean(),
@@ -200,30 +309,33 @@ const aiModelSchema = v.object({
200
309
  tools: v.boolean()
201
310
  })
202
311
  });
203
- const aiCatalogSchema = v.object({
204
- models: v.array(aiModelSchema),
205
- defaultModelID: v.pipe(v.string(), v.minLength(1))
312
+ /** What one web search costs; a service without search leaves it out of its catalog. */
313
+ const searchPricingSchema = v.object({ creditsPerRequest: creditsSchema$1 });
314
+ const serviceCatalogSchema = v.object({
315
+ models: v.array(chatModelSchema),
316
+ defaultModelID: v.pipe(v.string(), v.minLength(1)),
317
+ search: v.optional(searchPricingSchema)
206
318
  });
207
- const aiCreditBucketSchema = v.object({
319
+ const creditBucketSchema = v.object({
208
320
  kind: v.picklist([
209
321
  "allowance",
210
322
  "purchased",
211
323
  "grant"
212
324
  ]),
213
- remaining: creditsSchema,
325
+ remaining: creditsSchema$1,
214
326
  expiresAt: v.nullable(v.pipe(v.string(), v.isoTimestamp()))
215
327
  });
216
328
  /**
217
329
  * A service records a request's charge before the request's answer ends, so a wallet read after
218
330
  * an answer includes what it cost.
219
331
  */
220
- const aiWalletSchema = v.object({
332
+ const creditWalletSchema = v.object({
221
333
  /** Credits left to spend; `null` when the service sets no limit. */
222
- balance: v.nullable(creditsSchema),
334
+ balance: v.nullable(creditsSchema$1),
223
335
  /** Spent first to last. */
224
- buckets: v.array(aiCreditBucketSchema)
336
+ buckets: v.array(creditBucketSchema)
225
337
  });
226
- const aiUsageEntrySchema = v.object({
338
+ const usageEntrySchema = v.object({
227
339
  id: v.pipe(v.string(), v.minLength(1)),
228
340
  createdAt: v.pipe(v.string(), v.isoTimestamp()),
229
341
  kind: v.picklist([
@@ -233,94 +345,523 @@ const aiUsageEntrySchema = v.object({
233
345
  ]),
234
346
  modelID: v.nullable(v.string()),
235
347
  userId: v.pipe(v.string(), v.minLength(1)),
236
- credits: creditsSchema
348
+ credits: creditsSchema$1
237
349
  });
350
+ v.object({
351
+ query: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(1e3)),
352
+ numResults: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(10)), 5)
353
+ });
354
+ /** One page a search found, with the part of its text that answers the query. */
355
+ const searchResultSchema = v.object({
356
+ url: v.pipe(urlSchema$1, v.regex(/^https?:\/\//i, "A search result links to an HTTP(S) page")),
357
+ title: v.string(),
358
+ publishedAt: v.nullable(v.pipe(v.string(), v.isoTimestamp())),
359
+ author: v.nullable(v.string()),
360
+ text: v.string()
361
+ });
362
+ const searchResponseSchema = v.object({ results: v.array(searchResultSchema) });
238
363
  v.object({ cursor: v.optional(v.pipe(v.string(), v.minLength(1))) });
239
364
  v.object({
240
- entries: v.array(aiUsageEntrySchema),
365
+ entries: v.array(usageEntrySchema),
241
366
  next: v.nullable(v.string())
242
367
  });
243
- /** Errors an AI service answers with, beside the upstream model's own. */
244
- const aiErrorCodeSchema = v.picklist([
368
+ /** Errors a service answers with, beside the upstream provider's own. */
369
+ const serviceErrorCodeSchema = v.picklist([
370
+ "invalid_request",
245
371
  "unauthorized",
246
372
  "insufficient_credits",
247
373
  "model_not_allowed",
374
+ "capability_unavailable",
248
375
  "rate_limited"
249
376
  ]);
250
- const aiErrorSchema = v.object({ error: v.object({
251
- code: aiErrorCodeSchema,
377
+ const serviceErrorSchema = v.object({ error: v.object({
378
+ code: serviceErrorCodeSchema,
252
379
  message: v.optional(v.string()),
253
380
  /** With `insufficient_credits`: when the workspace's allowance renews, if the service knows. */
254
381
  resetsAt: v.optional(v.pipe(v.string(), v.isoTimestamp()))
255
382
  }) });
383
+ /**
384
+ * Whether a bearer token may travel to `url`: over HTTPS, or in the clear only to a loopback
385
+ * address, for development. Only literal addresses count, since a name such as `localhost` is
386
+ * whatever the resolver answers. Services and billing tokens act as the account until they expire.
387
+ */
388
+ function sendsTokenSafely(url) {
389
+ const { protocol, hostname } = new URL(url);
390
+ if (protocol === "https:") return true;
391
+ if (protocol !== "http:") return false;
392
+ return hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
393
+ }
394
+ /**
395
+ * The `aud` of the tokens Cloud signs for its billing service, with the services' signing key,
396
+ * whose public keys it publishes at `CLOUD_SERVICES_JWKS_PATH`.
397
+ */
398
+ const CLOUD_BILLING_TOKEN_AUDIENCE = "openpencil-billing";
399
+ const urlSchema = v.pipe(v.string(), v.url());
400
+ const idSchema = v.pipe(v.string(), v.regex(/^[a-z0-9][a-z0-9-]{0,62}$/));
401
+ const centsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
402
+ const bytesSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
403
+ const creditsSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
404
+ const cloudBillingDiscoverySchema = v.object({
405
+ endpoint: urlSchema,
406
+ contractVersion: v.literal("1")
407
+ });
408
+ const billingTokenSchema = v.object({
409
+ token: v.pipe(v.string(), v.minLength(1)),
410
+ expiresAt: v.pipe(v.string(), v.isoTimestamp())
411
+ });
412
+ v.object({
413
+ iss: urlSchema,
414
+ aud: v.literal(CLOUD_BILLING_TOKEN_AUDIENCE),
415
+ /** The account: the Cloud user whose plan and credits these are. */
416
+ sub: v.pipe(v.string(), v.minLength(1)),
417
+ /** Where the payment provider sends receipts and invoices. */
418
+ email: v.pipe(v.string(), v.email()),
419
+ iat: v.pipe(v.number(), v.integer()),
420
+ exp: v.pipe(v.number(), v.integer())
421
+ });
422
+ /** A plan an account subscribes to, billed every month in US dollars before tax. */
423
+ const billingPlanSchema = v.object({
424
+ id: idSchema,
425
+ name: v.pipe(v.string(), v.minLength(1)),
426
+ monthlyPriceCents: centsSchema,
427
+ storageBytes: bytesSchema,
428
+ monthlyCredits: creditsSchema
429
+ });
430
+ /** Credits an account on a plan buys once, in US dollars before tax. */
431
+ const creditPackSchema = v.object({
432
+ id: idSchema,
433
+ credits: creditsSchema,
434
+ priceCents: centsSchema,
435
+ /** How long the credits last from purchase. */
436
+ validDays: v.pipe(v.number(), v.integer(), v.minValue(1))
437
+ });
438
+ /** What the service sells; an account without a plan has its deployment's free entitlements. */
439
+ const billingCatalogSchema = v.object({
440
+ plans: v.array(billingPlanSchema),
441
+ creditPacks: v.array(creditPackSchema)
442
+ });
443
+ /**
444
+ * The account's subscription as the payment provider holds it, or `null` without one. A
445
+ * `past_due` plan keeps its entitlements while payment is retried.
446
+ */
447
+ const billingAccountSchema = v.object({ subscription: v.nullable(v.object({
448
+ planId: idSchema,
449
+ status: v.picklist(["active", "past_due"]),
450
+ /** When the current period ends: the next charge, or the end of a cancelled plan. */
451
+ currentPeriodEnd: v.pipe(v.string(), v.isoTimestamp()),
452
+ /** Whether the plan ends at `currentPeriodEnd` instead of renewing. */
453
+ cancelsAtPeriodEnd: v.boolean()
454
+ })) });
455
+ v.union([v.object({ planId: idSchema }), v.object({ creditPackId: idSchema })]);
456
+ /** Where to send the person: the payment provider's checkout or account portal. */
457
+ const billingRedirectSchema = v.object({ url: v.pipe(urlSchema, v.regex(/^https:\/\//i, "Billing sends people to an HTTPS page")) });
458
+ const billingErrorCodeSchema = v.picklist([
459
+ "invalid_request",
460
+ "unauthorized",
461
+ "not_allowed",
462
+ "provider_unavailable"
463
+ ]);
464
+ const billingErrorSchema = v.object({ error: v.object({
465
+ code: billingErrorCodeSchema,
466
+ message: v.optional(v.string())
467
+ }) });
256
468
  //#endregion
257
- //#region src/contract/workspaces.ts
258
- const workspaceRoleSchema = v.picklist([
259
- "viewer",
260
- "editor",
261
- "admin"
469
+ //#region src/contract/documents.ts
470
+ const CLOUD_PROTOCOL_MAX_UPLOAD_BYTES = 1073741824;
471
+ const checksumSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9+/]{43}=$/));
472
+ /** The most images one revision, or one request for image uploads, may name. */
473
+ const CLOUD_MAX_DOCUMENT_IMAGES = 1e4;
474
+ const imageNameSchema = v.pipe(v.string(), v.regex(/^[A-Za-z0-9._-]{1,128}$/));
475
+ const objectDownloadSchema = v.object({
476
+ url: v.pipe(v.string(), v.url()),
477
+ method: v.literal("GET"),
478
+ headers: v.record(v.string(), v.string()),
479
+ expiresAt: v.string()
480
+ });
481
+ /** An image a stored revision uses, where to download it, and what to check it against. */
482
+ const documentImageDownloadSchema = v.object({
483
+ name: imageNameSchema,
484
+ checksum: checksumSchema,
485
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
486
+ download: objectDownloadSchema
487
+ });
488
+ /** Where to download an image a document uses, found by its checksum. */
489
+ const documentImageLinkSchema = v.object({
490
+ checksum: checksumSchema,
491
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
492
+ download: objectDownloadSchema
493
+ });
494
+ /** The images a live room names, by checksum, that a peer needs links for. */
495
+ const requestImageLinksSchema = v.object({ checksums: v.pipe(v.array(checksumSchema), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
496
+ const documentPermissionSchema = v.picklist(["view", "edit"]);
497
+ const documentAccessSourceSchema = v.picklist([
498
+ "owner",
499
+ "workspace",
500
+ "direct-grant"
262
501
  ]);
263
- const workspaceSummarySchema = v.object({
502
+ const documentAccessSchema = v.object({
503
+ permission: documentPermissionSchema,
504
+ canManageSharing: v.boolean(),
505
+ sources: v.array(documentAccessSourceSchema)
506
+ });
507
+ /** What a document is: a Figma design or a FigJam board, which the file it stores says too. */
508
+ const documentKindSchema = v.picklist(["design", "board"]);
509
+ const documentSummarySchema = v.object({
264
510
  id: v.pipe(v.string(), v.uuid()),
511
+ workspaceId: v.pipe(v.string(), v.uuid()),
265
512
  name: v.string(),
266
- slug: v.string(),
267
- role: workspaceRoleSchema,
513
+ /** A design unless said otherwise; servers from before boards list no kind. */
514
+ kind: v.optional(documentKindSchema, "design"),
515
+ currentRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
516
+ version: v.number(),
268
517
  createdAt: v.string(),
269
518
  updatedAt: v.string()
270
519
  });
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]+)*$/)))
520
+ /** A document someone granted the person directly, in a workspace they are not a member of. */
521
+ const sharedDocumentSchema = v.object({
522
+ ...documentSummarySchema.entries,
523
+ workspaceName: v.string(),
524
+ permission: documentPermissionSchema,
525
+ sharedBy: v.nullable(v.object({ name: v.string() })),
526
+ sharedAt: v.string()
274
527
  });
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(),
528
+ /**
529
+ * A document in Trash the person may restore: who deleted it and when, and when it goes for good.
530
+ * `canPurge` says whether they may also delete it for good before then.
531
+ */
532
+ const trashedDocumentSchema = v.object({
533
+ id: v.pipe(v.string(), v.uuid()),
534
+ workspaceId: v.pipe(v.string(), v.uuid()),
535
+ workspaceName: v.string(),
280
536
  name: v.string(),
281
- email: v.string(),
282
- image: v.nullable(v.string()),
283
- role: workspaceRoleSchema,
284
- joinedAt: v.string()
537
+ kind: v.optional(documentKindSchema, "design"),
538
+ deletedAt: v.string(),
539
+ deletedBy: v.nullable(v.object({ name: v.string() })),
540
+ purgeAt: v.string(),
541
+ canPurge: v.boolean()
285
542
  });
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()
543
+ const trashSchema = v.object({ documents: v.array(trashedDocumentSchema) });
544
+ const documentDownloadSchema = v.object({
545
+ document: documentSummarySchema,
546
+ revisionId: v.pipe(v.string(), v.uuid()),
547
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
548
+ checksum: checksumSchema,
549
+ contentType: v.string(),
550
+ download: objectDownloadSchema,
551
+ /** The images the stored file leaves out, which a client puts back under their names. */
552
+ images: v.pipe(v.array(documentImageDownloadSchema), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES))
298
553
  });
299
- const workspaceMembersSchema = v.object({
300
- members: v.array(workspaceMemberSchema),
301
- /** Only administrators see pending invitations. */
302
- invitations: v.array(workspaceInvitationSchema)
554
+ const cloudActorSchema = v.object({
555
+ userId: v.string(),
556
+ email: v.pipe(v.string(), v.email()),
557
+ name: v.string()
558
+ });
559
+ const cloudSessionSchema = v.object({ user: cloudActorSchema });
560
+ const workspaceUsageSchema = v.object({
561
+ bytesUsed: v.pipe(v.number(), v.integer(), v.minValue(0)),
562
+ objectCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
563
+ documentCount: v.pipe(v.number(), v.integer(), v.minValue(0))
564
+ });
565
+ const createDocumentSchema = v.object({
566
+ id: v.optional(v.pipe(v.string(), v.uuid())),
567
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255)),
568
+ /** A design unless said otherwise; older clients create only designs. */
569
+ kind: v.optional(documentKindSchema, "design")
303
570
  });
304
571
  v.object({
305
- email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
306
- role: workspaceRoleSchema
572
+ baseRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
573
+ byteSize: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)),
574
+ checksum: checksumSchema,
575
+ contentType: v.literal("application/octet-stream")
307
576
  });
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()
577
+ const imageSizeSchema = v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES));
578
+ /** Where a client puts an object: one presigned PUT, or the parts of a multipart upload. */
579
+ const objectUploadSchema = v.variant("kind", [v.object({
580
+ kind: v.literal("single"),
581
+ url: v.pipe(v.string(), v.url()),
582
+ method: v.literal("PUT"),
583
+ headers: v.record(v.string(), v.string()),
584
+ expiresAt: v.string()
585
+ }), v.object({
586
+ kind: v.literal("multipart"),
587
+ uploadId: v.string(),
588
+ partSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
589
+ parts: v.array(v.object({
590
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1)),
591
+ url: v.pipe(v.string(), v.url()),
592
+ method: v.literal("PUT"),
593
+ headers: v.record(v.string(), v.string())
594
+ })),
595
+ expiresAt: v.string()
596
+ })]);
597
+ /** An upload the server offers for an image the workspace lacks. */
598
+ const imageUploadOfferSchema = v.object({
599
+ checksum: checksumSchema,
600
+ uploadId: v.pipe(v.string(), v.uuid()),
601
+ upload: objectUploadSchema
312
602
  });
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) {
603
+ v.object({ images: v.pipe(v.array(v.object({
604
+ checksum: checksumSchema,
605
+ byteSize: imageSizeSchema
606
+ })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
607
+ const completedUploadPartSchema = v.object({
608
+ partNumber: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1e4)),
609
+ etag: v.pipe(v.string(), v.minLength(1), v.maxLength(255))
610
+ });
611
+ const commitUploadSchema = v.object({
612
+ checksum: checksumSchema,
613
+ /** The document title captured with this revision; omitted by older clients. */
614
+ name: v.optional(createDocumentSchema.entries.name),
615
+ /** What the uploaded file is, which the document takes; omitted by older clients. */
616
+ kind: v.optional(documentKindSchema),
617
+ multipart: v.optional(v.object({
618
+ uploadId: v.pipe(v.string(), v.minLength(1)),
619
+ parts: v.pipe(v.array(completedUploadPartSchema), v.minLength(1), v.maxLength(1e4))
620
+ })),
621
+ /** The images the uploaded file leaves out, each stored in the workspace or uploaded before. */
622
+ images: v.optional(v.pipe(v.array(v.object({
623
+ name: imageNameSchema,
624
+ checksum: checksumSchema
625
+ })), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)), [])
626
+ });
627
+ v.object({ uploads: v.pipe(v.array(v.object({
628
+ uploadId: v.pipe(v.string(), v.uuid()),
629
+ checksum: checksumSchema,
630
+ multipart: commitUploadSchema.entries.multipart
631
+ })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
632
+ //#endregion
633
+ //#region src/contract/collaboration.ts
634
+ const collaborationPrincipalSchema = v.variant("kind", [v.object({
635
+ kind: v.literal("user"),
636
+ userId: v.string(),
637
+ name: v.string(),
638
+ email: v.pipe(v.string(), v.email())
639
+ }), v.object({
640
+ kind: v.literal("guest"),
641
+ guestId: v.string(),
642
+ name: v.string()
643
+ })]);
644
+ v.object({
645
+ kind: v.picklist(["user", "guest"]),
646
+ id: v.string(),
647
+ name: v.string(),
648
+ permission: documentPermissionSchema
649
+ });
650
+ const collaborationTicketSchema = v.object({
651
+ token: v.string(),
652
+ provider: v.optional(v.picklist(["trystero", "relay"])),
653
+ serverURL: v.optional(v.pipe(v.string(), v.url())),
654
+ documentId: v.pipe(v.string(), v.uuid()),
655
+ roomId: v.string(),
656
+ roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),
657
+ principal: collaborationPrincipalSchema,
658
+ permission: documentPermissionSchema,
659
+ /**
660
+ * Why a peer whose access would let them edit may only view: `storage-limit` when the document's
661
+ * owner holds their whole storage allowance, until they free space or their plan grows.
662
+ */
663
+ readOnly: v.optional(v.picklist(["storage-limit"])),
664
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
665
+ expiresAt: v.string(),
666
+ serverEnforcedWrites: v.boolean(),
667
+ /**
668
+ * Whether the relay answers `RELAY_HEARTBEAT`. A relay from before it takes a ping for a
669
+ * malformed frame and turns the peer away, so editors ask only a relay that says it answers.
670
+ */
671
+ relayHeartbeat: v.optional(v.boolean(), false)
672
+ });
673
+ //#endregion
674
+ //#region src/contract/workspaces.ts
675
+ const workspaceRoleSchema = v.picklist([
676
+ "viewer",
677
+ "editor",
678
+ "admin"
679
+ ]);
680
+ const workspaceSummarySchema = v.object({
681
+ id: v.pipe(v.string(), v.uuid()),
682
+ name: v.string(),
683
+ slug: v.string(),
684
+ role: workspaceRoleSchema,
685
+ createdAt: v.string(),
686
+ updatedAt: v.string()
687
+ });
688
+ v.object({
689
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)),
690
+ slug: v.optional(v.pipe(v.string(), v.trim(), v.minLength(3), v.maxLength(63), v.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)))
691
+ });
692
+ const workspaceListSchema = v.object({ workspaces: v.array(workspaceSummarySchema) });
693
+ v.object({ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(100)) });
694
+ /** Someone who belongs to a workspace, and what they may do in it. */
695
+ const workspaceMemberSchema = v.object({
696
+ userId: v.string(),
697
+ name: v.string(),
698
+ email: v.string(),
699
+ image: v.nullable(v.string()),
700
+ role: workspaceRoleSchema,
701
+ joinedAt: v.string()
702
+ });
703
+ /** An invitation to join a workspace that has not been accepted yet. */
704
+ const workspaceInvitationSchema = v.object({
705
+ id: v.pipe(v.string(), v.uuid()),
706
+ email: v.string(),
707
+ role: workspaceRoleSchema,
708
+ /** Who sent it; the name is null once their account is gone. */
709
+ invitedBy: v.object({
710
+ id: v.string(),
711
+ name: v.nullable(v.string())
712
+ }),
713
+ invitedAt: v.string(),
714
+ expiresAt: v.string()
715
+ });
716
+ const workspaceMembersSchema = v.object({
717
+ members: v.array(workspaceMemberSchema),
718
+ /** Only administrators see pending invitations. */
719
+ invitations: v.array(workspaceInvitationSchema)
720
+ });
721
+ v.object({
722
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
723
+ role: workspaceRoleSchema
724
+ });
725
+ /** A new invitation and its link, for an administrator to pass on when email is off. */
726
+ const createdWorkspaceInvitationSchema = v.object({
727
+ invitation: workspaceInvitationSchema,
728
+ acceptanceURL: v.string()
729
+ });
730
+ v.object({ role: workspaceRoleSchema });
731
+ //#endregion
732
+ //#region src/contract/sharing.ts
733
+ const documentShareSchema = v.object({
734
+ id: v.pipe(v.string(), v.uuid()),
735
+ documentId: v.pipe(v.string(), v.uuid()),
736
+ permission: documentPermissionSchema,
737
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
738
+ createdBy: v.string(),
739
+ createdAt: v.string(),
740
+ updatedAt: v.string(),
741
+ expiresAt: v.nullable(v.string()),
742
+ revokedAt: v.nullable(v.string()),
743
+ lastUsedAt: v.nullable(v.string())
744
+ });
745
+ /** When a link stops working, as an ISO timestamp; `null` keeps it working until revoked. */
746
+ const shareExpirySchema = v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp())));
747
+ v.object({
748
+ permission: documentPermissionSchema,
749
+ expiresAt: shareExpirySchema
750
+ });
751
+ v.object({
752
+ permission: v.optional(documentPermissionSchema),
753
+ expiresAt: shareExpirySchema
754
+ });
755
+ const resolveDocumentShareSchema = v.object({
756
+ secret: v.pipe(v.string(), v.minLength(32), v.maxLength(128)),
757
+ guestName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
758
+ guestId: v.optional(v.pipe(v.string(), v.minLength(16), v.maxLength(128)))
759
+ });
760
+ v.object({
761
+ ...resolveDocumentShareSchema.entries,
762
+ ...requestImageLinksSchema.entries
763
+ });
764
+ const resolvedDocumentShareSchema = v.object({
765
+ documentId: v.pipe(v.string(), v.uuid()),
766
+ /** What this person may do; a guest on an edit link may only view where guests may not edit. */
767
+ permission: documentPermissionSchema,
768
+ /** What the link lets someone signed in to the server do. */
769
+ linkPermission: documentPermissionSchema,
770
+ principal: collaborationPrincipalSchema,
771
+ roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0))
772
+ });
773
+ const cloudUserProfileSchema = v.object({
774
+ id: v.string(),
775
+ name: v.string(),
776
+ email: v.pipe(v.string(), v.email()),
777
+ image: v.nullable(v.pipe(v.string(), v.url()))
778
+ });
779
+ const documentGrantSchema = v.object({
780
+ id: v.pipe(v.string(), v.uuid()),
781
+ documentId: v.pipe(v.string(), v.uuid()),
782
+ userId: v.string(),
783
+ permission: documentPermissionSchema,
784
+ createdBy: v.string(),
785
+ createdAt: v.string(),
786
+ updatedAt: v.string()
787
+ });
788
+ /** What accepting an invitation gave: access to a document, or a place in a workspace. */
789
+ const acceptedInvitationSchema = v.variant("kind", [v.object({
790
+ kind: v.literal("document"),
791
+ grant: documentGrantSchema
792
+ }), v.object({
793
+ kind: v.literal("workspace"),
794
+ workspaceId: v.pipe(v.string(), v.uuid()),
795
+ role: workspaceRoleSchema
796
+ })]);
797
+ v.object({ permission: documentPermissionSchema });
798
+ v.object({
799
+ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
800
+ permission: documentPermissionSchema
801
+ });
802
+ v.object({ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128)) });
803
+ const createInvitationContinuationSchema = v.object({
804
+ invitationId: v.pipe(v.string(), v.uuid()),
805
+ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))
806
+ });
807
+ const invitationContinuationSchema = v.object({ id: v.pipe(v.string(), v.minLength(16), v.maxLength(128)) });
808
+ const invitationPreviewFields = {
809
+ inviterName: v.string(),
810
+ expiresAt: v.string(),
811
+ recipientHint: v.string()
812
+ };
813
+ /** What an invitation link opens: one document, or a whole workspace. */
814
+ const invitationPreviewSchema = v.variant("kind", [v.object({
815
+ kind: v.literal("document"),
816
+ documentName: v.string(),
817
+ permission: documentPermissionSchema,
818
+ ...invitationPreviewFields
819
+ }), v.object({
820
+ kind: v.literal("workspace"),
821
+ workspaceName: v.string(),
822
+ role: workspaceRoleSchema,
823
+ ...invitationPreviewFields
824
+ })]);
825
+ const documentInvitationSchema = v.object({
826
+ id: v.pipe(v.string(), v.uuid()),
827
+ documentId: v.pipe(v.string(), v.uuid()),
828
+ email: v.pipe(v.string(), v.email()),
829
+ permission: documentPermissionSchema,
830
+ invitedBy: v.string(),
831
+ invitedAt: v.string(),
832
+ expiresAt: v.string(),
833
+ acceptedAt: v.nullable(v.string())
834
+ });
835
+ //#endregion
836
+ //#region src/contract/reports.ts
837
+ /** Why someone reports a document shared with them. */
838
+ const documentReportReasonSchema = v.picklist([
839
+ "spam-phishing",
840
+ "illegal",
841
+ "copyright",
842
+ "harassment",
843
+ "other"
844
+ ]);
845
+ v.object({
846
+ secret: resolveDocumentShareSchema.entries.secret,
847
+ guestId: resolveDocumentShareSchema.entries.guestId,
848
+ reason: documentReportReasonSchema,
849
+ description: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(2e3)),
850
+ /** Where an administrator may answer; optional, and never shown to the document's people. */
851
+ replyEmail: v.optional(v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email(), v.maxLength(254)))
852
+ });
853
+ /** What filing a report answers: that it arrived, and nothing about the document. */
854
+ const fileDocumentReportResponseSchema = v.object({ received: v.literal(true) });
855
+ //#endregion
856
+ //#region src/contract/admin/index.ts
857
+ const timestampSchema = v.pipe(v.string(), v.isoTimestamp());
858
+ const nullableTimestampSchema = v.nullable(timestampSchema);
859
+ const countSchema = v.pipe(v.number(), v.integer(), v.minValue(0));
860
+ /**
861
+ * What every admin list answers besides its rows: how many rows match the search and filter
862
+ * across every page, and how many match the search under each filter.
863
+ */
864
+ function listTotals(filters) {
324
865
  return {
325
866
  total: countSchema,
326
867
  counts: v.object(zipObject(filters, filters.map(() => countSchema)))
@@ -336,7 +877,9 @@ const adminErrorCodeSchema = v.picklist([
336
877
  "last_admin_required",
337
878
  "self_admin_action_forbidden",
338
879
  "email_regeneration_unavailable",
339
- "mfa_required"
880
+ "mfa_required",
881
+ "document_not_restorable",
882
+ "workspace_gone"
340
883
  ]);
341
884
  const adminErrorResponseSchema = v.object({ error: v.object({ code: adminErrorCodeSchema }) });
342
885
  const enrollmentStatusSchema = v.picklist([
@@ -445,7 +988,7 @@ const adminAuditEventSchema = v.object({
445
988
  id: v.string(),
446
989
  actor: auditPartySchema,
447
990
  action: v.string(),
448
- /** What the event is about: an account, an access request, or an email. */
991
+ /** What the event is about: an account, an access request, an email, or a document. */
449
992
  subject: v.object({
450
993
  ...auditPartySchema.entries,
451
994
  type: v.string()
@@ -458,12 +1001,87 @@ const cloudAdminAuditFilterSchema = v.picklist([
458
1001
  "all",
459
1002
  "accounts",
460
1003
  "requests",
461
- "email"
1004
+ "email",
1005
+ "documents"
462
1006
  ]);
463
1007
  const adminAuditResponseSchema = v.object({
464
1008
  events: v.array(adminAuditEventSchema),
465
1009
  ...listTotals(cloudAdminAuditFilterSchema.options)
466
1010
  });
1011
+ /** A document as the console shows it: where it lives, who made it, and whether it is taken down. */
1012
+ const cloudAdminDocumentSchema = v.object({
1013
+ id: v.string(),
1014
+ name: v.string(),
1015
+ workspace: v.object({
1016
+ id: v.string(),
1017
+ name: v.string()
1018
+ }),
1019
+ /** Who made it, while the server knows them. */
1020
+ owner: v.nullable(v.object({
1021
+ id: v.string(),
1022
+ name: v.string(),
1023
+ email: v.string()
1024
+ })),
1025
+ createdAt: timestampSchema,
1026
+ updatedAt: timestampSchema,
1027
+ disabledAt: nullableTimestampSchema,
1028
+ disabledReason: v.nullable(v.string()),
1029
+ /** Reports about it still waiting for a decision. */
1030
+ openReports: countSchema,
1031
+ /**
1032
+ * When someone deleted it forever, and when cleanup destroys it; until then an administrator
1033
+ * can still restore it. Servers from before Trash send neither.
1034
+ */
1035
+ purgedAt: v.optional(nullableTimestampSchema, null),
1036
+ destroyedAt: v.optional(nullableTimestampSchema, null)
1037
+ });
1038
+ /** Which documents a list shows: live ones, or those deleted forever an administrator can restore. */
1039
+ const cloudAdminDocumentFilterSchema = v.picklist([
1040
+ "all",
1041
+ "reported",
1042
+ "disabled",
1043
+ "purged"
1044
+ ]);
1045
+ const cloudAdminDocumentsResponseSchema = v.object({
1046
+ documents: v.array(cloudAdminDocumentSchema),
1047
+ ...listTotals(cloudAdminDocumentFilterSchema.options)
1048
+ });
1049
+ const cloudAdminReportStatusSchema = v.picklist([
1050
+ "open",
1051
+ "dismissed",
1052
+ "actioned"
1053
+ ]);
1054
+ const cloudAdminReportSchema = v.object({
1055
+ id: v.string(),
1056
+ reason: documentReportReasonSchema,
1057
+ description: v.string(),
1058
+ status: cloudAdminReportStatusSchema,
1059
+ /** The account that filed it, or null for a guest. */
1060
+ reporter: v.nullable(v.object({
1061
+ id: v.string(),
1062
+ name: v.nullable(v.string())
1063
+ })),
1064
+ replyEmail: v.nullable(v.string()),
1065
+ createdAt: timestampSchema,
1066
+ resolvedAt: nullableTimestampSchema,
1067
+ document: cloudAdminDocumentSchema,
1068
+ /** The link it was opened from, and whether that link still works. */
1069
+ share: v.nullable(v.object({
1070
+ id: v.string(),
1071
+ revoked: v.boolean()
1072
+ }))
1073
+ });
1074
+ /** Which reports a list shows, by where they stand. */
1075
+ const cloudAdminReportFilterSchema = v.picklist([
1076
+ "open",
1077
+ "actioned",
1078
+ "dismissed",
1079
+ "all"
1080
+ ]);
1081
+ const cloudAdminReportsResponseSchema = v.object({
1082
+ reports: v.array(cloudAdminReportSchema),
1083
+ ...listTotals(cloudAdminReportFilterSchema.options)
1084
+ });
467
1085
  const adminOperationsResponseSchema = v.object({
468
1086
  deployment: v.picklist(["official", "self-hosted"]),
469
1087
  enrollmentMode: v.picklist([
@@ -477,6 +1095,7 @@ const adminOperationsResponseSchema = v.object({
477
1095
  "cloudflare"
478
1096
  ]),
479
1097
  pendingEnrollment: v.pipe(v.number(), v.integer(), v.minValue(0)),
1098
+ openReports: countSchema,
480
1099
  pendingEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
481
1100
  failedEmail: v.pipe(v.number(), v.integer(), v.minValue(0)),
482
1101
  accounts: countSchema,
@@ -485,185 +1104,6 @@ const adminOperationsResponseSchema = v.object({
485
1104
  storedBytes: countSchema
486
1105
  });
487
1106
  //#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(["view", "edit"]);
516
- const documentAccessSourceSchema = v.picklist([
517
- "owner",
518
- "workspace",
519
- "direct-grant"
520
- ]);
521
- const documentAccessSchema = v.object({
522
- permission: documentPermissionSchema,
523
- canManageSharing: v.boolean(),
524
- sources: v.array(documentAccessSourceSchema)
525
- });
526
- /** What a document is: a Figma design or a FigJam board, which the file it stores says too. */
527
- const documentKindSchema = v.picklist(["design", "board"]);
528
- const documentSummarySchema = v.object({
529
- id: v.pipe(v.string(), v.uuid()),
530
- workspaceId: v.pipe(v.string(), v.uuid()),
531
- name: v.string(),
532
- /** A design unless said otherwise; servers from before boards list no kind. */
533
- kind: v.optional(documentKindSchema, "design"),
534
- currentRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
535
- version: v.number(),
536
- createdAt: v.string(),
537
- updatedAt: v.string()
538
- });
539
- /** A document someone granted the person directly, in a workspace they are not a member of. */
540
- const sharedDocumentSchema = v.object({
541
- ...documentSummarySchema.entries,
542
- workspaceName: v.string(),
543
- permission: documentPermissionSchema,
544
- sharedBy: v.nullable(v.object({ name: v.string() })),
545
- sharedAt: v.string()
546
- });
547
- const documentDownloadSchema = v.object({
548
- document: documentSummarySchema,
549
- revisionId: v.pipe(v.string(), v.uuid()),
550
- byteSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
551
- checksum: checksumSchema,
552
- contentType: v.string(),
553
- download: objectDownloadSchema,
554
- /** The images the stored file leaves out, which a client puts back under their names. */
555
- images: v.pipe(v.array(documentImageDownloadSchema), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES))
556
- });
557
- const cloudActorSchema = v.object({
558
- userId: v.string(),
559
- email: v.pipe(v.string(), v.email()),
560
- name: v.string()
561
- });
562
- const cloudSessionSchema = v.object({ user: cloudActorSchema });
563
- const workspaceUsageSchema = v.object({
564
- bytesUsed: v.pipe(v.number(), v.integer(), v.minValue(0)),
565
- objectCount: v.pipe(v.number(), v.integer(), v.minValue(0)),
566
- documentCount: v.pipe(v.number(), v.integer(), v.minValue(0))
567
- });
568
- const createDocumentSchema = v.object({
569
- id: v.optional(v.pipe(v.string(), v.uuid())),
570
- name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255)),
571
- /** A design unless said otherwise; older clients create only designs. */
572
- kind: v.optional(documentKindSchema, "design")
573
- });
574
- v.object({
575
- baseRevisionId: v.nullable(v.pipe(v.string(), v.uuid())),
576
- byteSize: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES)),
577
- checksum: checksumSchema,
578
- contentType: v.literal("application/octet-stream")
579
- });
580
- const imageSizeSchema = v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(CLOUD_PROTOCOL_MAX_UPLOAD_BYTES));
581
- /** Where a client puts an object: one presigned PUT, or the parts of a multipart upload. */
582
- const objectUploadSchema = v.variant("kind", [v.object({
583
- kind: v.literal("single"),
584
- url: v.pipe(v.string(), v.url()),
585
- method: v.literal("PUT"),
586
- headers: v.record(v.string(), v.string()),
587
- expiresAt: v.string()
588
- }), v.object({
589
- kind: v.literal("multipart"),
590
- uploadId: v.string(),
591
- partSize: v.pipe(v.number(), v.integer(), v.minValue(1)),
592
- parts: v.array(v.object({
593
- partNumber: v.pipe(v.number(), v.integer(), v.minValue(1)),
594
- url: v.pipe(v.string(), v.url()),
595
- method: v.literal("PUT"),
596
- headers: v.record(v.string(), v.string())
597
- })),
598
- expiresAt: v.string()
599
- })]);
600
- /** An upload the server offers for an image the workspace lacks. */
601
- const imageUploadOfferSchema = v.object({
602
- checksum: checksumSchema,
603
- uploadId: v.pipe(v.string(), v.uuid()),
604
- upload: objectUploadSchema
605
- });
606
- v.object({ images: v.pipe(v.array(v.object({
607
- checksum: checksumSchema,
608
- byteSize: imageSizeSchema
609
- })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
610
- const completedUploadPartSchema = v.object({
611
- partNumber: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1e4)),
612
- etag: v.pipe(v.string(), v.minLength(1), v.maxLength(255))
613
- });
614
- const commitUploadSchema = v.object({
615
- checksum: checksumSchema,
616
- /** The document title captured with this revision; omitted by older clients. */
617
- name: v.optional(createDocumentSchema.entries.name),
618
- /** What the uploaded file is, which the document takes; omitted by older clients. */
619
- kind: v.optional(documentKindSchema),
620
- multipart: v.optional(v.object({
621
- uploadId: v.pipe(v.string(), v.minLength(1)),
622
- parts: v.pipe(v.array(completedUploadPartSchema), v.minLength(1), v.maxLength(1e4))
623
- })),
624
- /** The images the uploaded file leaves out, each stored in the workspace or uploaded before. */
625
- images: v.optional(v.pipe(v.array(v.object({
626
- name: imageNameSchema,
627
- checksum: checksumSchema
628
- })), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)), [])
629
- });
630
- v.object({ uploads: v.pipe(v.array(v.object({
631
- uploadId: v.pipe(v.string(), v.uuid()),
632
- checksum: checksumSchema,
633
- multipart: commitUploadSchema.entries.multipart
634
- })), v.minLength(1), v.maxLength(CLOUD_MAX_DOCUMENT_IMAGES)) });
635
- //#endregion
636
- //#region src/contract/collaboration.ts
637
- const collaborationPrincipalSchema = v.variant("kind", [v.object({
638
- kind: v.literal("user"),
639
- userId: v.string(),
640
- name: v.string(),
641
- email: v.pipe(v.string(), v.email())
642
- }), v.object({
643
- kind: v.literal("guest"),
644
- guestId: v.string(),
645
- name: v.string()
646
- })]);
647
- v.object({
648
- kind: v.picklist(["user", "guest"]),
649
- id: v.string(),
650
- name: v.string(),
651
- permission: documentPermissionSchema
652
- });
653
- const collaborationTicketSchema = v.object({
654
- token: v.string(),
655
- provider: v.optional(v.picklist(["trystero", "relay"])),
656
- serverURL: v.optional(v.pipe(v.string(), v.url())),
657
- documentId: v.pipe(v.string(), v.uuid()),
658
- roomId: v.string(),
659
- roomKey: v.pipe(v.string(), v.minLength(43), v.maxLength(128)),
660
- principal: collaborationPrincipalSchema,
661
- permission: documentPermissionSchema,
662
- roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
663
- expiresAt: v.string(),
664
- serverEnforcedWrites: v.boolean()
665
- });
666
- //#endregion
667
1107
  //#region src/contract/entitlements.ts
668
1108
  const workspaceEntitlementsSchema = v.object({
669
1109
  features: v.object({
@@ -673,7 +1113,7 @@ const workspaceEntitlementsSchema = v.object({
673
1113
  guestPresence: v.boolean(),
674
1114
  collaboration: v.boolean(),
675
1115
  revisionHistory: v.boolean(),
676
- cloudAI: v.optional(v.boolean(), false)
1116
+ cloudServices: v.optional(v.boolean(), false)
677
1117
  }),
678
1118
  limits: v.object({
679
1119
  maximumFileBytes: v.pipe(v.number(), v.integer(), v.minValue(1)),
@@ -686,6 +1126,12 @@ const workspaceEntitlementsSchema = v.object({
686
1126
  reservedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0))
687
1127
  })
688
1128
  });
1129
+ /**
1130
+ * An account's own plan and the storage its workspaces hold together. A workspace reports the
1131
+ * same for its owner, so the two read alike.
1132
+ */
1133
+ const accountEntitlementsSchema = workspaceEntitlementsSchema;
1134
+ const accountEntitlementsResponseSchema = v.object({ entitlements: accountEntitlementsSchema });
689
1135
  const CLOUD_DISCOVERY_PATH = "/.well-known/openpencil";
690
1136
  const cloudDeploymentSchema = v.picklist(["official", "self-hosted"]);
691
1137
  const cloudAuthenticationSchema = v.object({
@@ -719,12 +1165,60 @@ const cloudCapabilitiesSchema = v.object({
719
1165
  });
720
1166
  /** A released editor version, `major.minor.patch`. */
721
1167
  const cloudEditorVersionSchema = v.pipe(v.string(), v.regex(/^\d+\.\d+\.\d+$/));
1168
+ function editorVersionParts(version) {
1169
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
1170
+ return match ? match.slice(1).map(Number) : null;
1171
+ }
1172
+ /**
1173
+ * Whether `version` is `minimum` or later, comparing `major.minor.patch` numerically; a prerelease
1174
+ * counts as its release. A version that isn't one, on either side, is not at least anything.
1175
+ */
1176
+ function isEditorVersionAtLeast(version, minimum) {
1177
+ const have = editorVersionParts(version);
1178
+ const need = editorVersionParts(minimum);
1179
+ if (!have || !need) return false;
1180
+ for (let index = 0; index < need.length; index++) {
1181
+ const difference = (have[index] ?? 0) - (need[index] ?? 0);
1182
+ if (difference !== 0) return difference > 0;
1183
+ }
1184
+ return true;
1185
+ }
722
1186
  /**
723
1187
  * Whether editors offer this server to everyone, and from which editor version on. Only the
724
1188
  * official server's listing is read: it turns the Cloud entry points on without an editor release,
725
1189
  * and an editor older than the minimum keeps them hidden.
726
1190
  */
727
1191
  const cloudListingSchema = v.object({ minimumEditorVersion: cloudEditorVersionSchema });
1192
+ const legalURLSchema = v.pipe(v.string(), v.url());
1193
+ /**
1194
+ * The operator's legal links, which clients show at sign-up and in account pages. A server that
1195
+ * names none shows none; `requireAcceptance` means an account accepts `termsVersion` before it uses
1196
+ * the server.
1197
+ */
1198
+ const cloudLegalDiscoverySchema = v.object({
1199
+ termsURL: v.optional(legalURLSchema),
1200
+ privacyURL: v.optional(legalURLSchema),
1201
+ termsVersion: v.optional(v.string()),
1202
+ requireAcceptance: v.boolean(),
1203
+ abuseEmail: v.optional(v.pipe(v.string(), v.email())),
1204
+ minimumAge: v.optional(v.pipe(v.number(), v.integer()))
1205
+ });
1206
+ /** A web address a page may link or load: `http` or `https` only, never a script or data URL. */
1207
+ const webURLSchema = v.pipe(v.string(), v.url(), v.check((value) => ["http:", "https:"].includes(new URL(value).protocol)));
1208
+ /**
1209
+ * How a self-hosted server names itself on its public pages: the operator's name and logo in the
1210
+ * bar, and where its people get help. The official server is OpenPencil's own and names none.
1211
+ */
1212
+ const cloudBrandingSchema = v.object({
1213
+ name: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
1214
+ logoURL: v.optional(webURLSchema),
1215
+ helpURL: v.optional(webURLSchema)
1216
+ });
1217
+ /**
1218
+ * The server's community gallery: the workspace whose documents anyone may open read-only.
1219
+ * Saving to it publishes, so editors never choose it for anyone and say so when it is chosen.
1220
+ */
1221
+ const cloudCommunityDiscoverySchema = v.object({ workspaceId: v.pipe(v.string(), v.uuid()) });
728
1222
  const cloudDiscoverySchema = v.object({
729
1223
  protocolVersion: v.literal("1"),
730
1224
  deployment: cloudDeploymentSchema,
@@ -735,117 +1229,24 @@ const cloudDiscoverySchema = v.object({
735
1229
  authentication: cloudAuthenticationSchema,
736
1230
  capabilities: cloudCapabilitiesSchema,
737
1231
  listing: v.optional(cloudListingSchema),
738
- /** The AI service editors reach with Cloud-signed tokens; absent when the deployment has none. */
739
- ai: v.optional(cloudAIDiscoverySchema),
1232
+ /**
1233
+ * The oldest editor version the server works with. Older editors ask to be updated instead of
1234
+ * connecting, and the server refuses their requests.
1235
+ */
1236
+ minimumEditorVersion: v.optional(cloudEditorVersionSchema),
1237
+ /** The services editors reach with Cloud-signed tokens; absent when the deployment has none. */
1238
+ services: v.optional(cloudServicesDiscoverySchema),
740
1239
  /** Where people manage their plan and buy credits; absent when the deployment does not bill. */
741
- billing: v.optional(cloudBillingDiscoverySchema)
1240
+ billing: v.optional(cloudBillingDiscoverySchema),
1241
+ /** The community gallery; absent when the deployment has none. */
1242
+ community: v.optional(cloudCommunityDiscoverySchema),
1243
+ legal: v.optional(cloudLegalDiscoverySchema),
1244
+ branding: v.optional(cloudBrandingSchema)
742
1245
  });
743
1246
  /** The server's own address, where its editor and pages are, from its auth API's. */
744
1247
  function cloudServerOrigin(discovery) {
745
1248
  return new URL(discovery.authURL).origin;
746
1249
  }
747
- //#endregion
748
- //#region src/contract/sharing.ts
749
- const documentShareSchema = v.object({
750
- id: v.pipe(v.string(), v.uuid()),
751
- documentId: v.pipe(v.string(), v.uuid()),
752
- permission: documentPermissionSchema,
753
- roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0)),
754
- createdBy: v.string(),
755
- createdAt: v.string(),
756
- updatedAt: v.string(),
757
- expiresAt: v.nullable(v.string()),
758
- revokedAt: v.nullable(v.string()),
759
- lastUsedAt: v.nullable(v.string())
760
- });
761
- /** When a link stops working, as an ISO timestamp; `null` keeps it working until revoked. */
762
- const shareExpirySchema = v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp())));
763
- v.object({
764
- permission: documentPermissionSchema,
765
- expiresAt: shareExpirySchema
766
- });
767
- v.object({
768
- permission: v.optional(documentPermissionSchema),
769
- expiresAt: shareExpirySchema
770
- });
771
- const resolveDocumentShareSchema = v.object({
772
- secret: v.pipe(v.string(), v.minLength(32), v.maxLength(128)),
773
- guestName: v.optional(v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80))),
774
- guestId: v.optional(v.pipe(v.string(), v.minLength(16), v.maxLength(128)))
775
- });
776
- v.object({
777
- ...resolveDocumentShareSchema.entries,
778
- ...requestImageLinksSchema.entries
779
- });
780
- const resolvedDocumentShareSchema = v.object({
781
- documentId: v.pipe(v.string(), v.uuid()),
782
- permission: documentPermissionSchema,
783
- principal: collaborationPrincipalSchema,
784
- roomEpoch: v.pipe(v.number(), v.integer(), v.minValue(0))
785
- });
786
- const cloudUserProfileSchema = v.object({
787
- id: v.string(),
788
- name: v.string(),
789
- email: v.pipe(v.string(), v.email()),
790
- image: v.nullable(v.pipe(v.string(), v.url()))
791
- });
792
- const documentGrantSchema = v.object({
793
- id: v.pipe(v.string(), v.uuid()),
794
- documentId: v.pipe(v.string(), v.uuid()),
795
- userId: v.string(),
796
- permission: documentPermissionSchema,
797
- createdBy: v.string(),
798
- createdAt: v.string(),
799
- updatedAt: v.string()
800
- });
801
- /** What accepting an invitation gave: access to a document, or a place in a workspace. */
802
- const acceptedInvitationSchema = v.variant("kind", [v.object({
803
- kind: v.literal("document"),
804
- grant: documentGrantSchema
805
- }), v.object({
806
- kind: v.literal("workspace"),
807
- workspaceId: v.pipe(v.string(), v.uuid()),
808
- role: workspaceRoleSchema
809
- })]);
810
- v.object({ email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()) });
811
- v.object({ permission: documentPermissionSchema });
812
- v.object({
813
- email: v.pipe(v.string(), v.trim(), v.toLowerCase(), v.email()),
814
- permission: documentPermissionSchema
815
- });
816
- v.object({ token: v.pipe(v.string(), v.minLength(32), v.maxLength(128)) });
817
- const createInvitationContinuationSchema = v.object({
818
- invitationId: v.pipe(v.string(), v.uuid()),
819
- token: v.pipe(v.string(), v.minLength(32), v.maxLength(128))
820
- });
821
- const invitationContinuationSchema = v.object({ id: v.pipe(v.string(), v.minLength(16), v.maxLength(128)) });
822
- const invitationPreviewFields = {
823
- inviterName: v.string(),
824
- expiresAt: v.string(),
825
- recipientHint: v.string()
826
- };
827
- /** What an invitation link opens: one document, or a whole workspace. */
828
- const invitationPreviewSchema = v.variant("kind", [v.object({
829
- kind: v.literal("document"),
830
- documentName: v.string(),
831
- permission: documentPermissionSchema,
832
- ...invitationPreviewFields
833
- }), v.object({
834
- kind: v.literal("workspace"),
835
- workspaceName: v.string(),
836
- role: workspaceRoleSchema,
837
- ...invitationPreviewFields
838
- })]);
839
- const documentInvitationSchema = v.object({
840
- id: v.pipe(v.string(), v.uuid()),
841
- documentId: v.pipe(v.string(), v.uuid()),
842
- email: v.pipe(v.string(), v.email()),
843
- permission: documentPermissionSchema,
844
- invitedBy: v.string(),
845
- invitedAt: v.string(),
846
- expiresAt: v.string(),
847
- acceptedAt: v.nullable(v.string())
848
- });
849
1250
  const DOCUMENT_VERSION_DESCRIPTION_MAX_LENGTH = 1e3;
850
1251
  /** A checkpoint the server kept on its own, or a version someone named. */
851
1252
  const documentVersionKindSchema = v.picklist(["checkpoint", "named"]);
@@ -893,17 +1294,58 @@ const restoredDocumentSchema = v.object({
893
1294
  version: documentVersionSchema
894
1295
  });
895
1296
  //#endregion
896
- //#region src/client/ai.ts
897
- var CloudAIError = class extends Error {
1297
+ //#region src/contract/community.ts
1298
+ /** A version of a community document someone named, such as the release it was published for. */
1299
+ const communityVersionSchema = v.object({
1300
+ id: v.pipe(v.string(), v.uuid()),
1301
+ name: v.string(),
1302
+ description: v.nullable(v.string()),
1303
+ createdAt: v.string(),
1304
+ /** Whether the document holds this version now, with nothing changed since it was named. */
1305
+ current: v.boolean()
1306
+ });
1307
+ /**
1308
+ * A document in the deployment's community workspace, which anyone may open read-only: its name,
1309
+ * when it last changed, its thumbnail's path on the server, and its named versions, newest first.
1310
+ */
1311
+ const communityDocumentSchema = v.object({
1312
+ id: v.pipe(v.string(), v.uuid()),
1313
+ name: v.string(),
1314
+ kind: documentKindSchema,
1315
+ updatedAt: v.string(),
1316
+ revisionId: v.pipe(v.string(), v.uuid()),
1317
+ thumbnailPath: v.string(),
1318
+ versions: v.array(communityVersionSchema)
1319
+ });
1320
+ /** The community workspace's documents, most recently changed first. */
1321
+ const communityDocumentsSchema = v.object({ documents: v.array(communityDocumentSchema) });
1322
+ v.object({ version: v.optional(v.pipe(v.string(), v.uuid())) });
1323
+ /** A community document, or one of its named versions, with where to download it. */
1324
+ const communityDownloadSchema = v.object({
1325
+ document: documentDownloadSchema,
1326
+ version: v.nullable(communityVersionSchema)
1327
+ });
1328
+ //#endregion
1329
+ //#region src/client/services.ts
1330
+ var CloudServiceError = class extends Error {
898
1331
  status;
899
1332
  code;
900
- name = "CloudAIError";
1333
+ name = "CloudServiceError";
901
1334
  constructor(status, code) {
902
- super(`OpenPencil AI request failed with HTTP ${status}`);
1335
+ super(`OpenPencil services request failed with HTTP ${status}`);
903
1336
  this.status = status;
904
1337
  this.code = code;
905
1338
  }
906
1339
  };
1340
+ /** A service endpoint a token would reach in the clear, which no request is sent to. */
1341
+ var CloudServiceInsecureEndpointError = class extends Error {
1342
+ url;
1343
+ name = "CloudServiceInsecureEndpointError";
1344
+ constructor(url) {
1345
+ super("OpenPencil services and billing are reached only over HTTPS");
1346
+ this.url = url;
1347
+ }
1348
+ };
907
1349
  /** Whether a request can be sent twice: a stream, in `init` or a `Request`, is read by the first. */
908
1350
  function replayable(input, body) {
909
1351
  if (input instanceof Request && input.body) return false;
@@ -914,7 +1356,7 @@ function replayable(input, body) {
914
1356
  * by a key Cloud has since replaced, is dropped and a request that can be replayed is sent once
915
1357
  * more with a new one.
916
1358
  */
917
- function cloudAIFetch(tokens, fetch) {
1359
+ function cloudServicesFetch(tokens, fetch) {
918
1360
  const send = async (input, init, token) => {
919
1361
  const headers = new Headers(init?.headers);
920
1362
  headers.set("Authorization", `Bearer ${token}`);
@@ -924,6 +1366,8 @@ function cloudAIFetch(tokens, fetch) {
924
1366
  });
925
1367
  };
926
1368
  return async (input, init) => {
1369
+ const url = input instanceof Request ? input.url : input;
1370
+ if (!sendsTokenSafely(url)) throw new CloudServiceInsecureEndpointError(String(url));
927
1371
  const token = await tokens.token();
928
1372
  const response = await send(input, init, token);
929
1373
  if (response.status !== 401) return response;
@@ -932,28 +1376,71 @@ function cloudAIFetch(tokens, fetch) {
932
1376
  return send(input, init, await tokens.token());
933
1377
  };
934
1378
  }
935
- const errorBodySchema = v.pipe(v.string(), v.parseJson(), aiErrorSchema);
936
- async function parsed(response, schema) {
937
- const text = await response.text();
938
- if (!response.ok) {
939
- const error = v.safeParse(errorBodySchema, text);
940
- throw new CloudAIError(response.status, error.success ? error.output.error.code : void 0);
941
- }
942
- return v.parse(v.pipe(v.string(), v.parseJson(), schema), text);
1379
+ const errorBodySchema$1 = v.pipe(v.string(), v.parseJson(), serviceErrorSchema);
1380
+ function refused$1(status, body) {
1381
+ const error = v.safeParse(errorBodySchema$1, body);
1382
+ return new CloudServiceError(status, error.success ? error.output.error.code : void 0);
943
1383
  }
944
- /** The AI service a Cloud advertises: its model API base URL, catalog, and the wallet. */
945
- function createCloudAIClient(options) {
946
- const endpoint = options.endpoint.replace(/\/+$/, "");
947
- const fetch = cloudAIFetch(options.tokens, options.fetch);
1384
+ /** The services a Cloud advertises: the model API base URL, catalog, wallet, and search. */
1385
+ function createCloudServicesClient(options) {
1386
+ const endpoint = withoutTrailingSlash(options.endpoint);
1387
+ const fetch = cloudServicesFetch(options.tokens, options.fetch);
1388
+ const { v1 } = hc(endpoint, { fetch });
948
1389
  return {
949
1390
  /** The base URL an OpenAI-compatible client sends chat completions below. */
950
- modelBaseURL: `${endpoint}${CLOUD_AI_API_PATHS.base}`,
1391
+ modelBaseURL: joinURL(endpoint, CLOUD_SERVICES_API_PATHS.base),
951
1392
  fetch,
952
1393
  async catalog() {
953
- return parsed(await fetch(`${endpoint}${CLOUD_AI_API_PATHS.catalog}`), aiCatalogSchema);
1394
+ return serviceJSON(await v1.catalog.$get(), serviceCatalogSchema, refused$1);
954
1395
  },
955
1396
  async wallet() {
956
- return parsed(await fetch(`${endpoint}${CLOUD_AI_API_PATHS.wallet}`), aiWalletSchema);
1397
+ return serviceJSON(await v1.wallet.$get(), creditWalletSchema, refused$1);
1398
+ },
1399
+ /** A web search, charged to the workspace; only when the catalog lists `search`. */
1400
+ async search(input) {
1401
+ return serviceJSON(await v1.search.$post({ json: input }), searchResponseSchema, refused$1);
1402
+ }
1403
+ };
1404
+ }
1405
+ //#endregion
1406
+ //#region src/client/billing.ts
1407
+ var CloudBillingError = class extends Error {
1408
+ status;
1409
+ code;
1410
+ name = "CloudBillingError";
1411
+ constructor(status, code) {
1412
+ super(`OpenPencil billing request failed with HTTP ${status}`);
1413
+ this.status = status;
1414
+ this.code = code;
1415
+ }
1416
+ };
1417
+ const errorBodySchema = v.pipe(v.string(), v.parseJson(), billingErrorSchema);
1418
+ function refused(status, body) {
1419
+ const error = v.safeParse(errorBodySchema, body);
1420
+ return new CloudBillingError(status, error.success ? error.output.error.code : void 0);
1421
+ }
1422
+ /**
1423
+ * The billing a Cloud advertises: what it sells, the account's subscription, and where to buy or
1424
+ * manage it. Checkout and the portal answer with the payment provider's page to open, so a token
1425
+ * never travels in a URL.
1426
+ */
1427
+ function createCloudBillingClient(options) {
1428
+ const endpoint = withoutTrailingSlash(options.endpoint);
1429
+ const { v1 } = hc(endpoint, { fetch: cloudServicesFetch(options.tokens, options.fetch) });
1430
+ return {
1431
+ async catalog() {
1432
+ return serviceJSON(await v1.catalog.$get(), billingCatalogSchema, refused);
1433
+ },
1434
+ async account() {
1435
+ return serviceJSON(await v1.account.$get(), billingAccountSchema, refused);
1436
+ },
1437
+ /** The checkout page that buys `request` for the account. */
1438
+ async checkout(request) {
1439
+ return (await serviceJSON(await v1.checkout.$post({ json: request }), billingRedirectSchema, refused)).url;
1440
+ },
1441
+ /** The page where the account cancels, changes its card, and reads its invoices. */
1442
+ async portal() {
1443
+ return (await serviceJSON(await v1.portal.$post(), billingRedirectSchema, refused)).url;
957
1444
  }
958
1445
  };
959
1446
  }
@@ -966,13 +1453,13 @@ function cloudEditorReturnURL(discovery, value) {
966
1453
  return withoutFragment(destination.href);
967
1454
  }
968
1455
  /**
969
- * The server's sign-in page, coming back to `returnURL` on its editor afterwards. A `provider`
970
- * starts that provider's sign-in at once, while the server's pages still handle two-step sign-in
971
- * and approval before the return.
1456
+ * The server's sign-in page, or with `page` its sign-up page, coming back to `returnURL` on its
1457
+ * editor afterwards. A `provider` starts that provider's sign-in at once, while the server's pages
1458
+ * still handle two-step sign-in and approval before the return.
972
1459
  */
973
- function cloudSignInURL(discovery, returnURL, provider) {
1460
+ function cloudSignInURL(discovery, returnURL, provider, page = "sign-in") {
974
1461
  const offered = provider && discovery.authentication.socialProviders.includes(provider);
975
- return withQuery(new URL("/auth/sign-in", discovery.authURL).href, {
1462
+ return withQuery(new URL(`/auth/${page}`, discovery.authURL).href, {
976
1463
  redirect: withQuery("/auth/return", { editor: cloudEditorReturnURL(discovery, returnURL) }),
977
1464
  provider: offered ? provider : void 0
978
1465
  });
@@ -986,31 +1473,107 @@ function cloudRedirectPath(value, fallback = "/app") {
986
1473
  return `${url.pathname}${url.search}${url.hash}`;
987
1474
  }
988
1475
  //#endregion
989
- //#region src/client/response.ts
990
- const cloudErrorResponseSchema = v.object({ error: v.object({ code: v.string() }) });
991
- var CloudAPIError = class extends Error {
992
- status;
993
- code;
994
- name = "CloudAPIError";
995
- constructor(message, status, code) {
996
- super(message);
997
- this.status = status;
998
- this.code = code;
999
- }
1000
- };
1001
- async function responseBody(response, onDiagnostic) {
1002
- if (response.ok) return response.status === 204 ? null : response.json();
1003
- let code;
1004
- try {
1005
- const body = v.safeParse(cloudErrorResponseSchema, await response.json());
1006
- if (body.success) code = body.output.error.code;
1007
- } catch (error) {
1008
- onDiagnostic?.("Cloud API error response was not JSON", error);
1009
- }
1010
- throw new CloudAPIError(`OpenPencil Cloud request failed with HTTP ${response.status}`, response.status, code);
1476
+ //#region src/client/community.ts
1477
+ /** The server’s community gallery, which anyone may open without signing in. */
1478
+ function createCommunityRequests(publicClient, onDiagnostic) {
1479
+ return {
1480
+ /** The gallery's documents, most recently changed first. */
1481
+ async listCommunityDocuments() {
1482
+ return parseResponse(publicClient.community.$get(), communityDocumentsSchema, onDiagnostic);
1483
+ },
1484
+ /**
1485
+ * A document of the server's community gallery as it is now, or one of its named versions,
1486
+ * which anyone may open without signing in.
1487
+ */
1488
+ async getCommunityDocument(documentId, versionId = null) {
1489
+ return parseResponse(publicClient.community[":documentId"].document.$get({
1490
+ param: { documentId },
1491
+ query: versionId ? { version: versionId } : {}
1492
+ }), communityDownloadSchema, onDiagnostic);
1493
+ }
1494
+ };
1011
1495
  }
1012
- async function parseResponse(request, schema, onDiagnostic) {
1013
- return v.parse(schema, await responseBody(await request, onDiagnostic));
1496
+ //#endregion
1497
+ //#region src/client/schema.ts
1498
+ /** What the API answers with one document, as creating, restoring, or duplicating one does. */
1499
+ const documentResponseSchema = v.object({ document: documentSummarySchema });
1500
+ /** What the API answers with a ticket into a document's live room. */
1501
+ const collaborationTicketResponseSchema = v.object({ ticket: collaborationTicketSchema });
1502
+ //#endregion
1503
+ //#region src/client/documents.ts
1504
+ const documentsResponseSchema = v.object({ documents: v.array(documentSummarySchema) });
1505
+ const sharedDocumentsResponseSchema = v.object({ documents: v.array(sharedDocumentSchema) });
1506
+ const downloadResponseSchema = v.object({ document: documentDownloadSchema });
1507
+ const accessResponseSchema = v.object({ access: documentAccessSchema });
1508
+ const userLookupResponseSchema = v.object({ user: v.nullable(cloudUserProfileSchema) });
1509
+ const uploadResponseSchema = v.object({
1510
+ id: v.pipe(v.string(), v.uuid()),
1511
+ upload: objectUploadSchema
1512
+ });
1513
+ /** Documents: listing and creating them, Trash, downloads, uploads, and collaboration tickets. */
1514
+ function createDocumentRequests(client, onDiagnostic) {
1515
+ return {
1516
+ async getUserProfile(documentId, userId) {
1517
+ return (await parseResponse(client.documents[":documentId"].users[":userId"].$get({ param: {
1518
+ documentId,
1519
+ userId
1520
+ } }), userLookupResponseSchema, onDiagnostic)).user;
1521
+ },
1522
+ /** Documents shared with the person directly, outside their workspaces. */
1523
+ async listSharedDocuments() {
1524
+ return (await parseResponse(client["shared-documents"].$get(), sharedDocumentsResponseSchema, onDiagnostic)).documents;
1525
+ },
1526
+ async listDocuments(workspaceId) {
1527
+ return (await parseResponse(client.workspaces[":workspaceId"].documents.$get({ param: { workspaceId } }), documentsResponseSchema, onDiagnostic)).documents;
1528
+ },
1529
+ async createDocument(workspaceId, input) {
1530
+ return (await parseResponse(client.workspaces[":workspaceId"].documents.$post({
1531
+ param: { workspaceId },
1532
+ json: {
1533
+ ...input,
1534
+ kind: input.kind ?? "design"
1535
+ }
1536
+ }), documentResponseSchema, onDiagnostic)).document;
1537
+ },
1538
+ /** Documents in Trash the person may restore, across their workspaces, newest first. */
1539
+ async listTrash() {
1540
+ return (await parseResponse(client.trash.$get(), trashSchema, onDiagnostic)).documents;
1541
+ },
1542
+ async restoreDocument(documentId) {
1543
+ await responseBody(await client.trash[":documentId"].restore.$post({ param: { documentId } }), onDiagnostic);
1544
+ },
1545
+ /** Deletes a document in Trash for good. */
1546
+ async purgeDocument(documentId) {
1547
+ await responseBody(await client.trash[":documentId"].$delete({ param: { documentId } }), onDiagnostic);
1548
+ },
1549
+ async deleteDocument(documentId) {
1550
+ await responseBody(await client.documents[":documentId"].$delete({ param: { documentId } }), onDiagnostic);
1551
+ },
1552
+ async getDocument(documentId) {
1553
+ return (await parseResponse(client.documents[":documentId"].$get({ param: { documentId } }), downloadResponseSchema, onDiagnostic)).document;
1554
+ },
1555
+ async getDocumentAccess(documentId) {
1556
+ return (await parseResponse(client.documents[":documentId"].access.$get({ param: { documentId } }), accessResponseSchema, onDiagnostic)).access;
1557
+ },
1558
+ async getCollaborationTicket(documentId) {
1559
+ return (await parseResponse(client.documents[":documentId"]["collaboration-ticket"].$post({ param: { documentId } }), collaborationTicketResponseSchema, onDiagnostic)).ticket;
1560
+ },
1561
+ async createUpload(documentId, input) {
1562
+ return parseResponse(client.documents[":documentId"].uploads.$post({
1563
+ param: { documentId },
1564
+ json: input
1565
+ }), uploadResponseSchema, onDiagnostic);
1566
+ },
1567
+ async commitUpload(uploadId, input) {
1568
+ return (await parseResponse(client.uploads[":uploadId"].commit.$post({
1569
+ param: { uploadId },
1570
+ json: {
1571
+ ...input,
1572
+ images: input.images ?? []
1573
+ }
1574
+ }), documentResponseSchema, onDiagnostic)).document;
1575
+ }
1576
+ };
1014
1577
  }
1015
1578
  //#endregion
1016
1579
  //#region src/client/images.ts
@@ -1031,105 +1594,29 @@ function createImageRequests(client, publicClient, onDiagnostic) {
1031
1594
  await responseBody(await client.documents[":documentId"].images.commit.$post({
1032
1595
  param: { documentId },
1033
1596
  json: { uploads }
1034
- }), onDiagnostic);
1035
- },
1036
- /** Links for images a document's live room names. */
1037
- async getImageLinks(documentId, checksums) {
1038
- return (await parseResponse(client.documents[":documentId"].images.links.$post({
1039
- param: { documentId },
1040
- json: { checksums }
1041
- }), imageLinksResponseSchema, onDiagnostic)).images;
1042
- },
1043
- /** Links for images a shared document's live room names, as the share's guest. */
1044
- async getSharedImageLinks(shareId, input, checksums) {
1045
- return (await parseResponse(publicClient.shares[":shareId"].images.$post({
1046
- param: { shareId },
1047
- json: {
1048
- ...input,
1049
- checksums
1050
- }
1051
- }), imageLinksResponseSchema, onDiagnostic)).images;
1052
- }
1053
- };
1054
- }
1055
- //#endregion
1056
- //#region src/client/workspaces.ts
1057
- const workspaceResponseSchema = v.object({ workspace: workspaceSummarySchema });
1058
- const usageResponseSchema = v.object({ usage: workspaceUsageSchema });
1059
- const entitlementResponseSchema = v.object({ entitlements: workspaceEntitlementsSchema });
1060
- /** Workspaces, their members, invitations, entitlements, and storage use. */
1061
- function createWorkspaceRequests(client, onDiagnostic) {
1062
- return {
1063
- async listWorkspaces() {
1064
- return parseResponse(client.workspaces.$get(), workspaceListSchema, onDiagnostic);
1065
- },
1066
- async createWorkspace(name) {
1067
- return (await parseResponse(client.workspaces.$post({ json: { name } }), workspaceResponseSchema, onDiagnostic)).workspace;
1068
- },
1069
- async renameWorkspace(workspaceId, name) {
1070
- return (await parseResponse(client.workspaces[":workspaceId"].$patch({
1071
- param: { workspaceId },
1072
- json: { name }
1073
- }), workspaceResponseSchema, onDiagnostic)).workspace;
1074
- },
1075
- /** Deletes an empty workspace; the server refuses one that still holds documents. */
1076
- async deleteWorkspace(workspaceId) {
1077
- await responseBody(await client.workspaces[":workspaceId"].$delete({ param: { workspaceId } }), onDiagnostic);
1078
- },
1079
- /** The workspace's members, and for administrators its pending invitations. */
1080
- async listWorkspaceMembers(workspaceId) {
1081
- return parseResponse(client.workspaces[":workspaceId"].members.$get({ param: { workspaceId } }), workspaceMembersSchema, onDiagnostic);
1082
- },
1083
- async inviteToWorkspace(workspaceId, input) {
1084
- return parseResponse(client.workspaces[":workspaceId"].invitations.$post({
1085
- param: { workspaceId },
1086
- json: input
1087
- }), createdWorkspaceInvitationSchema, onDiagnostic);
1088
- },
1089
- /** Sends a waiting invitation again; its earlier link stops working. */
1090
- async resendWorkspaceInvitation(workspaceId, invitationId) {
1091
- return parseResponse(client.workspaces[":workspaceId"].invitations[":invitationId"].resend.$post({ param: {
1092
- workspaceId,
1093
- invitationId
1094
- } }), createdWorkspaceInvitationSchema, onDiagnostic);
1095
- },
1096
- async revokeWorkspaceInvitation(workspaceId, invitationId) {
1097
- await responseBody(await client.workspaces[":workspaceId"].invitations[":invitationId"].$delete({ param: {
1098
- workspaceId,
1099
- invitationId
1100
- } }), onDiagnostic);
1101
- },
1102
- async updateWorkspaceMember(workspaceId, userId, role) {
1103
- await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$patch({
1104
- param: {
1105
- workspaceId,
1106
- userId
1107
- },
1108
- json: { role }
1109
- }), onDiagnostic);
1110
- },
1111
- /** Removes someone from the workspace; with the person's own id, leaves it. */
1112
- async removeWorkspaceMember(workspaceId, userId) {
1113
- await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$delete({ param: {
1114
- workspaceId,
1115
- userId
1116
- } }), onDiagnostic);
1597
+ }), onDiagnostic);
1117
1598
  },
1118
- async getWorkspaceEntitlements(workspaceId) {
1119
- return (await parseResponse(client.workspaces[":workspaceId"].entitlements.$get({ param: { workspaceId } }), entitlementResponseSchema, onDiagnostic)).entitlements;
1599
+ /** Links for images a document's live room names. */
1600
+ async getImageLinks(documentId, checksums) {
1601
+ return (await parseResponse(client.documents[":documentId"].images.links.$post({
1602
+ param: { documentId },
1603
+ json: { checksums }
1604
+ }), imageLinksResponseSchema, onDiagnostic)).images;
1120
1605
  },
1121
- async getUsage(workspaceId) {
1122
- return (await parseResponse(client.workspaces[":workspaceId"].usage.$get({ param: { workspaceId } }), usageResponseSchema, onDiagnostic)).usage;
1606
+ /** Links for images a shared document's live room names, as the share's guest. */
1607
+ async getSharedImageLinks(shareId, input, checksums) {
1608
+ return (await parseResponse(publicClient.shares[":shareId"].images.$post({
1609
+ param: { shareId },
1610
+ json: {
1611
+ ...input,
1612
+ checksums
1613
+ }
1614
+ }), imageLinksResponseSchema, onDiagnostic)).images;
1123
1615
  }
1124
1616
  };
1125
1617
  }
1126
1618
  //#endregion
1127
- //#region src/client/api.ts
1128
- const documentsResponseSchema = v.object({ documents: v.array(documentSummarySchema) });
1129
- const sharedDocumentsResponseSchema = v.object({ documents: v.array(sharedDocumentSchema) });
1130
- const documentResponseSchema = v.object({ document: documentSummarySchema });
1131
- const downloadResponseSchema = v.object({ document: documentDownloadSchema });
1132
- const accessResponseSchema = v.object({ access: documentAccessSchema });
1619
+ //#region src/client/sharing.ts
1133
1620
  const sharesResponseSchema = v.object({ shares: v.array(documentShareSchema) });
1134
1621
  const shareResponseSchema = v.object({ share: documentShareSchema });
1135
1622
  const shareCapabilityResponseSchema = v.object({
@@ -1146,103 +1633,22 @@ const invitationCapabilityResponseSchema = v.object({
1146
1633
  invitation: documentInvitationSchema,
1147
1634
  token: v.string()
1148
1635
  });
1149
- const collaborationTicketResponseSchema = v.object({ ticket: collaborationTicketSchema });
1150
1636
  const resolvedShareResponseSchema = v.object({ resolution: resolvedDocumentShareSchema });
1151
1637
  const sharedDocumentResponseSchema = v.object({
1152
1638
  resolution: resolvedDocumentShareSchema,
1153
1639
  document: documentDownloadSchema
1154
1640
  });
1155
- const userLookupResponseSchema = v.object({ user: v.nullable(cloudUserProfileSchema) });
1156
- const uploadResponseSchema = v.object({
1157
- id: v.pipe(v.string(), v.uuid()),
1158
- upload: objectUploadSchema
1159
- });
1160
- function apiURL(baseURL) {
1161
- const url = new URL(baseURL);
1162
- if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudAPIError("OpenPencil Cloud API URL must use HTTP or HTTPS", 0);
1163
- url.pathname = url.pathname.replace(/\/$/, "");
1164
- url.search = "";
1165
- url.hash = "";
1166
- return url.href;
1167
- }
1168
- function createCloudAPIClient(baseURL, options = {}) {
1169
- const headers = {
1170
- "Content-Type": "application/json",
1171
- ...options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {}
1172
- };
1173
- const client = hc(apiURL(baseURL), {
1174
- fetch: options.fetch,
1175
- init: {
1176
- credentials: "include",
1177
- signal: options.signal,
1178
- headers
1179
- }
1180
- });
1181
- const publicClient = hc(apiURL(baseURL), {
1182
- fetch: options.fetch,
1183
- init: {
1184
- credentials: "include",
1185
- signal: options.signal,
1186
- headers
1187
- }
1188
- });
1641
+ /** Sharing a document: its links, grants, and invitations, and opening what someone shared. */
1642
+ function createSharingRequests(client, publicClient, onDiagnostic) {
1189
1643
  return {
1190
- async getSession() {
1191
- const response = await client.session.$get();
1192
- if (response.status === 401) return null;
1193
- return v.parse(cloudSessionSchema, await responseBody(response, options.onDiagnostic));
1194
- },
1195
- /** A short-lived token for the deployment's AI service, on the workspace's behalf. */
1196
- async requestAIToken(workspaceId) {
1197
- return parseResponse(client.ai.token.$post({ json: { workspaceId } }), aiTokenSchema, options.onDiagnostic);
1198
- },
1199
- async lookupUser(documentId, input) {
1200
- return (await parseResponse(client.documents[":documentId"].users.lookup.$post({
1201
- param: { documentId },
1202
- json: input
1203
- }), userLookupResponseSchema, options.onDiagnostic)).user;
1204
- },
1205
- async getUserProfile(documentId, userId) {
1206
- return (await parseResponse(client.documents[":documentId"].users[":userId"].$get({ param: {
1207
- documentId,
1208
- userId
1209
- } }), userLookupResponseSchema, options.onDiagnostic)).user;
1210
- },
1211
- ...createWorkspaceRequests(client, options.onDiagnostic),
1212
- ...createImageRequests(client, publicClient, options.onDiagnostic),
1213
- /** Documents shared with the person directly, outside their workspaces. */
1214
- async listSharedDocuments() {
1215
- return (await parseResponse(client["shared-documents"].$get(), sharedDocumentsResponseSchema, options.onDiagnostic)).documents;
1216
- },
1217
- async listDocuments(workspaceId) {
1218
- return (await parseResponse(client.workspaces[":workspaceId"].documents.$get({ param: { workspaceId } }), documentsResponseSchema, options.onDiagnostic)).documents;
1219
- },
1220
- async createDocument(workspaceId, input) {
1221
- return (await parseResponse(client.workspaces[":workspaceId"].documents.$post({
1222
- param: { workspaceId },
1223
- json: {
1224
- ...input,
1225
- kind: input.kind ?? "design"
1226
- }
1227
- }), documentResponseSchema, options.onDiagnostic)).document;
1228
- },
1229
- async deleteDocument(documentId) {
1230
- await responseBody(await client.documents[":documentId"].$delete({ param: { documentId } }), options.onDiagnostic);
1231
- },
1232
- async getDocument(documentId) {
1233
- return (await parseResponse(client.documents[":documentId"].$get({ param: { documentId } }), downloadResponseSchema, options.onDiagnostic)).document;
1234
- },
1235
- async getDocumentAccess(documentId) {
1236
- return (await parseResponse(client.documents[":documentId"].access.$get({ param: { documentId } }), accessResponseSchema, options.onDiagnostic)).access;
1237
- },
1238
1644
  async listDocumentShares(documentId) {
1239
- return (await parseResponse(client.documents[":documentId"].shares.$get({ param: { documentId } }), sharesResponseSchema, options.onDiagnostic)).shares;
1645
+ return (await parseResponse(client.documents[":documentId"].shares.$get({ param: { documentId } }), sharesResponseSchema, onDiagnostic)).shares;
1240
1646
  },
1241
1647
  async createDocumentShare(documentId, input) {
1242
1648
  return parseResponse(client.documents[":documentId"].shares.$post({
1243
1649
  param: { documentId },
1244
1650
  json: input
1245
- }), shareCapabilityResponseSchema, options.onDiagnostic);
1651
+ }), shareCapabilityResponseSchema, onDiagnostic);
1246
1652
  },
1247
1653
  async updateDocumentShare(documentId, shareId, input) {
1248
1654
  return (await parseResponse(client.documents[":documentId"].shares[":shareId"].$patch({
@@ -1251,22 +1657,22 @@ function createCloudAPIClient(baseURL, options = {}) {
1251
1657
  shareId
1252
1658
  },
1253
1659
  json: input
1254
- }), shareResponseSchema, options.onDiagnostic)).share;
1660
+ }), shareResponseSchema, onDiagnostic)).share;
1255
1661
  },
1256
1662
  async rotateDocumentShare(documentId, shareId) {
1257
1663
  return parseResponse(client.documents[":documentId"].shares[":shareId"].rotate.$post({ param: {
1258
1664
  documentId,
1259
1665
  shareId
1260
- } }), shareCapabilityResponseSchema, options.onDiagnostic);
1666
+ } }), shareCapabilityResponseSchema, onDiagnostic);
1261
1667
  },
1262
1668
  async revokeDocumentShare(documentId, shareId) {
1263
1669
  await responseBody(await client.documents[":documentId"].shares[":shareId"].$delete({ param: {
1264
1670
  documentId,
1265
1671
  shareId
1266
- } }), options.onDiagnostic);
1672
+ } }), onDiagnostic);
1267
1673
  },
1268
1674
  async listDocumentGrants(documentId) {
1269
- return (await parseResponse(client.documents[":documentId"].grants.$get({ param: { documentId } }), grantsResponseSchema, options.onDiagnostic)).grants;
1675
+ return (await parseResponse(client.documents[":documentId"].grants.$get({ param: { documentId } }), grantsResponseSchema, onDiagnostic)).grants;
1270
1676
  },
1271
1677
  async putDocumentGrant(documentId, userId, input) {
1272
1678
  return (await parseResponse(client.documents[":documentId"].grants[":userId"].$put({
@@ -1275,96 +1681,92 @@ function createCloudAPIClient(baseURL, options = {}) {
1275
1681
  userId
1276
1682
  },
1277
1683
  json: input
1278
- }), grantResponseSchema, options.onDiagnostic)).grant;
1684
+ }), grantResponseSchema, onDiagnostic)).grant;
1279
1685
  },
1280
1686
  async revokeDocumentGrant(documentId, userId) {
1281
1687
  await responseBody(await client.documents[":documentId"].grants[":userId"].$delete({ param: {
1282
1688
  documentId,
1283
1689
  userId
1284
- } }), options.onDiagnostic);
1690
+ } }), onDiagnostic);
1285
1691
  },
1286
1692
  async listDocumentInvitations(documentId) {
1287
- return (await parseResponse(client.documents[":documentId"].invitations.$get({ param: { documentId } }), invitationsResponseSchema, options.onDiagnostic)).invitations;
1693
+ return (await parseResponse(client.documents[":documentId"].invitations.$get({ param: { documentId } }), invitationsResponseSchema, onDiagnostic)).invitations;
1288
1694
  },
1289
1695
  async createDocumentInvitation(documentId, input) {
1290
1696
  return parseResponse(client.documents[":documentId"].invitations.$post({
1291
1697
  param: { documentId },
1292
1698
  json: input
1293
- }), invitationCapabilityResponseSchema, options.onDiagnostic);
1699
+ }), invitationCapabilityResponseSchema, onDiagnostic);
1294
1700
  },
1295
1701
  async createInvitationContinuation(input) {
1296
- return parseResponse(publicClient.invitations.continuations.$post({ json: input }), invitationContinuationSchema, options.onDiagnostic);
1702
+ return parseResponse(publicClient.invitations.continuations.$post({ json: input }), invitationContinuationSchema, onDiagnostic);
1297
1703
  },
1298
1704
  async consumeInvitationContinuation(id) {
1299
- return parseResponse(publicClient.invitations.continuations[":continuationId"].consume.$post({ param: { continuationId: id } }), createInvitationContinuationSchema, options.onDiagnostic);
1705
+ return parseResponse(publicClient.invitations.continuations[":continuationId"].consume.$post({ param: { continuationId: id } }), createInvitationContinuationSchema, onDiagnostic);
1300
1706
  },
1301
1707
  async previewInvitation(invitationId, input) {
1302
1708
  return (await parseResponse(publicClient.invitations[":invitationId"].preview.$post({
1303
1709
  param: { invitationId },
1304
1710
  json: input
1305
- }), invitationPreviewResponseSchema, options.onDiagnostic)).invitation;
1711
+ }), invitationPreviewResponseSchema, onDiagnostic)).invitation;
1306
1712
  },
1307
1713
  /** Accepts a document or workspace invitation, and says which it was. */
1308
1714
  async acceptInvitation(invitationId, input) {
1309
1715
  return (await parseResponse(client.invitations[":invitationId"].accept.$post({
1310
1716
  param: { invitationId },
1311
1717
  json: input
1312
- }), acceptedResponseSchema, options.onDiagnostic)).accepted;
1718
+ }), acceptedResponseSchema, onDiagnostic)).accepted;
1313
1719
  },
1314
1720
  async revokeDocumentInvitation(documentId, invitationId) {
1315
1721
  await responseBody(await client.documents[":documentId"].invitations[":invitationId"].$delete({ param: {
1316
1722
  documentId,
1317
1723
  invitationId
1318
- } }), options.onDiagnostic);
1724
+ } }), onDiagnostic);
1725
+ },
1726
+ /** Reports the document a share link opens to the server's administrators. */
1727
+ async fileDocumentReport(shareId, input) {
1728
+ await parseResponse(publicClient.shares[":shareId"].reports.$post({
1729
+ param: { shareId },
1730
+ json: input
1731
+ }), fileDocumentReportResponseSchema, onDiagnostic);
1319
1732
  },
1320
1733
  async resolveDocumentShare(shareId, input) {
1321
1734
  return (await parseResponse(publicClient.shares[":shareId"].resolve.$post({
1322
1735
  param: { shareId },
1323
1736
  json: input
1324
- }), resolvedShareResponseSchema, options.onDiagnostic)).resolution;
1737
+ }), resolvedShareResponseSchema, onDiagnostic)).resolution;
1325
1738
  },
1326
1739
  async getSharedDocument(shareId, input) {
1327
1740
  return parseResponse(publicClient.shares[":shareId"].document.$post({
1328
1741
  param: { shareId },
1329
1742
  json: input
1330
- }), sharedDocumentResponseSchema, options.onDiagnostic);
1743
+ }), sharedDocumentResponseSchema, onDiagnostic);
1331
1744
  },
1332
1745
  async getSharedCollaborationTicket(shareId, input) {
1333
1746
  return (await parseResponse(publicClient.shares[":shareId"]["collaboration-ticket"].$post({
1334
1747
  param: { shareId },
1335
1748
  json: input
1336
- }), collaborationTicketResponseSchema, options.onDiagnostic)).ticket;
1337
- },
1338
- async getCollaborationTicket(documentId) {
1339
- return (await parseResponse(client.documents[":documentId"]["collaboration-ticket"].$post({ param: { documentId } }), collaborationTicketResponseSchema, options.onDiagnostic)).ticket;
1340
- },
1341
- async createUpload(documentId, input) {
1342
- return parseResponse(client.documents[":documentId"].uploads.$post({
1343
- param: { documentId },
1344
- json: input
1345
- }), uploadResponseSchema, options.onDiagnostic);
1346
- },
1347
- async commitUpload(uploadId, input) {
1348
- return (await parseResponse(client.uploads[":uploadId"].commit.$post({
1349
- param: { uploadId },
1350
- json: {
1351
- ...input,
1352
- images: input.images ?? []
1353
- }
1354
- }), documentResponseSchema, options.onDiagnostic)).document;
1355
- },
1749
+ }), collaborationTicketResponseSchema, onDiagnostic)).ticket;
1750
+ }
1751
+ };
1752
+ }
1753
+ //#endregion
1754
+ //#region src/client/versions.ts
1755
+ /** A document’s version history: listing, naming, opening, restoring, and duplicating. */
1756
+ function createVersionRequests(client, onDiagnostic) {
1757
+ return {
1356
1758
  /** A page of the document's version history, newest first. */
1357
1759
  async listDocumentVersions(documentId, page = {}) {
1358
1760
  return parseResponse(client.documents[":documentId"].versions.$get({
1359
1761
  param: { documentId },
1360
1762
  query: pickBy(page, (value) => value !== void 0)
1361
- }), documentVersionsSchema, options.onDiagnostic);
1763
+ }), documentVersionsSchema, onDiagnostic);
1362
1764
  },
1363
1765
  async saveDocumentVersion(documentId, input) {
1364
1766
  return (await parseResponse(client.documents[":documentId"].versions.$post({
1365
1767
  param: { documentId },
1366
1768
  json: input
1367
- }), documentVersionResponseSchema, options.onDiagnostic)).version;
1769
+ }), documentVersionResponseSchema, onDiagnostic)).version;
1368
1770
  },
1369
1771
  async updateDocumentVersion(documentId, versionId, input) {
1370
1772
  return (await parseResponse(client.documents[":documentId"].versions[":versionId"].$patch({
@@ -1373,19 +1775,19 @@ function createCloudAPIClient(baseURL, options = {}) {
1373
1775
  versionId
1374
1776
  },
1375
1777
  json: input
1376
- }), documentVersionResponseSchema, options.onDiagnostic)).version;
1778
+ }), documentVersionResponseSchema, onDiagnostic)).version;
1377
1779
  },
1378
1780
  async getDocumentVersion(documentId, versionId) {
1379
1781
  return parseResponse(client.documents[":documentId"].versions[":versionId"].$get({ param: {
1380
1782
  documentId,
1381
1783
  versionId
1382
- } }), documentVersionDownloadSchema, options.onDiagnostic);
1784
+ } }), documentVersionDownloadSchema, onDiagnostic);
1383
1785
  },
1384
1786
  async restoreDocumentVersion(documentId, versionId) {
1385
1787
  return parseResponse(client.documents[":documentId"].versions[":versionId"].restore.$post({ param: {
1386
1788
  documentId,
1387
1789
  versionId
1388
- } }), restoredDocumentSchema, options.onDiagnostic);
1790
+ } }), restoredDocumentSchema, onDiagnostic);
1389
1791
  },
1390
1792
  async duplicateDocumentVersion(documentId, versionId, input) {
1391
1793
  return (await parseResponse(client.documents[":documentId"].versions[":versionId"].duplicate.$post({
@@ -1394,8 +1796,136 @@ function createCloudAPIClient(baseURL, options = {}) {
1394
1796
  versionId
1395
1797
  },
1396
1798
  json: input
1397
- }), documentResponseSchema, options.onDiagnostic)).document;
1799
+ }), documentResponseSchema, onDiagnostic)).document;
1800
+ }
1801
+ };
1802
+ }
1803
+ //#endregion
1804
+ //#region src/client/workspaces.ts
1805
+ const workspaceResponseSchema = v.object({ workspace: workspaceSummarySchema });
1806
+ const usageResponseSchema = v.object({ usage: workspaceUsageSchema });
1807
+ const entitlementResponseSchema = v.object({ entitlements: workspaceEntitlementsSchema });
1808
+ /** Workspaces, their members, invitations, entitlements, and storage use. */
1809
+ function createWorkspaceRequests(client, onDiagnostic) {
1810
+ return {
1811
+ async listWorkspaces() {
1812
+ return parseResponse(client.workspaces.$get(), workspaceListSchema, onDiagnostic);
1813
+ },
1814
+ async createWorkspace(name) {
1815
+ return (await parseResponse(client.workspaces.$post({ json: { name } }), workspaceResponseSchema, onDiagnostic)).workspace;
1816
+ },
1817
+ async renameWorkspace(workspaceId, name) {
1818
+ return (await parseResponse(client.workspaces[":workspaceId"].$patch({
1819
+ param: { workspaceId },
1820
+ json: { name }
1821
+ }), workspaceResponseSchema, onDiagnostic)).workspace;
1822
+ },
1823
+ /** Deletes an empty workspace; the server refuses one that still holds documents. */
1824
+ async deleteWorkspace(workspaceId) {
1825
+ await responseBody(await client.workspaces[":workspaceId"].$delete({ param: { workspaceId } }), onDiagnostic);
1826
+ },
1827
+ /** The workspace's members, and for administrators its pending invitations. */
1828
+ async listWorkspaceMembers(workspaceId) {
1829
+ return parseResponse(client.workspaces[":workspaceId"].members.$get({ param: { workspaceId } }), workspaceMembersSchema, onDiagnostic);
1830
+ },
1831
+ async inviteToWorkspace(workspaceId, input) {
1832
+ return parseResponse(client.workspaces[":workspaceId"].invitations.$post({
1833
+ param: { workspaceId },
1834
+ json: input
1835
+ }), createdWorkspaceInvitationSchema, onDiagnostic);
1836
+ },
1837
+ /** Sends a waiting invitation again; its earlier link stops working. */
1838
+ async resendWorkspaceInvitation(workspaceId, invitationId) {
1839
+ return parseResponse(client.workspaces[":workspaceId"].invitations[":invitationId"].resend.$post({ param: {
1840
+ workspaceId,
1841
+ invitationId
1842
+ } }), createdWorkspaceInvitationSchema, onDiagnostic);
1843
+ },
1844
+ async revokeWorkspaceInvitation(workspaceId, invitationId) {
1845
+ await responseBody(await client.workspaces[":workspaceId"].invitations[":invitationId"].$delete({ param: {
1846
+ workspaceId,
1847
+ invitationId
1848
+ } }), onDiagnostic);
1849
+ },
1850
+ async updateWorkspaceMember(workspaceId, userId, role) {
1851
+ await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$patch({
1852
+ param: {
1853
+ workspaceId,
1854
+ userId
1855
+ },
1856
+ json: { role }
1857
+ }), onDiagnostic);
1858
+ },
1859
+ /** Removes someone from the workspace; with the person's own id, leaves it. */
1860
+ async removeWorkspaceMember(workspaceId, userId) {
1861
+ await responseBody(await client.workspaces[":workspaceId"].members[":userId"].$delete({ param: {
1862
+ workspaceId,
1863
+ userId
1864
+ } }), onDiagnostic);
1865
+ },
1866
+ async getWorkspaceEntitlements(workspaceId) {
1867
+ return (await parseResponse(client.workspaces[":workspaceId"].entitlements.$get({ param: { workspaceId } }), entitlementResponseSchema, onDiagnostic)).entitlements;
1868
+ },
1869
+ async getUsage(workspaceId) {
1870
+ return (await parseResponse(client.workspaces[":workspaceId"].usage.$get({ param: { workspaceId } }), usageResponseSchema, onDiagnostic)).usage;
1871
+ }
1872
+ };
1873
+ }
1874
+ //#endregion
1875
+ //#region src/client/api.ts
1876
+ function apiURL(baseURL) {
1877
+ const url = new URL(baseURL);
1878
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new CloudAPIError("OpenPencil Cloud API URL must use HTTP or HTTPS", 0);
1879
+ url.pathname = url.pathname.replace(/\/$/, "");
1880
+ url.search = "";
1881
+ url.hash = "";
1882
+ return url.href;
1883
+ }
1884
+ function createCloudAPIClient(baseURL, options = {}) {
1885
+ const headers = {
1886
+ "Content-Type": "application/json",
1887
+ ...options.accessToken ? { Authorization: `Bearer ${options.accessToken}` } : {}
1888
+ };
1889
+ const client = hc(apiURL(baseURL), {
1890
+ fetch: options.fetch,
1891
+ init: {
1892
+ credentials: "include",
1893
+ signal: options.signal,
1894
+ headers
1895
+ }
1896
+ });
1897
+ const publicClient = hc(apiURL(baseURL), {
1898
+ fetch: options.fetch,
1899
+ init: {
1900
+ credentials: "include",
1901
+ signal: options.signal,
1902
+ headers
1398
1903
  }
1904
+ });
1905
+ return {
1906
+ async getSession() {
1907
+ const response = await client.session.$get();
1908
+ if (response.status === 401) return null;
1909
+ return v.parse(cloudSessionSchema, await responseBody(response, options.onDiagnostic));
1910
+ },
1911
+ /** A short-lived token for the deployment's services, on the workspace's behalf. */
1912
+ async requestServicesToken(workspaceId) {
1913
+ return parseResponse(client.services.token.$post({ json: { workspaceId } }), servicesTokenSchema, options.onDiagnostic);
1914
+ },
1915
+ /** A short-lived token for the deployment's billing, for the signed-in person's own account. */
1916
+ async requestBillingToken() {
1917
+ return parseResponse(client.billing.token.$post(), billingTokenSchema, options.onDiagnostic);
1918
+ },
1919
+ /** The signed-in account's plan, and the storage its workspaces hold together. */
1920
+ async getAccountEntitlements() {
1921
+ return (await parseResponse(client.account.entitlements.$get(), accountEntitlementsResponseSchema, options.onDiagnostic)).entitlements;
1922
+ },
1923
+ ...createWorkspaceRequests(client, options.onDiagnostic),
1924
+ ...createImageRequests(client, publicClient, options.onDiagnostic),
1925
+ ...createDocumentRequests(client, options.onDiagnostic),
1926
+ ...createVersionRequests(client, options.onDiagnostic),
1927
+ ...createSharingRequests(client, publicClient, options.onDiagnostic),
1928
+ ...createCommunityRequests(publicClient, options.onDiagnostic)
1399
1929
  };
1400
1930
  }
1401
1931
  //#endregion
@@ -1519,12 +2049,16 @@ async function signInToCloudWithEmail(discovery, input, options = {}) {
1519
2049
  }
1520
2050
  };
1521
2051
  }
1522
- /** Creates an account; the server emails a link that opens `verifiedURL` once it is confirmed. */
2052
+ /**
2053
+ * Creates an account; the server emails a link that opens `verifiedURL` once it is confirmed,
2054
+ * written in `locale`, the app's language.
2055
+ */
1523
2056
  async function signUpToCloudWithEmail(discovery, input, options = {}) {
1524
2057
  const result = await createCloudAuthClient(discovery, options).signUp.email({
1525
2058
  name: input.name,
1526
2059
  email: input.email,
1527
2060
  password: input.password,
2061
+ locale: input.locale,
1528
2062
  callbackURL: input.verifiedURL
1529
2063
  }).catch(() => null);
1530
2064
  if (!result) return cloudAuthFailure(null);
@@ -1667,14 +2201,24 @@ function discoveryURL(serverURL) {
1667
2201
  url.hash = "";
1668
2202
  return url;
1669
2203
  }
1670
- function parseDiscoveryBody(text) {
2204
+ /** Which side is behind when the server speaks another protocol, or null when it doesn't. */
2205
+ function protocolMismatch(version) {
2206
+ if (version === "1") return null;
2207
+ return Number(version) > 1 ? "editor-outdated" : "server-outdated";
2208
+ }
2209
+ function parseDiscoveryBody(text, editorVersion) {
1671
2210
  const body = v.safeParse(discoveryBodySchema, text);
1672
2211
  if (!body.success) throw new CloudClientError("OpenPencil server discovery is not JSON", body.issues, "not-cloud");
1673
2212
  const discovery = v.safeParse(cloudDiscoverySchema, body.output);
1674
- if (discovery.success) return discovery.output;
2213
+ if (discovery.success) {
2214
+ const minimum = discovery.output.minimumEditorVersion;
2215
+ if (minimum && editorVersion && !isEditorVersionAtLeast(editorVersion, minimum)) throw new CloudClientError(`OpenPencil server needs editor ${minimum} or later`, void 0, "editor-outdated");
2216
+ return discovery.output;
2217
+ }
1675
2218
  const protocol = v.safeParse(protocolSchema, body.output);
1676
- const outdated = protocol.success && protocol.output.protocolVersion !== "1";
1677
- throw new CloudClientError(outdated ? `OpenPencil server speaks protocol ${protocol.output.protocolVersion}` : "OpenPencil server discovery is invalid", discovery.issues, outdated ? "outdated" : "not-cloud");
2219
+ const version = protocol.success ? protocol.output.protocolVersion : null;
2220
+ const mismatch = version === null ? null : protocolMismatch(version);
2221
+ throw new CloudClientError(mismatch ? `OpenPencil server speaks protocol ${version}` : "OpenPencil server discovery is invalid", discovery.issues, mismatch ?? "not-cloud");
1678
2222
  }
1679
2223
  async function discoverCloud(serverURL, options = {}) {
1680
2224
  const fetchImplementation = options.fetch ?? globalThis.fetch;
@@ -1687,7 +2231,7 @@ async function discoverCloud(serverURL, options = {}) {
1687
2231
  signal
1688
2232
  });
1689
2233
  if (!response.ok) throw new CloudClientError(`OpenPencil server discovery failed with HTTP ${response.status}`, void 0, response.status >= 500 ? "unreachable" : "not-cloud");
1690
- return parseDiscoveryBody(await response.text());
2234
+ return parseDiscoveryBody(await response.text(), options.editorVersion);
1691
2235
  } catch (error) {
1692
2236
  if (error instanceof CloudClientError) throw error;
1693
2237
  if (signal.aborted) throw new CloudClientError("OpenPencil server discovery was cancelled or timed out", error);
@@ -1696,11 +2240,23 @@ async function discoverCloud(serverURL, options = {}) {
1696
2240
  }
1697
2241
  //#endregion
1698
2242
  //#region src/client/portal/account.ts
1699
- function createAccountAPI(call, { account }) {
2243
+ function createAccountAPI(call, { account, tokens, api }) {
1700
2244
  return {
2245
+ /** The account's plan, and the storage its workspaces hold together. */
2246
+ entitlements(signal) {
2247
+ return call((options) => api.account.entitlements.$get(void 0, options), accountEntitlementsResponseSchema, signal);
2248
+ },
2249
+ /** A short-lived token for the deployment's billing, for this account. */
2250
+ billingToken(signal) {
2251
+ return call((options) => api.billing.token.$post(void 0, options), billingTokenSchema, signal);
2252
+ },
1701
2253
  accountStatus(signal) {
1702
2254
  return call((options) => account.status.$get(void 0, options), cloudAccountStatusResponseSchema, signal);
1703
2255
  },
2256
+ /** Accepts the server's terms at `version`, the one its discovery names. */
2257
+ acceptTerms(version, signal) {
2258
+ return call((options) => account.terms.$post({ json: { version } }, options), cloudAccountMutationResponseSchema, signal);
2259
+ },
1704
2260
  authenticationMethods(signal) {
1705
2261
  return call((options) => account.authentication.$get(void 0, options), cloudAuthenticationMethodsResponseSchema, signal);
1706
2262
  },
@@ -1743,6 +2299,10 @@ function createAccountAPI(call, { account }) {
1743
2299
  profile(signal) {
1744
2300
  return call((options) => account.profile.$get(void 0, options), cloudProfileResponseSchema, signal);
1745
2301
  },
2302
+ /** The app's language tag; the server writes to the account in it, or the nearest it has. */
2303
+ setLocale(locale, signal) {
2304
+ return call((options) => account.locale.$put({ json: { locale } }, options), cloudAccountMutationResponseSchema, signal);
2305
+ },
1746
2306
  updateProfile(name, signal) {
1747
2307
  return call((options) => account.profile.$post({ json: { name } }, options), cloudAccountMutationResponseSchema, signal);
1748
2308
  },
@@ -1760,6 +2320,17 @@ function createAccountAPI(call, { account }) {
1760
2320
  callbackURL
1761
2321
  } }, options), cloudAccountMutationResponseSchema, signal);
1762
2322
  },
2323
+ /** The account's personal access tokens, by their first characters; never a whole one. */
2324
+ accessTokens(signal) {
2325
+ return call((options) => tokens.$get(void 0, options), cloudAccessTokensResponseSchema, signal);
2326
+ },
2327
+ /** Makes a token; the answer holds the whole token, which is shown this once. */
2328
+ createAccessToken(input, signal) {
2329
+ return call((options) => tokens.create.$post({ json: input }, options), cloudAccessTokenCreatedResponseSchema, signal);
2330
+ },
2331
+ revokeAccessToken(id, signal) {
2332
+ return call((options) => tokens.revoke.$post({ json: { id } }, options), cloudAccountMutationResponseSchema, signal);
2333
+ },
1763
2334
  sessions(signal) {
1764
2335
  return call((options) => account.sessions.$get(void 0, options), cloudAccountSessionsResponseSchema, signal);
1765
2336
  },
@@ -1772,6 +2343,14 @@ function createAccountAPI(call, { account }) {
1772
2343
  signIns(signal) {
1773
2344
  return call((options) => account["sign-ins"].$get(void 0, options), cloudSignInsResponseSchema, signal);
1774
2345
  },
2346
+ /** What deleting the account takes, and the workspaces that stop it. */
2347
+ accountDeletion(signal) {
2348
+ return call((options) => account.deletion.$get(void 0, options), cloudAccountDeletionResponseSchema, signal);
2349
+ },
2350
+ /** Deletes the account; a session that signed in a while ago gives its password. */
2351
+ deleteAccount(password, signal) {
2352
+ return call((options) => account.delete.$post({ json: { password } }, options), cloudAccountMutationResponseSchema, signal);
2353
+ },
1775
2354
  unlinkAuthenticationMethod(methodId, signal) {
1776
2355
  return call((options) => account.authentication.unlink.$post({ json: { methodId } }, options), cloudAccountMutationResponseSchema, signal);
1777
2356
  }
@@ -1829,6 +2408,29 @@ function createAdministrationAPI(call, { admin, api }) {
1829
2408
  audit(request, signal) {
1830
2409
  return call((options) => admin.audit.$get(listQuery(request), options), adminAuditResponseSchema, signal);
1831
2410
  },
2411
+ reports(request, signal) {
2412
+ return call((options) => admin.reports.$get(listQuery(request), options), cloudAdminReportsResponseSchema, signal);
2413
+ },
2414
+ /** Closes a report: dismissed, or acted on outside a takedown. */
2415
+ resolveReport(id, action, signal) {
2416
+ return call((options) => admin.reports[":id"][action].$post({ param: { id } }, options), adminMutationResponseSchema, signal);
2417
+ },
2418
+ documents(request, signal) {
2419
+ return call((options) => admin.documents.$get(listQuery(request), options), cloudAdminDocumentsResponseSchema, signal);
2420
+ },
2421
+ /** Takes a document down, or puts it back. */
2422
+ documentAction(id, action, reason, signal) {
2423
+ return call((options) => {
2424
+ if (action === "disable") return admin.documents[":id"].disable.$post({
2425
+ param: { id },
2426
+ json: { reason }
2427
+ }, options);
2428
+ return action === "enable" ? admin.documents[":id"].enable.$post({ param: { id } }, options) : admin.documents[":id"].undelete.$post({ param: { id } }, options);
2429
+ }, adminMutationResponseSchema, signal);
2430
+ },
2431
+ revokeShare(id, signal) {
2432
+ return call((options) => admin.shares[":id"].revoke.$post({ param: { id } }, options), adminMutationResponseSchema, signal);
2433
+ },
1832
2434
  operations(signal) {
1833
2435
  return call((options) => admin.operations.$get(void 0, options), adminOperationsResponseSchema, signal);
1834
2436
  }
@@ -1896,6 +2498,7 @@ function createPortalRouteClients(options = {}) {
1896
2498
  };
1897
2499
  return {
1898
2500
  account: hc(origin, clientOptions).api.account,
2501
+ tokens: hc(origin, clientOptions).api.account.tokens,
1899
2502
  admin: hc(new URL("/api/admin", origin).href, clientOptions),
1900
2503
  api: hc(new URL("/api", origin).href, clientOptions)
1901
2504
  };
@@ -1912,6 +2515,6 @@ function createCloudPortalClient(options = {}) {
1912
2515
  };
1913
2516
  }
1914
2517
  //#endregion
1915
- export { CloudAIError, CloudAPIError, CloudClientError, CloudDeviceAuthorizationError, CloudPortalAPIError, cloudAIFetch, cloudAuthFailure, cloudEditorReturnURL, cloudRedirectPath, cloudSignInURL, createCloudAIClient, createCloudAPIClient, createCloudAuthClient, createCloudPortalClient, discoverCloud, pollCloudDeviceToken, requestCloudDeviceAuthorization, resendCloudVerification, signInToCloud, signInToCloudWithEmail, signOutFromCloud, signUpToCloudWithEmail };
2518
+ export { CloudAPIError, CloudBillingError, CloudClientError, CloudDeviceAuthorizationError, CloudPortalAPIError, CloudServiceError, CloudServiceInsecureEndpointError, cloudAuthFailure, cloudEditorReturnURL, cloudRedirectPath, cloudServicesFetch, cloudSignInURL, createCloudAPIClient, createCloudAuthClient, createCloudBillingClient, createCloudPortalClient, createCloudServicesClient, discoverCloud, pollCloudDeviceToken, requestCloudDeviceAuthorization, resendCloudVerification, signInToCloud, signInToCloudWithEmail, signOutFromCloud, signUpToCloudWithEmail };
1916
2519
 
1917
2520
  //# sourceMappingURL=client.js.map