@tunasand/sdk 0.8.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/README.md +165 -144
  3. package/dist/analytics.js +183 -109
  4. package/dist/app.js +276 -166
  5. package/dist/apps-BysPfMuR.js +408 -0
  6. package/dist/astro-image.d.ts +1 -0
  7. package/dist/astro-image.js +33 -0
  8. package/dist/astro-server-Bwau8F6d.js +99 -0
  9. package/dist/astro-server.d.ts +1 -0
  10. package/dist/astro-server.js +1 -0
  11. package/dist/astro.d.ts +1 -0
  12. package/dist/astro.js +306 -0
  13. package/dist/bridge-C2Bl-OAF.js +80 -0
  14. package/dist/bridge.js +1 -13
  15. package/dist/build-file-DNi0PHC5.js +31 -0
  16. package/dist/cli.js +6212 -8
  17. package/dist/{client-Derrexwr.js → client-C8STAw9T.js} +43 -24
  18. package/dist/code-N8pBUDbq.js +30 -0
  19. package/dist/code.d.ts +1 -0
  20. package/dist/code.js +1 -0
  21. package/dist/collection-26aglrg6.js +282 -0
  22. package/dist/{declared-DuNMsdXw.js → declared-CE4a61qb.js} +35 -35
  23. package/dist/delivery.js +121 -114
  24. package/dist/dev-operations-Tutwi1On.js +46 -0
  25. package/dist/dev.js +9 -16
  26. package/dist/embeds-DY6O5TrJ.js +29 -0
  27. package/dist/end-users.d.ts +1 -0
  28. package/dist/end-users.js +189 -0
  29. package/dist/endUsers-DODfjnv1.js +77 -0
  30. package/dist/{errorLabels-BgtQ_zUn.js → errorLabels-BK1NJ6Wz.js} +374 -238
  31. package/dist/i18n.js +4 -4
  32. package/dist/ids-DmtIoqBX.js +109 -0
  33. package/dist/integrations.js +95 -24
  34. package/dist/{ja-Du6ooL6i.js → ja-B3lAaOhZ.js} +91 -45
  35. package/dist/{ja-CeHU0EaY.js → ja-axQPxMJ-.js} +3 -3
  36. package/dist/operations-CIB99rIY.js +95 -0
  37. package/dist/operations.d.ts +1 -0
  38. package/dist/operations.js +1 -0
  39. package/dist/{page-Bzrj24sJ.js → page-yo1cw1kW.js} +1 -1
  40. package/dist/paymentPort-p1jV44Zz.js +203 -0
  41. package/dist/preview.js +8 -1
  42. package/dist/{profile-1em_lcxq.js → profile-DBsXLvvI.js} +48 -48
  43. package/dist/rich-text.js +16 -16
  44. package/dist/{schema-WnobuwLg.js → schema-Bs_BUUNv.js} +526 -265
  45. package/dist/schema.js +66 -88
  46. package/dist/types/access/src/handoff.d.ts +19 -14
  47. package/dist/types/access/src/index.d.ts +2 -2
  48. package/dist/types/access/src/jws.d.ts +41 -0
  49. package/dist/types/access/src/oidc.d.ts +12 -2
  50. package/dist/types/access/src/signed.d.ts +0 -2
  51. package/dist/types/adapter-cloudflare/src/eventLog/viewSchema.d.ts +11 -0
  52. package/dist/types/contract/src/accountProfile.d.ts +7 -0
  53. package/dist/types/contract/src/api/define.d.ts +165 -0
  54. package/dist/types/contract/src/apiKeys.d.ts +6 -2
  55. package/dist/types/contract/src/app.d.ts +32 -7
  56. package/dist/types/contract/src/appChannels.d.ts +152 -0
  57. package/dist/types/contract/src/appDefinition.d.ts +11 -5
  58. package/dist/types/contract/src/appDependencies.d.ts +107 -24
  59. package/dist/types/contract/src/appIdentities.d.ts +21 -0
  60. package/dist/types/contract/src/appInbound.d.ts +53 -0
  61. package/dist/types/contract/src/appMail.d.ts +106 -0
  62. package/dist/types/contract/src/appSecrets.d.ts +63 -0
  63. package/dist/types/contract/src/appServer.d.ts +460 -45
  64. package/dist/types/contract/src/approvals.d.ts +1 -1
  65. package/dist/types/contract/src/apps.d.ts +126 -60
  66. package/dist/types/contract/src/auditActions.d.ts +2 -2
  67. package/dist/types/contract/src/auditLabels.d.ts +120 -15
  68. package/dist/types/contract/src/authorize.d.ts +42 -14
  69. package/dist/types/contract/src/bridge.d.ts +35 -36
  70. package/dist/types/contract/src/consents.d.ts +29 -27
  71. package/dist/types/contract/src/deletion.d.ts +18 -0
  72. package/dist/types/contract/src/embeds.d.ts +26 -90
  73. package/dist/types/contract/src/{customerLabels.d.ts → endUserLabels.d.ts} +6 -9
  74. package/dist/types/contract/src/endUsers.d.ts +244 -0
  75. package/dist/types/contract/src/errorLabels.d.ts +67 -37
  76. package/dist/types/contract/src/errorLabelsEn.d.ts +50 -33
  77. package/dist/types/contract/src/errors.d.ts +28 -16
  78. package/dist/types/contract/src/eventSchemas.d.ts +70 -0
  79. package/dist/types/contract/src/eventTraces.d.ts +41 -0
  80. package/dist/types/contract/src/failureStatus.d.ts +14 -22
  81. package/dist/types/contract/src/fieldAccess.d.ts +8 -8
  82. package/dist/types/contract/src/formLabels.d.ts +3 -0
  83. package/dist/types/contract/src/forms.d.ts +4 -0
  84. package/dist/types/contract/src/grants.d.ts +26 -0
  85. package/dist/types/contract/src/headers.d.ts +5 -0
  86. package/dist/types/contract/src/hostingRpc.d.ts +44 -19
  87. package/dist/types/contract/src/identifiers.d.ts +45 -17
  88. package/dist/types/contract/src/ids.d.ts +18 -10
  89. package/dist/types/contract/src/import.d.ts +17 -16
  90. package/dist/types/contract/src/index.d.ts +57 -29
  91. package/dist/types/contract/src/integrationGraph.d.ts +83 -0
  92. package/dist/types/contract/src/issueLabels.d.ts +121 -81
  93. package/dist/types/contract/src/issueLabelsEn.d.ts +61 -41
  94. package/dist/types/contract/src/manage.d.ts +16 -7
  95. package/dist/types/contract/src/manageLabels.d.ts +2 -0
  96. package/dist/types/contract/src/manifestText.d.ts +66 -0
  97. package/dist/types/contract/src/messagePort.d.ts +208 -0
  98. package/dist/types/contract/src/migration.d.ts +2 -2
  99. package/dist/types/contract/src/notices.d.ts +37 -0
  100. package/dist/types/contract/src/operationEffects.d.ts +39 -0
  101. package/dist/types/contract/src/operatorOperations.d.ts +104 -110
  102. package/dist/types/contract/src/outbound.d.ts +29 -0
  103. package/dist/types/contract/src/paths.d.ts +13 -0
  104. package/dist/types/contract/src/paymentPort.d.ts +129 -0
  105. package/dist/types/contract/src/pending.d.ts +2 -0
  106. package/dist/types/contract/src/permissions.d.ts +7 -11
  107. package/dist/types/contract/src/perspective.d.ts +26 -0
  108. package/dist/types/contract/src/powers.d.ts +5 -0
  109. package/dist/types/contract/src/principal.d.ts +127 -56
  110. package/dist/types/contract/src/readPages.d.ts +92 -0
  111. package/dist/types/contract/src/recordLabels.d.ts +6 -0
  112. package/dist/types/contract/src/roles.d.ts +7 -4
  113. package/dist/types/contract/src/ruleLabels.d.ts +16 -0
  114. package/dist/types/contract/src/ruleProblems.d.ts +16 -0
  115. package/dist/types/contract/src/schemaLabels.d.ts +8 -0
  116. package/dist/types/contract/src/settingProblems.d.ts +18 -1
  117. package/dist/types/contract/src/settings.d.ts +5 -7
  118. package/dist/types/contract/src/siteDeclaration.d.ts +7 -7
  119. package/dist/types/contract/src/siteIndex.d.ts +76 -0
  120. package/dist/types/contract/src/transfer.d.ts +1 -1
  121. package/dist/types/contract/src/trial.d.ts +4 -1
  122. package/dist/types/contract/src/versions.d.ts +1 -3
  123. package/dist/types/contract/src/viewEvent.d.ts +0 -9
  124. package/dist/types/contract/src/webhooks.d.ts +24 -3
  125. package/dist/types/contract/src/workflow.d.ts +16 -19
  126. package/dist/types/contract/src/workspaceItems.d.ts +23 -7
  127. package/dist/types/contract/src/workspacePaths.d.ts +1 -1
  128. package/dist/types/rich-text/src/html.d.ts +1 -1
  129. package/dist/types/rich-text/src/index.d.ts +8 -7
  130. package/dist/types/rich-text/src/labels/en.d.ts +1 -1
  131. package/dist/types/rich-text/src/labels/ja.d.ts +2 -2
  132. package/dist/types/rich-text/src/library.d.ts +1 -1
  133. package/dist/types/rich-text/src/media.d.ts +2 -0
  134. package/dist/types/rich-text/src/normalize.d.ts +1 -1
  135. package/dist/types/rich-text/src/problems.d.ts +5 -5
  136. package/dist/types/rich-text/src/profile.d.ts +10 -10
  137. package/dist/types/rich-text/src/render.d.ts +1 -1
  138. package/dist/types/rich-text/src/schema.d.ts +2 -2
  139. package/dist/types/rich-text/src/standard.d.ts +4 -4
  140. package/dist/types/rich-text/src/types.d.ts +2 -2
  141. package/dist/types/schema/src/audience.d.ts +1 -3
  142. package/dist/types/schema/src/capabilities.d.ts +18 -27
  143. package/dist/types/schema/src/changes.d.ts +3 -1
  144. package/dist/types/schema/src/collection.d.ts +142 -111
  145. package/dist/types/schema/src/defaultSchema.d.ts +8 -2
  146. package/dist/types/schema/src/fieldIds.d.ts +18 -0
  147. package/dist/types/schema/src/file.d.ts +24 -11
  148. package/dist/types/schema/src/fileRefs.d.ts +14 -0
  149. package/dist/types/schema/src/fileSignature.d.ts +20 -0
  150. package/dist/types/schema/src/filesCollection.d.ts +7 -0
  151. package/dist/types/schema/src/forms.d.ts +43 -0
  152. package/dist/types/schema/src/imageMetadata.d.ts +9 -0
  153. package/dist/types/schema/src/index.d.ts +19 -10
  154. package/dist/types/schema/src/indexes.d.ts +11 -0
  155. package/dist/types/schema/src/input.d.ts +1 -1
  156. package/dist/types/schema/src/integrity.d.ts +8 -7
  157. package/dist/types/schema/src/kinds.d.ts +26 -0
  158. package/dist/types/schema/src/labels/en.d.ts +89 -46
  159. package/dist/types/schema/src/labels/ja.d.ts +92 -46
  160. package/dist/types/schema/src/mediaUrl.d.ts +26 -33
  161. package/dist/types/schema/src/page.d.ts +4 -4
  162. package/dist/types/schema/src/problems.d.ts +85 -42
  163. package/dist/types/schema/src/refs.d.ts +0 -9
  164. package/dist/types/schema/src/schema.d.ts +17 -12
  165. package/dist/types/schema/src/selfOps.d.ts +20 -19
  166. package/dist/types/schema/src/traits.d.ts +28 -0
  167. package/dist/types/schema/src/typesSource.d.ts +1 -1
  168. package/dist/types/schema/src/values.d.ts +5 -2
  169. package/dist/types/schema/src/widening.d.ts +3 -0
  170. package/dist/types/sdk/src/analytics.d.ts +2 -1
  171. package/dist/types/sdk/src/app.d.ts +43 -14
  172. package/dist/types/sdk/src/astro-image.d.ts +19 -0
  173. package/dist/types/sdk/src/astro-response.d.ts +6 -0
  174. package/dist/types/sdk/src/astro-server.d.ts +16 -0
  175. package/dist/types/sdk/src/astro.d.ts +19 -0
  176. package/dist/types/sdk/src/bridge.d.ts +2 -4
  177. package/dist/types/sdk/src/code.d.ts +61 -0
  178. package/dist/types/sdk/src/delegation.d.ts +13 -3
  179. package/dist/types/sdk/src/delivery/changes.d.ts +4 -4
  180. package/dist/types/sdk/src/delivery/client.d.ts +33 -22
  181. package/dist/types/sdk/src/delivery/fields.d.ts +3 -3
  182. package/dist/types/sdk/src/delivery/index.d.ts +3 -3
  183. package/dist/types/sdk/src/delivery/media.d.ts +5 -8
  184. package/dist/types/sdk/src/delivery/query.d.ts +15 -11
  185. package/dist/types/sdk/src/delivery/schema.d.ts +1 -1
  186. package/dist/types/sdk/src/delivery/values.d.ts +10 -14
  187. package/dist/types/sdk/src/delivery.d.ts +2 -2
  188. package/dist/types/sdk/src/dev-operations.d.ts +20 -0
  189. package/dist/types/sdk/src/dev.d.ts +6 -5
  190. package/dist/types/sdk/src/end-users.d.ts +187 -0
  191. package/dist/types/sdk/src/i18n.d.ts +2 -2
  192. package/dist/types/sdk/src/integrations.d.ts +14 -21
  193. package/dist/types/sdk/src/operations.d.ts +17 -0
  194. package/dist/types/sdk/src/preview.d.ts +2 -1
  195. package/dist/types/sdk/src/rich-text.d.ts +2 -2
  196. package/dist/types/sdk/src/schema.d.ts +1 -1
  197. package/dist/types/sdk/src/site/artifact.d.ts +64 -0
  198. package/dist/types/sdk/src/site/build-file.d.ts +30 -0
  199. package/dist/types/sdk/src/site/check-code.d.ts +14 -0
  200. package/dist/types/sdk/src/site/check-text.d.ts +19 -0
  201. package/dist/types/sdk/src/site/cli.d.ts +52 -0
  202. package/dist/types/sdk/src/site/content-type.d.ts +2 -0
  203. package/dist/types/sdk/src/site/labels.d.ts +14 -0
  204. package/dist/types/sdk/src/types.d.ts +1 -1
  205. package/dist/{types-B77qvqPJ.js → types-CYnY-63C.js} +5 -6
  206. package/dist/types.js +1 -1
  207. package/dist/{typesSource-CWybQYus.js → typesSource-BTA9-rcB.js} +17 -15
  208. package/package.json +32 -6
  209. package/dist/apps-BxnJ1RlU.js +0 -435
  210. package/dist/bridge-DtHw9hS6.js +0 -74
  211. package/dist/collection-BEOxeISR.js +0 -189
  212. package/dist/customers-DTbL0qn6.js +0 -86
  213. package/dist/customers.d.ts +0 -1
  214. package/dist/customers.js +0 -185
  215. package/dist/embeds-B5V54Zur.js +0 -34
  216. package/dist/ids--RF7hGyC.js +0 -36
  217. package/dist/src-sazhzYui.js +0 -71
  218. package/dist/types/contract/src/customers.d.ts +0 -266
  219. package/dist/types/schema/src/legacy.d.ts +0 -2
  220. package/dist/types/schema/src/media.d.ts +0 -5
  221. package/dist/types/sdk/src/customers.d.ts +0 -184
package/dist/app.js CHANGED
@@ -1,12 +1,14 @@
1
- import { _ as JSON_BODY_MAX, d as problemEnglish, g as ERROR_STATUS, h as apiIssueText, i as errorText, n as errorBodyFor } from "./errorLabels-BgtQ_zUn.js";
2
- import { t as newUuidV7 } from "./ids--RF7hGyC.js";
3
- import { c as formatMessage, d as problemOf, f as problemText } from "./ja-CeHU0EaY.js";
4
- import { o as TOKEN_EXCHANGE } from "./embeds-B5V54Zur.js";
5
- import { a as accountDelegationOf, i as ownsRow, n as isAdmin, o as customerOf, r as allows, s as principalOfUser } from "./apps-BxnJ1RlU.js";
6
- import { S as isPublishable, b as isPersonalCollection, j as roleFieldOf, l as audienceOf, t as AUDIENCES } from "./collection-BEOxeISR.js";
7
- import { a as CUSTOMER_STATUSES, t as CUSTOMERS_KEY_TARGET } from "./customers-DTbL0qn6.js";
8
- import { l as bodyProblemText, s as embedOfUrl } from "./declared-DuNMsdXw.js";
9
- import { a as mergeStyle, c as ALIGNS, n as isSafeCssValue, o as sortMarks, r as HTML_TAG_MARKS, s as isSafeHref, u as isTableCell } from "./profile-1em_lcxq.js";
1
+ import { _ as JSON_BODY_MAX, a as problemBodyWithoutType, f as problemEnglish, g as apiIssueText, o as problemResponse, r as errorText } from "./errorLabels-BK1NJ6Wz.js";
2
+ import { i as newUuidV7 } from "./ids-DmtIoqBX.js";
3
+ import { c as formatMessage, d as problemOf, f as problemText } from "./ja-axQPxMJ-.js";
4
+ import { _ as MESSAGE_RECEIVED, a as APP_CHANNEL_LIMITS, c as CHANNEL_MODES, d as ADMIN_AREA_OPERATION, g as MESSAGE_PORT, h as MESSAGE_LIMITS, i as APP_CHANNEL_KIND_LIMITS, l as channelSettingPattern, m as BUNDLED_APP_IDS, o as CHANNEL_ADDRESS_KINDS, p as INSTALLATION_TOKEN, r as appToolPrefixOf, s as CHANNEL_CAPABILITIES, u as COLLECTION_SIZE_LIMITS, v as MESSAGE_SKIP_REASONS } from "./apps-BysPfMuR.js";
5
+ import { r as TOKEN_EXCHANGE } from "./embeds-DY6O5TrJ.js";
6
+ import { _ as cyclicCollections, a as PRICE_KINDS, c as priceLookupKeyOf, d as NOTICES_PORT, f as manifestDocumentOf, g as ORIGIN_REF, h as IMPORT_ITEMS_MAX, i as PRICE_INTERVALS, l as isLiveState, n as PAYMENT_PORT, o as PURCHASE_STATUSES, p as END_USER_REF, r as PRICE_CURRENCIES, s as SUBSCRIPTION_STATUSES, t as PAYMENT_LIMITS, u as recordStateOf, v as importIdOf, y as importItemOfRow } from "./paymentPort-p1jV44Zz.js";
7
+ import { a as END_USER_STATUSES, t as END_USERS_KEY_TARGET } from "./endUsers-DODfjnv1.js";
8
+ import { l as richTextProblemText, s as embedOfUrl } from "./declared-CE4a61qb.js";
9
+ import { a as mergeStyle, c as ALIGNS, n as isSafeCssValue, o as sortMarks, r as HTML_TAG_MARKS, s as isSafeHref, u as isTableCell } from "./profile-DBsXLvvI.js";
10
+ import { E as isPublishable, t as AUDIENCES } from "./collection-26aglrg6.js";
11
+ import { z } from "zod";
10
12
  import { parseDocument } from "htmlparser2";
11
13
  // ../rich-text/src/normalize.ts
12
14
  const keyOf = (inline) => "component" in inline ? null : JSON.stringify([
@@ -54,7 +56,7 @@ const normalizeCell = (cell) => isTableCell(cell) ? {
54
56
  content: cell.content.map(normalizeRich)
55
57
  } : normalizeRich(cell);
56
58
  /** 本文を正規化 */
57
- function normalizeBody(body) {
59
+ function normalizeRichText(body) {
58
60
  return body.map((block) => {
59
61
  switch (block.type) {
60
62
  case "paragraph":
@@ -181,7 +183,7 @@ const intOf = (v) => {
181
183
  return Number.isFinite(n) && n > 0 ? n : void 0;
182
184
  };
183
185
  /** HTML を本文に(コピーできないものは dropped) */
184
- function bodyFromHtml(html, options) {
186
+ function richTextFromHtml(html, options) {
185
187
  const counts = /* @__PURE__ */ new Map();
186
188
  const drop = (what) => counts.set(what, (counts.get(what) ?? 0) + 1);
187
189
  const alignOf = (el) => {
@@ -190,9 +192,9 @@ function bodyFromHtml(html, options) {
190
192
  };
191
193
  /** 要素の属性と style のうち、コピーできないものを数える(used はコピーした style の項目) */
192
194
  const audit = (el, used = []) => {
193
- for (const name of Object.keys(el.attribs)) if (name.startsWith("on")) drop(bodyProblemText("drop_attribute", { name }));
194
- else if (!SILENT_ATTRS.has(name) && !name.startsWith("data-") && !name.startsWith("aria-")) drop(bodyProblemText("drop_attribute", { name }));
195
- for (const key of declarations(el).keys()) if (!used.includes(key)) drop(bodyProblemText("drop_style", { key }));
195
+ for (const name of Object.keys(el.attribs)) if (name.startsWith("on")) drop(richTextProblemText("drop_attribute", { name }));
196
+ else if (!SILENT_ATTRS.has(name) && !name.startsWith("data-") && !name.startsWith("aria-")) drop(richTextProblemText("drop_attribute", { name }));
197
+ for (const key of declarations(el).keys()) if (!used.includes(key)) drop(richTextProblemText("drop_style", { key }));
196
198
  };
197
199
  const classesOf = (el) => (el.attribs.class ?? "").split(/\s+/).filter(Boolean);
198
200
  /** span などの見た目(コピーできない class と style の項目は数える) */
@@ -205,7 +207,7 @@ function bodyFromHtml(html, options) {
205
207
  if (!value) continue;
206
208
  used.push(key);
207
209
  if (!isSafeCssValue(kind, value)) {
208
- drop(bodyProblemText("drop_style_value", { key }));
210
+ drop(richTextProblemText("drop_style_value", { key }));
209
211
  continue;
210
212
  }
211
213
  const name = options.nameOf?.(kind, value);
@@ -217,7 +219,7 @@ function bodyFromHtml(html, options) {
217
219
  if (decls.has("text-align")) used.push("text-align");
218
220
  const kept = classesOf(el).filter((c) => {
219
221
  if (options.styleClass?.(c)) return true;
220
- drop(bodyProblemText("drop_class", { name: c }));
222
+ drop(richTextProblemText("drop_class", { name: c }));
221
223
  return false;
222
224
  });
223
225
  if (kept.length) style.styles = kept;
@@ -228,7 +230,7 @@ function bodyFromHtml(html, options) {
228
230
  const href = el.attribs.href?.trim();
229
231
  if (!href) return void 0;
230
232
  if (!isSafeHref(href)) {
231
- drop(bodyProblemText("drop_unsafe_link"));
233
+ drop(richTextProblemText("drop_unsafe_link"));
232
234
  return;
233
235
  }
234
236
  const rel = el.attribs.rel?.trim();
@@ -254,7 +256,7 @@ function bodyFromHtml(html, options) {
254
256
  if (!isElement(node)) return [];
255
257
  const name = node.name.toLowerCase();
256
258
  if (DANGEROUS.has(name) || name === "iframe") {
257
- drop(bodyProblemText("drop_element", { name }));
259
+ drop(richTextProblemText("drop_element", { name }));
258
260
  return [];
259
261
  }
260
262
  if (name === "br") return ["\n"];
@@ -263,7 +265,7 @@ function bodyFromHtml(html, options) {
263
265
  img: node,
264
266
  ...ctx.link ? { link: ctx.link } : {}
265
267
  });
266
- else drop(bodyProblemText("drop_inline_image"));
268
+ else drop(richTextProblemText("drop_inline_image"));
267
269
  return [];
268
270
  }
269
271
  const mark = HTML_TAG_MARKS[name];
@@ -288,7 +290,7 @@ function bodyFromHtml(html, options) {
288
290
  style: mergeStyle(ctx.style, style)
289
291
  });
290
292
  }
291
- if (!BLOCK_TAGS.has(name)) drop(bodyProblemText("drop_element", { name }));
293
+ if (!BLOCK_TAGS.has(name)) drop(richTextProblemText("drop_element", { name }));
292
294
  return inlines(node.children, ctx);
293
295
  });
294
296
  /** 断片の列(images があれば中の画像をそこへ集める) */
@@ -312,7 +314,7 @@ function bodyFromHtml(html, options) {
312
314
  const hasText = (r) => r.some((i) => typeof i === "string" ? i.trim() : "text" in i ? (i.text ?? "").trim() : true);
313
315
  /** 集めた画像を画像のブロックに(where は数える場所) */
314
316
  const hoistedBlocks = (images, where) => images.flatMap(({ img, link }) => {
315
- drop(bodyProblemText("drop_hoisted_image", { where }));
317
+ drop(richTextProblemText("drop_hoisted_image", { where }));
316
318
  const image = imageOf(img, link ? { link } : {});
317
319
  return image ? [image] : [];
318
320
  });
@@ -331,7 +333,7 @@ function bodyFromHtml(html, options) {
331
333
  };
332
334
  /** キャプション・表の説明の文字(文字だけの項目のため、装飾は捨てて数える、中の画像は images へ) */
333
335
  const captionText = (el, images) => {
334
- if (rich(el.children, images).some((i) => typeof i !== "string")) drop(bodyProblemText("drop_caption_marks"));
336
+ if (rich(el.children, images).some((i) => typeof i !== "string")) drop(richTextProblemText("drop_caption_marks"));
335
337
  return textOf(el.children.filter((c) => !(isElement(c) && c.name === "img"))).trim();
336
338
  };
337
339
  const HEADINGS = /* @__PURE__ */ new Set([
@@ -363,38 +365,38 @@ function bodyFromHtml(html, options) {
363
365
  const name = el.name.toLowerCase();
364
366
  if (name === "p") push(rich(el.children, images));
365
367
  else if (name === "ul" || name === "ol") {
366
- drop(bodyProblemText("drop_flattened", {
368
+ drop(richTextProblemText("drop_flattened", {
367
369
  where,
368
370
  what: "list"
369
371
  }));
370
372
  listParagraphs(listOf(el, images), "").forEach(push);
371
373
  } else if (HEADINGS.has(name)) {
372
- drop(bodyProblemText("drop_flattened", {
374
+ drop(richTextProblemText("drop_flattened", {
373
375
  where,
374
376
  what: "heading"
375
377
  }));
376
378
  push(rich(el.children, images));
377
379
  } else if (name === "blockquote") {
378
- drop(bodyProblemText("drop_flattened", {
380
+ drop(richTextProblemText("drop_flattened", {
379
381
  where,
380
382
  what: "quote"
381
383
  }));
382
384
  paragraphsOf(el.children, where, images).forEach(push);
383
385
  } else if (name === "pre") {
384
- drop(bodyProblemText("drop_flattened", {
386
+ drop(richTextProblemText("drop_flattened", {
385
387
  where,
386
388
  what: "code"
387
389
  }));
388
390
  push([textOf(el.children).replace(/\n$/, "")]);
389
391
  } else if (name === "table") {
390
- drop(bodyProblemText("drop_flattened", {
392
+ drop(richTextProblemText("drop_flattened", {
391
393
  where,
392
394
  what: "table"
393
395
  }));
394
396
  for (const tr of findAll(el, (e) => e.name === "tr")) push(normalizeRich(tr.children.filter((c) => isElement(c) && (c.name === "td" || c.name === "th")).flatMap((td, i) => [...i ? [" / "] : [], ...paragraphsOf(td.children, where, images).flatMap((r, j) => [...j ? [" "] : [], ...r])])));
395
397
  } else if (name === "img") images.push({ img: el });
396
398
  else if (name === "figure") {
397
- drop(bodyProblemText("drop_flattened", {
399
+ drop(richTextProblemText("drop_flattened", {
398
400
  where,
399
401
  what: "figure"
400
402
  }));
@@ -405,7 +407,7 @@ function bodyFromHtml(html, options) {
405
407
  const figcaption = findDeep(el, (e) => e.name === "figcaption");
406
408
  if (figcaption) push([captionText(figcaption, [])]);
407
409
  } else if (CONTAINERS.has(name)) paragraphsOf(el.children, where, images).forEach(push);
408
- else drop(bodyProblemText("drop_inner_element", {
410
+ else drop(richTextProblemText("drop_inner_element", {
409
411
  where,
410
412
  name
411
413
  }));
@@ -430,7 +432,7 @@ function bodyFromHtml(html, options) {
430
432
  };
431
433
  const embedBlock = (url, el) => {
432
434
  if (!url || !URL.parse(url)) {
433
- drop(bodyProblemText("drop_embed_no_url"));
435
+ drop(richTextProblemText("drop_embed_no_url"));
434
436
  return null;
435
437
  }
436
438
  const target = embedOfUrl(url);
@@ -447,7 +449,7 @@ function bodyFromHtml(html, options) {
447
449
  }
448
450
  };
449
451
  if (!url.startsWith("https://")) {
450
- drop(bodyProblemText("drop_embed_not_https"));
452
+ drop(richTextProblemText("drop_embed_not_https"));
451
453
  return null;
452
454
  }
453
455
  return {
@@ -479,7 +481,7 @@ function bodyFromHtml(html, options) {
479
481
  const imageOf = (img, extra = {}) => {
480
482
  const src = img.attribs.src?.trim();
481
483
  if (!src) {
482
- drop(bodyProblemText("drop_image_no_src"));
484
+ drop(richTextProblemText("drop_image_no_src"));
483
485
  return null;
484
486
  }
485
487
  const alt = img.attribs.alt?.trim();
@@ -487,7 +489,7 @@ function bodyFromHtml(html, options) {
487
489
  const height = intOf(img.attribs.height);
488
490
  return {
489
491
  type: "image",
490
- media: options.image(src, {
492
+ file: options.image(src, {
491
493
  ...alt ? { alt } : {},
492
494
  ...width ? { width } : {},
493
495
  ...height ? { height } : {}
@@ -500,11 +502,11 @@ function bodyFromHtml(html, options) {
500
502
  const listOf = (el, images) => {
501
503
  const items = el.children.filter(isElement).flatMap((li) => {
502
504
  if (li.name !== "li") {
503
- drop(bodyProblemText("drop_list_element", { name: li.name }));
505
+ drop(richTextProblemText("drop_list_element", { name: li.name }));
504
506
  return [];
505
507
  }
506
508
  const nestedLists = li.children.filter((c) => isElement(c) && (c.name === "ul" || c.name === "ol"));
507
- if (nestedLists.length > 1) drop(bodyProblemText("drop_extra_nested_list"));
509
+ if (nestedLists.length > 1) drop(richTextProblemText("drop_extra_nested_list"));
508
510
  const inner = li.children.filter((c) => !nestedLists.includes(c));
509
511
  const paragraphs = inner.filter((c) => isElement(c) && c.name === "p");
510
512
  const content = paragraphs.length ? normalizeRich(paragraphs.flatMap((p, i) => [...i ? ["\n"] : [], ...rich(p.children, images)])) : rich(inner, images);
@@ -530,7 +532,7 @@ function bodyFromHtml(html, options) {
530
532
  if (!isElement(c)) continue;
531
533
  if (c.name === "tr") rows.push(c);
532
534
  else if (c.name === "thead" || c.name === "tbody" || c.name === "tfoot") collect(c);
533
- else if (c.name !== "caption" && c.name !== "colgroup") drop(bodyProblemText("drop_table_element", { name: c.name }));
535
+ else if (c.name !== "caption" && c.name !== "colgroup") drop(richTextProblemText("drop_table_element", { name: c.name }));
534
536
  }
535
537
  };
536
538
  collect(el);
@@ -577,7 +579,7 @@ function bodyFromHtml(html, options) {
577
579
  return DANGEROUS.has(name) || BLOCK_TAGS.has(name) || name === "a" && el.attribs["data-embed-type"] === "file" && Boolean(options.file);
578
580
  }, (run) => out.push(...paragraphBlocks(run, void 0)), (el) => {
579
581
  const name = el.name.toLowerCase();
580
- if (DANGEROUS.has(name)) drop(bodyProblemText("drop_element", { name }));
582
+ if (DANGEROUS.has(name)) drop(richTextProblemText("drop_element", { name }));
581
583
  else if (name === "a") out.push(fileOf(el));
582
584
  else out.push(...blockOf(el));
583
585
  });
@@ -619,7 +621,7 @@ function bodyFromHtml(html, options) {
619
621
  const name = textOf(a.children).trim();
620
622
  return {
621
623
  type: "file",
622
- media: options.file(a.attribs.href ?? "", {
624
+ file: options.file(a.attribs.href ?? "", {
623
625
  ...a.attribs["data-mime-type"] ? { mime: a.attribs["data-mime-type"] } : {},
624
626
  ...name ? { name } : {}
625
627
  }),
@@ -717,27 +719,30 @@ function bodyFromHtml(html, options) {
717
719
  }
718
720
  };
719
721
  return {
720
- body: normalizeBody(blocks(parseDocument(html, { decodeEntities: true }).children)),
722
+ body: normalizeRichText(blocks(parseDocument(html, { decodeEntities: true }).children)),
721
723
  dropped: [...counts].map(([what, count]) => ({
722
724
  what,
723
725
  count
724
726
  }))
725
727
  };
726
728
  }
727
- // ../contract/src/identifiers.ts
729
+ // ../contract/src/appMail.ts
730
+ /** 能力の要素(送信、受信) */
731
+ const MAIL_CAPABILITIES = {
732
+ send: "mail:send",
733
+ inbound: "mail:inbound"
734
+ };
728
735
  /**
729
- * インストールのトークンの形(GitHub App の形: アプリの鍵で署名したアプリの JWT と交換する)
730
- * - JWS のコンパクトな形。発行と検証はどちらも Tunasand だけで、署名の鍵は SECRETS_KEY からプロジェクトごとに HKDF で導く
731
- * - アプリの JWT: ES256 か RS256、iss はアプリの ID、aud はプロジェクトの配信の基点、exp − iat は appJwtMaxSec 秒まで
732
- * - 時計のずれ: iat の未来と exp の過去を skewSec 秒まで許す
736
+ * 送らなかった理由
737
+ * - suppressed: 抑止の一覧、no_consent: 同意の目的で送れない
738
+ * - domain_unverified: 差出人のドメインが検証されていない、test_environment: live 以外の環境
733
739
  */
734
- const INSTALLATION_TOKEN = {
735
- typ: "tunasand-installation+jwt",
736
- alg: "HS256",
737
- ttlSec: 3600,
738
- appJwtMaxSec: 600,
739
- skewSec: 60
740
- };
740
+ const APP_MAIL_SKIP_REASONS = [
741
+ "suppressed",
742
+ "no_consent",
743
+ "domain_unverified",
744
+ "test_environment"
745
+ ];
741
746
  // ../contract/src/appProblems.ts
742
747
  /** 問題の表から、問題を作る関数(差し込みの不足は型の誤り) */
743
748
  function appProblems(tables) {
@@ -774,107 +779,63 @@ var SettingProblem = class extends Error {
774
779
  this.params = params;
775
780
  }
776
781
  };
782
+ /** 設定値の問題の既定の形(field は項目名) */
783
+ const settingProblemText = (p, field) => problemText({
784
+ code: `setting_${p.problem}`,
785
+ params: {
786
+ ...p.params,
787
+ field
788
+ }
789
+ });
790
+ /**
791
+ * 繰り返しフィールド(repeater)の値の検証(不正な値は例外)
792
+ * - 行番号 row は1から、sub はフィールドの表示名
793
+ * - 定義にないフィールドと、任意のフィールドの空文字は除外する
794
+ */
795
+ function settingRowsOf(key, value, fields) {
796
+ if (!Array.isArray(value)) throw new SettingProblem(key, "shape");
797
+ return value.map((input, i) => {
798
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw new SettingProblem(key, "shape");
799
+ const row = input;
800
+ const entries = fields.flatMap((f) => {
801
+ const v = row[f.key];
802
+ if (v !== void 0 && typeof v !== "string") throw new SettingProblem(key, "row_text", {
803
+ row: i + 1,
804
+ sub: f.label
805
+ });
806
+ const text = v?.trim() ?? "";
807
+ if (!text && f.required) throw new SettingProblem(key, "row_text", {
808
+ row: i + 1,
809
+ sub: f.label
810
+ });
811
+ return text ? [[f.key, text]] : [];
812
+ });
813
+ return Object.fromEntries(entries);
814
+ });
815
+ }
777
816
  // ../contract/src/workspaceItems.ts
778
817
  /** 日付のフィールドの予定が持つ source(`field:<コレクション>.<フィールド>`) */
779
818
  const calendarFieldSource = (f) => `field:${f.collection}.${f.field}`;
780
819
  // ../contract/src/appDefinition.ts
781
820
  /** 設定値のないアプリの設定値の解釈 */
782
821
  const NO_SETTINGS = { parse: () => ({}) };
783
- // ../contract/src/fieldAccess.ts
784
- const ALL = /* @__PURE__ */ new Set([
785
- "public",
786
- "granted",
787
- "self",
788
- "staff"
789
- ]);
790
- /** 配信 API に出せる見える範囲(公開とアクセス権、* の範囲) */
791
- const DELIVERED = /* @__PURE__ */ new Set(["public", "granted"]);
792
- /** MCP にスタッフの項目を出すコレクションの見える範囲(本人の項目は除く) */
793
- const STAFF_FOR_MCP = /* @__PURE__ */ new Set([
794
- "public",
795
- "granted",
796
- "staff"
797
- ]);
798
- /** 能力のうちコレクション target を名指しした操作(* を除く) */
799
- const namedOps = (capabilities, target) => Object.hasOwn(capabilities, target) && target !== "*" ? capabilities[target] : [];
800
- /** 能力の操作(名指しと * の和) */
801
- const opsOf = (capabilities, target) => [...namedOps(capabilities, target), ...Object.hasOwn(capabilities, "*") ? capabilities["*"] : []];
802
- const READS = ["read", "read_drafts"];
803
- /** 主体がコレクションのレコードで見られる見える範囲 */
804
- function audiencesFor(reader, collection) {
805
- if (reader === "system") return ALL;
806
- if (reader.effective.form === "roles") {
807
- const delegation = accountDelegationOf(reader);
808
- if (!delegation) return ALL;
809
- if (delegation.kind === "app") return namedOps(delegation.consented, collection.id).some((op) => READS.includes(op)) ? ALL : DELIVERED;
810
- const { permissions } = reader.effective;
811
- return (permissions[collection.id]?.read ?? permissions["*"]?.read ?? "none") !== "none" && !isPersonalCollection(collection) && delegation.staffCollections.includes(collection.id) ? STAFF_FOR_MCP : DELIVERED;
812
- }
813
- const { capabilities } = reader.effective;
814
- if (!customerOf(reader) && namedOps(capabilities, collection.id).some((op) => READS.includes(op))) return ALL;
815
- const out = /* @__PURE__ */ new Set(["public"]);
816
- if (opsOf(capabilities, collection.id).includes("read_customers")) out.add("granted");
817
- return out;
818
- }
819
- /** コレクションの最上位の項目を見られるか(読み替えは schema のパッケージの audienceOf) */
820
- const canReadField = (audiences, field, collection) => audiences.has(audienceOf(field, collection));
821
- /** レコードの題(題の項目を見られなければレコードの ID、題の項目がなければ ID) */
822
- function titleFor(audiences, collection, values, id) {
823
- const field = roleFieldOf(collection, "title");
824
- const value = field && canReadField(audiences, field, collection) ? values[field.key] : null;
825
- return typeof value === "string" && value ? value : id;
826
- }
827
- // ../contract/src/import.ts
828
- /** 1回のリクエストで取り込む件数の上限(画像の取得の時間と、本文の大きさの上限 JSON_BODY_MAX のため) */
829
- const IMPORT_ITEMS_MAX = 50;
830
- /** 参照の項目の値で、同じ取り出し元の元の ID を指す形の印({ "$origin": "<元の ID>" }) */
831
- const ORIGIN_REF = "$origin";
832
- /** 顧客フィールドの値で、人の元の ID を指す形の印({ "$customer": "<元の ID>" }) */
833
- const CUSTOMER_REF = "$customer";
834
- /** 元の ID を指す値の元の ID(印 marker の1つのキーで値が文字列、ほかは null) */
835
- function originIdOf(value, marker) {
836
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
837
- const records = Object.entries(value);
838
- return records.length === 1 && records[0][0] === marker && typeof records[0][1] === "string" ? records[0][1] : null;
839
- }
840
- const isOriginRef = (v) => originIdOf(v, ORIGIN_REF) !== null;
841
- /** 元の ID を指す参照({ "$origin" })を除いた値(まとまりの中と配列の要素も。循環の1段目の項目) */
842
- function withoutOrigins(value) {
843
- if (Array.isArray(value)) return value.filter((v) => !isOriginRef(v)).map(withoutOrigins);
844
- if (typeof value !== "object" || value === null) return value;
845
- return Object.fromEntries(Object.entries(value).flatMap(([k, v]) => isOriginRef(v) ? [] : [[k, withoutOrigins(v)]]));
846
- }
847
- /** 入力の形のレコードを取り込みの1件に(at は報告の位置、phase はコレクションどうしの循環のフェーズで、1段目は参照を除く) */
848
- const importItemOfRow = (line, at, phase) => ({
849
- collection: line.collection,
850
- ...line.new_id !== void 0 && { id: line.new_id },
851
- fields: phase === 1 ? withoutOrigins(line.fields) : line.fields,
852
- source: at,
853
- origin_id: line.id,
854
- ...phase !== void 0 && { phase },
855
- ...line.created_at !== void 0 && { created_at: line.created_at }
856
- });
857
- /** 取り込む ID(前後の空白を除き小文字に、changed は大文字を含んでいた) */
858
- function importIdOf(raw) {
859
- const trimmed = raw.trim();
860
- const id = trimmed.toLowerCase();
861
- return {
862
- id,
863
- changed: id !== trimmed
864
- };
865
- }
866
- /** 関係が循環する API のエンドポイント(関係をたどって自分に戻る、自分への関係を含む。参照なしと参照ありの2フェーズで取り込む) */
867
- function cyclicCollections(apis) {
868
- const reaches = (from, goal, seen) => Object.values(from.relations).some((target) => {
869
- if (target === goal) return true;
870
- if (seen.has(target)) return false;
871
- seen.add(target);
872
- const next = apis.find((x) => x.endpoint === target);
873
- return next ? reaches(next, goal, seen) : false;
874
- });
875
- return new Set(apis.filter((a) => reaches(a, a.endpoint, /* @__PURE__ */ new Set())).map((a) => a.endpoint));
876
- }
877
822
  // ../contract/src/app.ts
823
+ /**
824
+ * 管理の API の一覧を、続きのカーソル next_cursor が尽きるまで読む(読めなければその応答)
825
+ * - path は一覧の経路(クエリを含めてよい)。1要求ごとに件数と走査の上限は効く
826
+ */
827
+ async function cmsListAll(cms, path) {
828
+ const items = [];
829
+ let next = null;
830
+ do {
831
+ const res = await cms.fetch(next === null ? path : `${path}${path.includes("?") ? "&" : "?"}cursor=${encodeURIComponent(next)}`);
832
+ if (!res.ok) return res;
833
+ const page = await res.json();
834
+ items.push(...page.data);
835
+ next = page.next_cursor;
836
+ } while (next !== null);
837
+ return items;
838
+ }
878
839
  /** 外への読み込みの宛先の宣言に URL が当たるか(宣言は https のオリジン、ホスト名の先頭の `*.` は1つ以上の区間。https だけ、ポートの指定なし) */
879
840
  function egressAllows(declared, url) {
880
841
  if (url.protocol !== "https:" || url.port !== "") return false;
@@ -884,27 +845,75 @@ function egressAllows(declared, url) {
884
845
  return m[1] ? url.hostname.endsWith(`.${m[2]}`) : url.hostname === m[2];
885
846
  });
886
847
  }
848
+ // ../contract/src/appServer.ts
849
+ /** 集計の作り直しの処理の ID(実行の記録と、運営者の経路の名指し) */
850
+ const aggregateJobIdOf = (app, collection) => `${app}.${collection}`;
851
+ /** アプリ用の状態の置き場の上限(キーの字数、値の JSON の UTF-8 のバイト数、インストールごとのキーの数) */
852
+ const APP_STATE_LIMITS = {
853
+ keyMaxChars: 200,
854
+ valueMaxBytes: 16384,
855
+ keysMax: 200
856
+ };
857
+ /**
858
+ * 一覧のページを next が尽きるまで読む(ページ送りの画面を持たない利用者の仮の形。1要求ごとの上限は効き、拒否はそのページの拒否)
859
+ */
860
+ async function allRecordPages(read) {
861
+ const records = [];
862
+ let cursor;
863
+ do {
864
+ const page = await read(cursor === void 0 ? {} : { cursor });
865
+ if (!page.ok) return page;
866
+ records.push(...page.value.records);
867
+ cursor = page.value.next ?? void 0;
868
+ } while (cursor !== void 0);
869
+ return {
870
+ ok: true,
871
+ value: records
872
+ };
873
+ }
874
+ /**
875
+ * アプリの口の呼ぶ側の誤りのコード(アプリのコードを直すまで回復しない。結果にせず、このコードを code に持つ UsageError を投げる)
876
+ * - 宣言のないコレクション・イベント・秘密値・ポート・メール・チャネルの種類、未登録の発行者、DB だけの文脈、この環境に入っていない
877
+ */
878
+ const APP_USAGE_ERRORS = [
879
+ "app_collection_undeclared",
880
+ "app_event_undeclared",
881
+ "app_secret_undeclared",
882
+ "app_port_undeclared",
883
+ "app_scope_without_bindings",
884
+ "app_not_installed",
885
+ "end_user_identity_unregistered",
886
+ "app_channel_undeclared",
887
+ "app_mail_undeclared"
888
+ ];
889
+ /** ファイルの読み出しの上限(バイト数) */
890
+ const APP_FILE_LIMITS = { readMaxBytes: 10485760 };
891
+ /** アプリがアカウントへ送れる知らせの種類(レコードの新着、担当の割り当て。件名と本文はコアの定型) */
892
+ const APP_NOTICE_KINDS = ["record_received", "record_assigned"];
893
+ /** アカウントへの知らせの上限(1回の宛先の数) */
894
+ const APP_NOTIFY_LIMITS = { accountsMax: 50 };
887
895
  // ../contract/src/workspacePaths.ts
888
- /** ワークスペースのコレクションの経路(URL はレコードのスラッグ、record を省くと一覧) */
889
- const workspaceRecordPath = (collection, record) => `/collections/${encodeURIComponent(collection.slug)}/records${record === void 0 ? "" : `/${encodeURIComponent(String(record.slug))}`}`;
896
+ /** ワークスペースのコレクションの経路(コレクションはスラッグ、レコードは UUID、record を省くと一覧) */
897
+ const workspaceRecordPath = (collection, record) => `/collections/${encodeURIComponent(collection.slug)}/records${record === void 0 ? "" : `/${encodeURIComponent(String(record.id))}`}`;
890
898
  // src/delegation.ts
891
899
  /** アプリの JWT の有効の秒数(INSTALLATION_TOKEN.appJwtMaxSec の内) */
892
900
  const ASSERTION_TTL_SEC = 60;
893
901
  const base64Url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
894
902
  const textPart = (value) => base64Url(new TextEncoder().encode(JSON.stringify(value)));
895
- /** アプリの JWT(iss はアプリの ID、aud は環境の CMS の URL) */
903
+ /** アプリの JWT(iss はアプリの ID、aud は配信の基点) */
896
904
  async function appAssertion(key, claims, nowMs = Date.now()) {
897
905
  const { kid, ...jwk } = key.jwk;
906
+ const pq = jwk.kty === "AKP";
898
907
  const signer = await crypto.subtle.importKey("jwk", {
899
908
  ...jwk,
900
909
  key_ops: ["sign"]
901
- }, {
910
+ }, pq ? { name: "ML-DSA-44" } : {
902
911
  name: "ECDSA",
903
912
  namedCurve: "P-256"
904
913
  }, false, ["sign"]);
905
914
  const iat = Math.floor(nowMs / 1e3);
906
915
  const input = `${textPart({
907
- alg: "ES256",
916
+ alg: pq ? "ML-DSA-44" : "ES256",
908
917
  typ: "JWT",
909
918
  ...kid && { kid }
910
919
  })}.${textPart({
@@ -913,26 +922,45 @@ async function appAssertion(key, claims, nowMs = Date.now()) {
913
922
  iat,
914
923
  exp: iat + Math.min(ASSERTION_TTL_SEC, INSTALLATION_TOKEN.appJwtMaxSec)
915
924
  })}`;
916
- const signature = new Uint8Array(await crypto.subtle.sign({
925
+ const signature = new Uint8Array(await crypto.subtle.sign(pq ? { name: "ML-DSA-44" } : {
917
926
  name: "ECDSA",
918
927
  hash: "SHA-256"
919
928
  }, signer, new TextEncoder().encode(input)));
920
929
  return `${input}.${base64Url(signature)}`;
921
930
  }
931
+ /** 交換するトークンの iss(配信の基点。読めなければ null。署名は交換の側が検証する) */
932
+ function issuerOf(token) {
933
+ try {
934
+ const part = token.split(".")[1] ?? "";
935
+ const claims = JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/")));
936
+ return typeof claims.iss === "string" ? claims.iss : null;
937
+ } catch {
938
+ return null;
939
+ }
940
+ }
922
941
  /** 代理の委任の主張をアカウントの資格のトークンに替える */
923
- async function exchangeDelegation(input) {
942
+ const exchangeDelegation = (input) => exchanged(input, input.delegation);
943
+ /** 画面のトークンをアカウントの資格のトークンに替える(結果の形は exchangeDelegation と同じ) */
944
+ const exchangeSessionToken = (input) => exchanged(input, input.sessionToken);
945
+ async function exchanged(input, subject) {
924
946
  const send = input.fetch ?? ((request) => fetch(request));
947
+ const audience = issuerOf(subject);
948
+ if (!audience) return {
949
+ ok: false,
950
+ error: "invalid_grant",
951
+ status: 0
952
+ };
925
953
  const body = new URLSearchParams({
926
954
  grant_type: TOKEN_EXCHANGE.grantType,
927
- subject_token: input.delegation,
955
+ subject_token: subject,
928
956
  subject_token_type: TOKEN_EXCHANGE.subjectTokenType,
929
957
  client_assertion_type: TOKEN_EXCHANGE.clientAssertionType,
930
958
  client_assertion: await appAssertion(input.key, {
931
959
  appId: input.appId,
932
- audience: input.base
960
+ audience
933
961
  })
934
962
  });
935
- const res = await send(new Request(`${input.base}/api/embeds/token`, {
963
+ const res = await send(new Request(`${input.base}${TOKEN_EXCHANGE.path}`, {
936
964
  method: "POST",
937
965
  headers: { "content-type": "application/x-www-form-urlencoded" },
938
966
  body: body.toString()
@@ -959,6 +987,68 @@ const bearerClient = (input) => ({ fetch: (path, init = {}) => {
959
987
  });
960
988
  return input.fetch ? input.fetch(request) : fetch(request);
961
989
  } });
990
+ // ../contract/src/api/define.ts
991
+ /** ワークスペースの経路の資格の組(人のログイン、MCP、人の代理のアプリ) */
992
+ const PERSON = ["session", "mcp"];
993
+ const DELEGABLE = [
994
+ "session",
995
+ "mcp",
996
+ "account_token"
997
+ ];
998
+ /** 行の数に上限のある一覧の宣言(order は並べ替えのキー、先頭の - は降順の既定。size は上限の定数のキーで、1ページで上限までの全件を返す) */
999
+ const boundedList = (defaultOrder, size) => {
1000
+ const limit = COLLECTION_SIZE_LIMITS[size];
1001
+ return {
1002
+ keys: "fixed",
1003
+ indexes: [],
1004
+ bounded: {
1005
+ keys: [defaultOrder.replace(/^-/, "")],
1006
+ size
1007
+ },
1008
+ defaultOrder,
1009
+ filters: {},
1010
+ limit: {
1011
+ default: limit,
1012
+ max: limit
1013
+ }
1014
+ };
1015
+ };
1016
+ /**
1017
+ * アプリのコレクションをレコードの口のページ(作成の新しい順、続きは口のカーソル)で読むアプリの経路の一覧の宣言
1018
+ * - collection はマニフェストのコレクションの名前。索引の表は c_{<名前>}(インストールで決まるコレクションの表)
1019
+ * - filters はレコードの口の where に渡す絞り込み(索引の後の条件で、走査の上限で打ち切る)
1020
+ */
1021
+ const appRecordList = (collection, filters = {}) => ({
1022
+ keys: "fixed",
1023
+ indexes: [{
1024
+ name: `i_c_{${collection}}_created_at`,
1025
+ table: `c_{${collection}}`,
1026
+ order: "created_at",
1027
+ where: "deleted_at IS NULL"
1028
+ }],
1029
+ defaultOrder: "-created_at",
1030
+ filters
1031
+ });
1032
+ /** 一覧の応答(data はページの資源、next_cursor は続きがない場合だけ null) */
1033
+ const pageOf = (item) => z.object({
1034
+ data: z.array(item),
1035
+ next_cursor: z.string().nullable()
1036
+ });
1037
+ z.object({
1038
+ count: z.int().min(0).max(2 ** 31 - 1),
1039
+ capped: z.boolean()
1040
+ });
1041
+ /** 型を文書に書かないオブジェクト(中身はコンテンツスキーマとアプリの宣言が決める) */
1042
+ const OBJECT = z.record(z.string(), z.unknown());
1043
+ z.iso.datetime({ offset: true });
1044
+ z.int().min(0).max(2 ** 31 - 1);
1045
+ z.looseObject({
1046
+ id: z.string(),
1047
+ _meta: OBJECT.optional()
1048
+ }).meta({
1049
+ id: "Record",
1050
+ description: "record values; fields follow the content schema (docs/specs/values.md); _meta is left out when fields selects other fields"
1051
+ });
962
1052
  // src/app.ts
963
1053
  /** 相関の ID のヘッダー(CMS の応答とログと同じ名前) */
964
1054
  const REQUEST_ID_HEADER = "x-request-id";
@@ -979,17 +1069,30 @@ function appFailureOf(targets) {
979
1069
  return (request, code, params, extra = {}) => {
980
1070
  const given = request.headers.get(REQUEST_ID_HEADER);
981
1071
  const requestId = given && REQUEST_ID_FORM.test(given) ? given : newUuidV7();
982
- return Response.json({
983
- ...errorBodyFor(code, requestId, params),
984
- message: errorText(code, params, targets),
985
- ...extra,
986
- requestId
987
- }, {
988
- status: ERROR_STATUS[code],
989
- headers: { [REQUEST_ID_HEADER]: requestId }
990
- });
1072
+ const { issues, ...rest } = extra;
1073
+ return problemResponse(problemBodyWithoutType(code, requestId, {
1074
+ ...params && { params },
1075
+ detail: errorText(code, params, targets),
1076
+ ...rest,
1077
+ ...issues && { issues: [...issues] }
1078
+ }), { [REQUEST_ID_HEADER]: requestId });
991
1079
  };
992
1080
  }
1081
+ /** アプリの口の拒否の応答(CMS の API と同じ problem+json。状態はコードから) */
1082
+ const appPortResponse = (request, failure) => appFailure(request, failure.error, failure.params, failure.issues?.length ? { issues: failure.issues.map(appIssue) } : {});
1083
+ /** 値のない成功の結果 */
1084
+ const PORT_DONE = {
1085
+ ok: true,
1086
+ value: void 0
1087
+ };
1088
+ /**
1089
+ * 結果の値(拒否は app_port_refused: <コード> の Error で投げる)
1090
+ * - 拒否を想定しない処理(定期の処理が自分のコレクションを読むなど)だけで使う。利用者の操作の拒否は appPortResponse で返す
1091
+ */
1092
+ function portValue(result) {
1093
+ if (result.ok) return result.value;
1094
+ throw new Error(`app_port_refused: ${result.error}`);
1095
+ }
993
1096
  /** 本文の JSON(空の本文は empty、壊れた JSON は400の応答) */
994
1097
  async function appJson(request, empty = null) {
995
1098
  const text = await request.text();
@@ -1022,10 +1125,17 @@ function appInvalid(request, error, problems = {}) {
1022
1125
  });
1023
1126
  return appFailure(request, "invalid_input", void 0, { issues });
1024
1127
  }
1025
- /** 呼んだ人のアカウント(管理の API の /api/me、失敗は例外) */
1128
+ /** 呼んだ人がコレクションに行える操作の ID(管理の API の /api/schema の viewer_can。record.list、record.create など、失敗は例外) */
1129
+ async function appCollectionCan(ctx, collection) {
1130
+ const res = await ctx.cms.fetch("/api/schema");
1131
+ if (!res.ok) throw new Error(`app_schema_unavailable: ${res.status}`);
1132
+ const { viewer_can: viewerCan } = await res.json();
1133
+ return viewerCan?.[collection] ?? [];
1134
+ }
1135
+ /** 呼んだ人のアカウント(管理の API の /api/me、can は操作の ID ごとの可否。失敗は例外) */
1026
1136
  async function appUser(ctx) {
1027
1137
  const res = await ctx.cms.fetch("/api/me");
1028
1138
  if (!res.ok) throw new Error(`app_user_unavailable: ${res.status}`);
1029
1139
  return await res.json();
1030
1140
  }
1031
- export { AUDIENCES, CUSTOMERS_KEY_TARGET, CUSTOMER_REF, CUSTOMER_STATUSES, IMPORT_ITEMS_MAX, JSON_BODY_MAX, NO_SETTINGS, ORIGIN_REF, SettingProblem, allows, appAssertion, appFailure, appFailureOf, appInvalid, appIssue, appJson, appProblems, appUser, audiencesFor, bearerClient, bodyFromHtml, calendarFieldSource, canReadField, cyclicCollections, egressAllows, exchangeDelegation, importIdOf, importItemOfRow, isAdmin, isPublishable, newUuidV7, ownsRow, principalOfUser, titleFor, workspaceRecordPath };
1141
+ export { ADMIN_AREA_OPERATION, APP_CHANNEL_KIND_LIMITS, APP_CHANNEL_LIMITS, APP_FILE_LIMITS, APP_MAIL_SKIP_REASONS, APP_NOTICE_KINDS, APP_NOTIFY_LIMITS, APP_STATE_LIMITS, APP_USAGE_ERRORS, AUDIENCES, BUNDLED_APP_IDS, CHANNEL_ADDRESS_KINDS, CHANNEL_CAPABILITIES, CHANNEL_MODES, DELEGABLE, END_USERS_KEY_TARGET, END_USER_REF, END_USER_STATUSES, IMPORT_ITEMS_MAX, JSON_BODY_MAX, MAIL_CAPABILITIES, MESSAGE_LIMITS, MESSAGE_PORT, MESSAGE_RECEIVED, MESSAGE_SKIP_REASONS, NOTICES_PORT, NO_SETTINGS, ORIGIN_REF, PAYMENT_LIMITS, PAYMENT_PORT, PERSON, PORT_DONE, PRICE_CURRENCIES, PRICE_INTERVALS, PRICE_KINDS, PURCHASE_STATUSES, SUBSCRIPTION_STATUSES, SettingProblem, aggregateJobIdOf, allRecordPages, appAssertion, appCollectionCan, appFailure, appFailureOf, appInvalid, appIssue, appJson, appPortResponse, appProblems, appRecordList, appToolPrefixOf, appUser, bearerClient, boundedList, calendarFieldSource, channelSettingPattern, cmsListAll, cyclicCollections, egressAllows, exchangeDelegation, exchangeSessionToken, importIdOf, importItemOfRow, isLiveState, isPublishable, manifestDocumentOf, newUuidV7, pageOf, portValue, priceLookupKeyOf, recordStateOf, richTextFromHtml, settingProblemText, settingRowsOf, workspaceRecordPath };