@reopt-ai/workspace-sdk 0.1.0-rc.13 → 0.1.0-rc.15

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.
@@ -34,7 +34,7 @@ declare function canAll(source: PermissionSource, keys: readonly WorkspacePermis
34
34
  /** 하나라도 가졌는가 */
35
35
  declare function canAny(source: PermissionSource, keys: readonly WorkspacePermissionKey[]): boolean;
36
36
  /** 위임 클라이언트의 메서드 이름(`createConnectClient`의 경로 그대로) */
37
- declare const CONNECT_OPERATION_NAMES: readonly ["me", "brands", "members", "works.listPipelines", "works.listTasks", "works.getTask", "works.createTask", "works.updateTask", "works.moveTask", "works.deleteTask", "works.deleteTasks", "works.listFeed", "works.addComment", "works.updateComment", "works.deleteComment", "posts.listGroups", "posts.listTags", "posts.list", "posts.checkSlug", "posts.get", "posts.create", "posts.update", "posts.publish", "posts.unpublish", "posts.delete", "folders.list", "folders.create", "folders.update", "folders.delete", "files.list", "files.usage", "files.signedUrls", "files.upload", "files.get", "files.update", "files.delete", "files.content", "forms.list", "inquiries.list", "inquiries.get", "inquiries.moveStage", "customers.list", "customers.listTags", "customers.listFields", "customers.get", "customers.create", "customers.update", "customers.updateTags", "customers.listNotes", "customers.addNote", "customers.updateNote", "customers.deleteNote", "customers.timeline", "notifications.list", "notifications.unseenCount", "notifications.markAllSeen", "notifications.markSeen", "eav.listEntities", "eav.listRecords", "eav.createRecord", "eav.updateRecord", "eav.deleteRecord"];
37
+ declare const CONNECT_OPERATION_NAMES: readonly ["me", "brands", "members", "works.listPipelines", "works.listTasks", "works.getTask", "works.createTask", "works.updateTask", "works.moveTask", "works.deleteTask", "works.deleteTasks", "works.listFeed", "works.addComment", "works.updateComment", "works.deleteComment", "posts.listGroups", "posts.listTags", "posts.list", "posts.checkSlug", "posts.get", "posts.create", "posts.update", "posts.publish", "posts.unpublish", "posts.delete", "folders.list", "folders.create", "folders.update", "folders.delete", "files.list", "files.usage", "files.signedUrls", "files.upload", "files.get", "files.update", "files.delete", "files.content", "forms.list", "inquiries.list", "inquiries.summary", "inquiries.get", "inquiries.moveStage", "customers.list", "customers.listTags", "customers.listFields", "customers.get", "customers.create", "customers.update", "customers.updateTags", "customers.listNotes", "customers.addNote", "customers.updateNote", "customers.deleteNote", "customers.timeline", "notifications.list", "notifications.unseenCount", "notifications.markAllSeen", "notifications.markSeen", "eav.listEntities", "eav.listRecords", "eav.createRecord", "eav.updateRecord", "eav.deleteRecord"];
38
38
  type ConnectOperation = (typeof CONNECT_OPERATION_NAMES)[number];
39
39
  type ConnectOperationRule = {
40
40
  /** 서버 라우트(정책 표의 키) */
@@ -61,4 +61,4 @@ declare function canCall(me: {
61
61
  } | readonly string[] | null | undefined, operation: ConnectOperation): boolean;
62
62
  //#endregion
63
63
  export { ConnectOperationRule as a, WorkspacePermissionKey as c, canAny as d, canCall as f, ConnectOperation as i, can as l, CONNECT_OPERATION_NAMES as n, ConnectScope as o, CONNECT_SCOPES as r, WORKSPACE_PERMISSION_KEYS as s, CONNECT_OPERATIONS as t, canAll as u };
64
- //# sourceMappingURL=permissions-DKm_zC_X.d.ts.map
64
+ //# sourceMappingURL=permissions-D5-qPHua.d.ts.map
@@ -1,2 +1,2 @@
1
- import { a as ConnectOperationRule, c as WorkspacePermissionKey, d as canAny, f as canCall, i as ConnectOperation, l as can, n as CONNECT_OPERATION_NAMES, o as ConnectScope, r as CONNECT_SCOPES, s as WORKSPACE_PERMISSION_KEYS, t as CONNECT_OPERATIONS, u as canAll } from "./permissions-DKm_zC_X.js";
1
+ import { a as ConnectOperationRule, c as WorkspacePermissionKey, d as canAny, f as canCall, i as ConnectOperation, l as can, n as CONNECT_OPERATION_NAMES, o as ConnectScope, r as CONNECT_SCOPES, s as WORKSPACE_PERMISSION_KEYS, t as CONNECT_OPERATIONS, u as canAll } from "./permissions-D5-qPHua.js";
2
2
  export { CONNECT_OPERATIONS, CONNECT_OPERATION_NAMES, CONNECT_SCOPES, ConnectOperation, ConnectOperationRule, ConnectScope, WORKSPACE_PERMISSION_KEYS, WorkspacePermissionKey, can, canAll, canAny, canCall };
@@ -153,6 +153,7 @@ const CONNECT_OPERATION_NAMES = [
153
153
  "files.content",
154
154
  "forms.list",
155
155
  "inquiries.list",
156
+ "inquiries.summary",
156
157
  "inquiries.get",
157
158
  "inquiries.moveStage",
158
159
  "customers.list",
@@ -391,6 +392,11 @@ const CONNECT_OPERATIONS = {
391
392
  permission: "form:read",
392
393
  scopes: ["customer:read"]
393
394
  },
395
+ "inquiries.summary": {
396
+ route: "GET /inquiries/summary",
397
+ permission: "form:read",
398
+ scopes: READ
399
+ },
394
400
  "inquiries.get": {
395
401
  route: "GET /inquiries/:submissionId",
396
402
  permission: "form:read",
@@ -399,7 +405,8 @@ const CONNECT_OPERATIONS = {
399
405
  "inquiries.moveStage": {
400
406
  route: "POST /inquiries/:submissionId/stage",
401
407
  permission: "form:write",
402
- scopes: WRITE
408
+ scopes: WRITE,
409
+ alsoScopes: ["customer:read"]
403
410
  },
404
411
  "customers.list": customerRead("GET /customers"),
405
412
  "customers.listTags": customerRead("GET /customer-tags"),
@@ -19,7 +19,16 @@ const PLATFORM_TASK_PRIORITIES = [
19
19
  "urgent"
20
20
  ];
21
21
  const PLATFORM_TASK_OUTCOMES = ["completed", "canceled"];
22
- const PLATFORM_WEBHOOK_TRIGGERS = ["workTaskStageChanged"];
22
+ const PLATFORM_WEBHOOK_TRIGGERS = ["workTaskStageChanged", "postsChanged"];
23
+ /**
24
+ * 트리거를 구독하는 데 필요한 기계 scope — **그 사건의 자료를 다루는 scope**다(`workspace:admin`은 전부).
25
+ * 웹훅의 `data`는 그 자료의 일부라, 표가 없으면 업무 쓰기 열쇠가 글 변경을 구독해 scope 밖의 것을 받는다.
26
+ * 서버(`/v1/webhooks`)·설치 선언 검증·개발 에뮬레이터가 이 표 하나를 읽는다.
27
+ */
28
+ const PLATFORM_WEBHOOK_TRIGGER_SCOPES = {
29
+ workTaskStageChanged: "works:write",
30
+ postsChanged: "posts:read"
31
+ };
23
32
  /** 소스 쪽 식별자 — 경로 세그먼트라 슬래시·공백 금지, ≤255 */
24
33
  const platformExternalIdSchema = z.string().trim().min(1).max(255).regex(/^[^/\s]+$/, "externalId must not contain slashes or whitespace");
25
34
  const versionSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
@@ -161,6 +170,17 @@ const platformErrorSchema = z.object({ error: z.object({
161
170
  message: z.string()
162
171
  })).optional()
163
172
  }) });
173
+ const platformPostsChangedEventSchema = z.object({
174
+ postIds: z.array(z.string()),
175
+ groupIds: z.array(z.string()),
176
+ published: z.array(z.object({
177
+ id: z.string(),
178
+ groupId: z.string(),
179
+ slug: z.string()
180
+ })),
181
+ truncated: z.boolean(),
182
+ version: z.number()
183
+ });
164
184
  const platformWorkTaskStageChangedEventSchema = z.object({
165
185
  id: z.string(),
166
186
  title: z.string(),
@@ -522,5 +542,5 @@ const platformResourcesV2Schema = z.object({
522
542
  });
523
543
 
524
544
  //#endregion
525
- export { platformWorkTaskStageChangedEventSchema as $, platformOAuthClientImportInputSchema as A, platformPublishedPostPageSchema as B, platformEavSchemaApplyResultSchema as C, platformLockAcquiredSchema as D, platformExternalIdSchema as E, platformPipelineSchema as F, platformResourcesV2Schema as G, platformPublishedPostSummarySchema as H, platformPipelineStageInputSchema as I, platformTaskStageSchema as J, platformTaskSchema as K, platformPipelineUpsertInputSchema as L, platformOAuthClientUpsertInputSchema as M, platformPipelineImportInputSchema as N, platformLockReleasedSchema as O, platformPipelineResourceSchema as P, platformWebhookUpsertInputSchema as Q, platformPublishedPostDetailQuerySchema as R, platformEavSchemaApplyInputSchema as S, platformErrorSchema as T, platformResourceKeySchema as U, platformPublishedPostSchema as V, platformResourcesSchema as W, platformWebhookResourceSchema as X, platformTaskUpsertInputSchema as Y, platformWebhookSchema as Z, platformBrandappResourceSchema as _, PLATFORM_MANAGED_BY_VALUES as a, platformEavBrandappResourcesSchema as b, PLATFORM_OAUTH_GRANT_TYPES as c, PLATFORM_TASK_PRIORITIES as d, platformWriteMetaSchema as et, PLATFORM_TOKEN_ENDPOINT_AUTH_METHODS as f, platformBrandUpsertInputSchema as g, platformBrandResourceSchema as h, PLATFORM_EAV_DATA_TYPES as i, platformOAuthClientResourceSchema as j, platformMeSchema as k, PLATFORM_STAGE_COLORS as l, platformBrandImportInputSchema as m, PLATFORM_BRANDAPP_STATUSES as n, PLATFORM_OAUTH_APPLICATION_TYPES as o, PLATFORM_WEBHOOK_TRIGGERS as p, platformTaskStageInputSchema as q, PLATFORM_DOMAIN_STATUSES as r, PLATFORM_OAUTH_CLIENT_PURPOSES as s, PLATFORM_ADMIN_SCOPE as t, PLATFORM_TASK_OUTCOMES as u, platformBrandappUpsertInputSchema as v, platformEavSchemaOperationSchema as w, platformEavEntityResourceSchema as x, platformCustomerUpsertInputSchema as y, platformPublishedPostListQuerySchema as z };
526
- //# sourceMappingURL=schemas-eWh_FUfh.js.map
545
+ export { platformWebhookSchema as $, platformMeSchema as A, platformPublishedPostDetailQuerySchema as B, platformEavSchemaApplyInputSchema as C, platformExternalIdSchema as D, platformErrorSchema as E, platformPipelineResourceSchema as F, platformResourceKeySchema as G, platformPublishedPostPageSchema as H, platformPipelineSchema as I, platformTaskSchema as J, platformResourcesSchema as K, platformPipelineStageInputSchema as L, platformOAuthClientResourceSchema as M, platformOAuthClientUpsertInputSchema as N, platformLockAcquiredSchema as O, platformPipelineImportInputSchema as P, platformWebhookResourceSchema as Q, platformPipelineUpsertInputSchema as R, platformEavEntityResourceSchema as S, platformEavSchemaOperationSchema as T, platformPublishedPostSchema as U, platformPublishedPostListQuerySchema as V, platformPublishedPostSummarySchema as W, platformTaskStageSchema as X, platformTaskStageInputSchema as Y, platformTaskUpsertInputSchema as Z, platformBrandUpsertInputSchema as _, PLATFORM_MANAGED_BY_VALUES as a, platformCustomerUpsertInputSchema as b, PLATFORM_OAUTH_GRANT_TYPES as c, PLATFORM_TASK_PRIORITIES as d, platformWebhookUpsertInputSchema as et, PLATFORM_TOKEN_ENDPOINT_AUTH_METHODS as f, platformBrandResourceSchema as g, platformBrandImportInputSchema as h, PLATFORM_EAV_DATA_TYPES as i, platformOAuthClientImportInputSchema as j, platformLockReleasedSchema as k, PLATFORM_STAGE_COLORS as l, PLATFORM_WEBHOOK_TRIGGER_SCOPES as m, PLATFORM_BRANDAPP_STATUSES as n, platformWriteMetaSchema as nt, PLATFORM_OAUTH_APPLICATION_TYPES as o, PLATFORM_WEBHOOK_TRIGGERS as p, platformResourcesV2Schema as q, PLATFORM_DOMAIN_STATUSES as r, PLATFORM_OAUTH_CLIENT_PURPOSES as s, PLATFORM_ADMIN_SCOPE as t, platformWorkTaskStageChangedEventSchema as tt, PLATFORM_TASK_OUTCOMES as u, platformBrandappResourceSchema as v, platformEavSchemaApplyResultSchema as w, platformEavBrandappResourcesSchema as x, platformBrandappUpsertInputSchema as y, platformPostsChangedEventSchema as z };
546
+ //# sourceMappingURL=schemas-BBUKRn_G.js.map
@@ -1,6 +1,6 @@
1
1
  import { n as PlatformApiError } from "../errors-CLUuzCNG.js";
2
2
  import { a as REOPT_PLATFORM_URLS, c as resolvePlatformUrls, i as REOPT_PLATFORM_ID_URLS, n as PlatformUrls } from "../urls-DiYp_PHg.js";
3
- import { r as PlatformClientConfig } from "../client-olMIaJZH.js";
3
+ import { r as PlatformClientConfig } from "../client-C-J5e2Zo.js";
4
4
  import { z } from "zod";
5
5
  //#region src/social/schemas.d.ts
6
6
  /**
@@ -1,6 +1,6 @@
1
- import { n as PlatformApiError } from "../errors-DKMC4kId.js";
1
+ import { n as PlatformApiError } from "../errors-Cnh-XDtf.js";
2
2
  import { REOPT_PLATFORM_ID_URLS, REOPT_PLATFORM_URLS, resolvePlatformUrls } from "../urls.js";
3
- import { r as createPlatformRequester } from "../client-BX4VHJS6.js";
3
+ import { r as createPlatformRequester } from "../client-BqdU2uJM.js";
4
4
  import { z } from "zod";
5
5
 
6
6
  //#region src/social/schemas.ts
@@ -1,5 +1,5 @@
1
- import { c as WorkspacePermissionKey } from "../permissions-DKm_zC_X.js";
2
- import { $ as ConnectStageColor, G as ConnectPostSpec, N as ConnectMemberRole, et as ConnectStageOutcome, lt as ConnectTaskPriority, n as ConnectAnswerValue } from "../connect-CTxppAjD.js";
1
+ import { c as WorkspacePermissionKey } from "../permissions-D5-qPHua.js";
2
+ import { F as ConnectMemberRole, dt as ConnectTaskPriority, n as ConnectAnswerValue, nt as ConnectStageOutcome, q as ConnectPostSpec, tt as ConnectStageColor } from "../connect-aWLB141V.js";
3
3
  //#region src/testing/index.d.ts
4
4
  /** 서로는 id가 아니라 `key`로 가리킨다 — id는 에뮬레이터가 만든다(`platform.id("task", key)`로 읽는다). */
5
5
  type DevPlatformSeed = {
@@ -191,9 +191,18 @@ type DevPlatformOptions = {
191
191
  * 예: `http://localhost:3000/api/dev-reopt`. 생략하면 `platformUrl`.
192
192
  */
193
193
  browserBaseUrl?: string;
194
- /** 기계 표면(`/v1/me`)이 답하는 클라이언트 이름 */
194
+ /** 기계 표면 — `/v1/me`가 답하는 클라이언트 이름과 scope(기본 `["posts:read"]`). scope는 웹훅 등록을 가른다 */
195
195
  machine?: {
196
196
  clientName?: string;
197
+ scopes?: string[];
198
+ };
199
+ /**
200
+ * 웹훅 — 앱이 `platform.webhooks.upsert`로 등록한 주소에 `postsChanged`를 **실제로 보낸다**(운영과 같은 서명).
201
+ * 운영에서는 앱이 위임 표면으로 글을 바꿔도 이 신호가 오므로, 여기서도 `posts.*` 쓰기가 끝나면 보낸다.
202
+ * `fetch`를 주면 그것으로 보낸다(테스트에서 수신 핸들러에 바로 물린다). 생략하면 전역 `fetch`.
203
+ */
204
+ webhooks?: {
205
+ fetch?: typeof fetch;
197
206
  };
198
207
  /** 모든 응답 앞의 지연(ms) — 로딩 상태를 보려고 */
199
208
  latencyMs?: number;
@@ -223,9 +232,27 @@ type DevPlatform = {
223
232
  reset: () => void;
224
233
  /** 받은 요청 기록(최근 1,000건) — `"GET /files?folderId=all"` */
225
234
  requests: string[];
235
+ /** 보낸 웹훅 기록(최근 1,000건) — `status`가 null이면 보내지 못했다(`error`) */
236
+ webhookDeliveries: DevWebhookDelivery[];
237
+ /** 보내는 중인 웹훅이 끝날 때까지 기다린다 — 테스트가 수신 결과를 보기 전에 부른다 */
238
+ settled: () => Promise<void>;
239
+ /**
240
+ * 스튜디오에서 일어난 변경을 흉내 낸다 — 등록된 주소로 `postsChanged`를 보낸다(상태는 바꾸지 않는다).
241
+ * 앱 밖에서 글이 바뀌었을 때 사이트가 다시 굽는지 시험한다.
242
+ */
243
+ emitPostsChanged: (input?: {
244
+ postIds?: string[];
245
+ groupIds?: string[];
246
+ }) => Promise<void>;
247
+ };
248
+ type DevWebhookDelivery = {
249
+ url: string;
250
+ type: string;
251
+ status: number | null;
252
+ error?: string;
226
253
  };
227
254
  type DevIdKind = "member" | "brand" | "pipeline" | "stage" | "task" | "postGroup" | "post" | "folder" | "file" | "form" | "submission" | "customer" | "notification" | "table";
228
255
  declare function createDevPlatform(options?: DevPlatformOptions): DevPlatform;
229
256
  //#endregion
230
- export { DevFormField, DevIdKind, DevPlatform, DevPlatformOptions, DevPlatformSeed, createDevPlatform };
257
+ export { DevFormField, DevIdKind, DevPlatform, DevPlatformOptions, DevPlatformSeed, DevWebhookDelivery, createDevPlatform };
231
258
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,6 @@
1
+ import { m as PLATFORM_WEBHOOK_TRIGGER_SCOPES, p as PLATFORM_WEBHOOK_TRIGGERS } from "../schemas-BBUKRn_G.js";
1
2
  import { CONNECT_OPERATIONS, WORKSPACE_PERMISSION_KEYS } from "../permissions.js";
3
+ import { signWebhookRequest } from "../webhooks.js";
2
4
 
3
5
  //#region src/testing/index.ts
4
6
  /**
@@ -18,7 +20,8 @@ import { CONNECT_OPERATIONS, WORKSPACE_PERMISSION_KEYS } from "../permissions.js
18
20
  * });
19
21
  * ```
20
22
  *
21
- * 흉내 내는 것: 위임 표면(`/v1/connect/*`) 전부와 기계 표면의 토큰·`/v1/me`·`/v1/posts`, 그리고 브라우저가 직접 여는 두 곳
23
+ * 흉내 내는 것: 위임 표면(`/v1/connect/*`) 전부와 기계 표면의 토큰·`/v1/me`·`/v1/posts`·`/v1/webhooks`(등록한 주소로 `postsChanged`를
24
+ * 실제로 보낸다 — 아래 "웹훅"), 그리고 브라우저가 직접 여는 두 곳
22
25
  * (서명 주소·공개 파일의 바이트, 공개 폼 제출 — `handler`). 계약 규칙도 따라 한다: 목록의 창·정렬, 쓰기의 전체 객체,
23
26
  * `VERSION_CONFLICT`·`SLUG_TAKEN`·`VALIDATION_ERROR`(`fields`)·413/415·`QUOTA_EXCEEDED`, 시스템 폴더 변경 거절,
24
27
  * 비어 있지 않은 폴더 삭제 409, 그리고 `me.permissions`·`me.scopes`를 주면 `CONNECT_OPERATIONS`대로 403.
@@ -28,6 +31,7 @@ import { CONNECT_OPERATIONS, WORKSPACE_PERMISSION_KEYS } from "../permissions.js
28
31
  *
29
32
  * 🔴 프로덕션 번들에 넣지 않는다 — 인증이 없다. `NODE_ENV === "production"`에서 만들면 던진다(`allowInProduction`으로만 푼다).
30
33
  */
34
+ const WEBHOOK_TRIGGER_SCOPE = PLATFORM_WEBHOOK_TRIGGER_SCOPES;
31
35
  var Refusal = class extends Error {
32
36
  status;
33
37
  code;
@@ -127,6 +131,53 @@ function build(options) {
127
131
  ];
128
132
  const requests = [];
129
133
  let state = seedState(options);
134
+ const machineScopes = options.machine?.scopes ?? ["posts:read"];
135
+ const webhookDeliveries = [];
136
+ let webhookQueue = Promise.resolve();
137
+ const sendWebhook = (type, data) => {
138
+ const targets = state.webhooks.filter((hook) => hook.triggers.includes(type));
139
+ if (targets.length === 0) return;
140
+ const send = options.webhooks?.fetch ?? globalThis.fetch;
141
+ const workspaceId = state.workspace.id;
142
+ webhookQueue = webhookQueue.then(async () => {
143
+ const id = `dev-evt-${state.counter += 1}`;
144
+ for (const hook of targets) {
145
+ const delivery = {
146
+ url: hook.url,
147
+ type,
148
+ status: null
149
+ };
150
+ try {
151
+ const request = await signWebhookRequest({
152
+ url: hook.url,
153
+ secret: hook.secret,
154
+ type,
155
+ data,
156
+ id,
157
+ entityType: "workspace",
158
+ entityId: workspaceId
159
+ });
160
+ delivery.status = (await send(request)).status;
161
+ } catch (error) {
162
+ delivery.error = error instanceof Error ? error.message : String(error);
163
+ }
164
+ webhookDeliveries.push(delivery);
165
+ if (webhookDeliveries.length > REQUEST_LOG_MAX) webhookDeliveries.splice(0, webhookDeliveries.length - REQUEST_LOG_MAX);
166
+ }
167
+ });
168
+ };
169
+ /** `postsChanged`의 `data` — 운영의 전달 층과 같은 모양(지금 게시 중인 글만 주소와 함께). */
170
+ const postsChangedData = (postIds, groupIds) => ({
171
+ postIds,
172
+ groupIds,
173
+ published: state.posts.filter((post) => postIds.includes(post.id) && post.status === "published").map((post) => ({
174
+ id: post.id,
175
+ groupId: post.groupId,
176
+ slug: post.slug
177
+ })),
178
+ truncated: false,
179
+ version: state.clock += 1
180
+ });
130
181
  const stamp = () => new Date(state.clock += 1).toISOString();
131
182
  const newId = () => {
132
183
  state.counter += 1;
@@ -1337,12 +1388,49 @@ function build(options) {
1337
1388
  const formIds = url.searchParams.getAll("formId");
1338
1389
  if (formIds.length < 1 || formIds.length > 50) return invalid("formId", "Expected 1 to 50 form ids");
1339
1390
  const window = windowOf(url, 500);
1340
- return paged(state.submissions.filter((s) => formIds.includes(s.formId)).sort((a, b) => b.submittedAt.localeCompare(a.submittedAt) || b.id.localeCompare(a.id)).map(inquiryDto), {
1391
+ const q = url.searchParams;
1392
+ const stageIds = q.getAll("stageId");
1393
+ const customerId = q.get("customerId");
1394
+ const after = q.get("submittedAfter");
1395
+ const before = q.get("submittedBefore");
1396
+ for (const [name, value] of [["submittedAfter", after], ["submittedBefore", before]]) if (value && Number.isNaN(Date.parse(value))) invalid(name, "Expected a date");
1397
+ const stageOf = (s) => state.tasks.find((t) => t.id === s.taskId)?.stageId ?? null;
1398
+ return paged(state.submissions.filter((s) => formIds.includes(s.formId)).filter((s) => (stageIds.length === 0 || stageIds.includes(stageOf(s) ?? "")) && (!customerId || s.customerId === customerId) && (!after || s.submittedAt >= new Date(after).toISOString()) && (!before || s.submittedAt < new Date(before).toISOString())).sort((a, b) => b.submittedAt.localeCompare(a.submittedAt) || b.id.localeCompare(a.id)).map(inquiryDto), {
1341
1399
  limit: window.limit ?? 100,
1342
1400
  offset: window.offset
1343
1401
  });
1344
1402
  }
1345
1403
  ],
1404
+ [
1405
+ "GET",
1406
+ /^\/inquiries\/summary$/,
1407
+ "inquiries.summary",
1408
+ ({ url }) => {
1409
+ const formIds = url.searchParams.getAll("formId");
1410
+ if (formIds.length < 1 || formIds.length > 50) return invalid("formId", "Expected 1 to 50 form ids");
1411
+ const rows = state.submissions.filter((s) => formIds.includes(s.formId));
1412
+ const counts = /* @__PURE__ */ new Map();
1413
+ for (const row of rows) {
1414
+ const stageId = state.tasks.find((t) => t.id === row.taskId)?.stageId ?? null;
1415
+ counts.set(stageId, (counts.get(stageId) ?? 0) + 1);
1416
+ }
1417
+ const day = 1440 * 60 * 1e3;
1418
+ const nowMs = state.clock;
1419
+ const within = (from, to) => rows.filter((row) => {
1420
+ const age = nowMs - Date.parse(row.submittedAt);
1421
+ return age >= from && age < to;
1422
+ }).length;
1423
+ return ok({
1424
+ total: rows.length,
1425
+ byStage: [...counts].map(([stageId, count]) => ({
1426
+ stageId,
1427
+ count
1428
+ })).sort((a, b) => b.count - a.count),
1429
+ last7Days: within(0, 7 * day),
1430
+ previous7Days: within(7 * day, 14 * day)
1431
+ });
1432
+ }
1433
+ ],
1346
1434
  [
1347
1435
  "GET",
1348
1436
  new RegExp(`^/inquiries/${UUID}$`),
@@ -1806,8 +1894,103 @@ function build(options) {
1806
1894
  } : null
1807
1895
  };
1808
1896
  };
1809
- const machine = (method, url) => {
1897
+ const webhookDto = (row) => ({
1898
+ id: row.id,
1899
+ url: row.url,
1900
+ triggers: row.triggers,
1901
+ hasSecret: row.secret.length > 0,
1902
+ managedBy: row.managedBy
1903
+ });
1904
+ const canManageWebhook = (triggers) => machineScopes.includes("workspace:admin") || triggers.every((trigger) => {
1905
+ const scope = WEBHOOK_TRIGGER_SCOPE[trigger];
1906
+ return scope !== void 0 && machineScopes.includes(scope);
1907
+ });
1908
+ const requireWebhookScope = () => {
1909
+ const any = [...Object.values(WEBHOOK_TRIGGER_SCOPE), "workspace:admin"];
1910
+ if (!any.some((scope) => machineScopes.includes(scope))) refuse(403, "INSUFFICIENT_SCOPE", `Required scope: ${[...new Set(any)].join(" | ")}`);
1911
+ };
1912
+ const machineWebhooks = (method, path, body) => {
1913
+ if (path === "/v1/webhooks" && method === "GET") {
1914
+ requireWebhookScope();
1915
+ return ok(state.webhooks.filter((row) => canManageWebhook(row.triggers)).map(webhookDto));
1916
+ }
1917
+ if (path === "/v1/webhooks" && method === "PUT") {
1918
+ requireWebhookScope();
1919
+ const input = assertBody(body);
1920
+ const url = str(input, "url", {
1921
+ required: true,
1922
+ max: 2e3
1923
+ });
1924
+ try {
1925
+ new URL(url);
1926
+ } catch {
1927
+ invalid("url", "Expected a URL");
1928
+ }
1929
+ const triggers = Array.isArray(input.triggers) ? input.triggers.map(String) : [];
1930
+ const known = PLATFORM_WEBHOOK_TRIGGERS;
1931
+ if (triggers.length === 0 || triggers.some((trigger) => !known.includes(trigger))) invalid("triggers", `Expected one or more of ${known.join(", ")}`);
1932
+ for (const trigger of triggers) {
1933
+ const scope = WEBHOOK_TRIGGER_SCOPE[trigger];
1934
+ if (!machineScopes.includes("workspace:admin") && !(scope && machineScopes.includes(scope))) refuse(403, "INSUFFICIENT_SCOPE", `Required scope: ${scope} | workspace:admin`);
1935
+ }
1936
+ const secret = str(input, "secret", { max: 1024 });
1937
+ if (secret !== void 0 && secret !== null && secret.length < 16) invalid("secret", "required (16–1024 chars)");
1938
+ if (input.managedBy !== void 0 && !machineScopes.includes("workspace:admin")) refuse(403, "INSUFFICIENT_SCOPE", "managedBy requires scope: workspace:admin");
1939
+ const managedBy = input.managedBy === "code" ? "code" : null;
1940
+ const existing = state.webhooks.find((row) => row.url === url);
1941
+ if (existing) {
1942
+ if (!canManageWebhook(existing.triggers)) refuse(403, "INSUFFICIENT_SCOPE", "A webhook at this URL subscribes to triggers outside this credential");
1943
+ existing.triggers = triggers;
1944
+ if (secret) existing.secret = secret;
1945
+ if (input.managedBy !== void 0) existing.managedBy = managedBy;
1946
+ return {
1947
+ status: 200,
1948
+ body: {
1949
+ data: webhookDto(existing),
1950
+ meta: {
1951
+ created: false,
1952
+ applied: true
1953
+ }
1954
+ }
1955
+ };
1956
+ }
1957
+ if (!secret) return invalid("secret", "required (16–1024 chars)");
1958
+ const row = {
1959
+ id: newId(),
1960
+ url,
1961
+ triggers,
1962
+ secret,
1963
+ managedBy
1964
+ };
1965
+ state.webhooks.push(row);
1966
+ return {
1967
+ status: 201,
1968
+ body: {
1969
+ data: webhookDto(row),
1970
+ meta: {
1971
+ created: true,
1972
+ applied: true
1973
+ }
1974
+ }
1975
+ };
1976
+ }
1977
+ const single = /^\/v1\/webhooks\/([^/]+)$/.exec(path);
1978
+ if (single && method === "DELETE") {
1979
+ requireWebhookScope();
1980
+ const id = decodeURIComponent(single[1]);
1981
+ const row = state.webhooks.find((candidate) => candidate.id === id && canManageWebhook(candidate.triggers));
1982
+ if (!row) return notFound("Webhook");
1983
+ state.webhooks = state.webhooks.filter((candidate) => candidate !== row);
1984
+ return ok({
1985
+ id,
1986
+ deleted: true
1987
+ });
1988
+ }
1989
+ return null;
1990
+ };
1991
+ const machine = (method, url, body) => {
1810
1992
  const path = url.pathname;
1993
+ if (path.startsWith("/v1/webhooks")) return machineWebhooks(method, path, body);
1811
1994
  if (method === "POST" && path.endsWith("/oauth2/token")) return {
1812
1995
  status: 200,
1813
1996
  body: {
@@ -1823,7 +2006,7 @@ function build(options) {
1823
2006
  workspaceId: state.workspace.id,
1824
2007
  brandappId: null,
1825
2008
  defaultBrandId: null,
1826
- scopes: ["posts:read"]
2009
+ scopes: machineScopes
1827
2010
  });
1828
2011
  if (method === "GET" && path === "/v1/posts") {
1829
2012
  const q = url.searchParams;
@@ -1887,11 +2070,18 @@ function build(options) {
1887
2070
  const match = pattern.exec(path);
1888
2071
  if (!match) continue;
1889
2072
  authorize(operation);
2073
+ const params = match.slice(1);
1890
2074
  reply = run({
1891
2075
  url,
1892
2076
  body: await readBody(request),
1893
- params: match.slice(1)
2077
+ params
1894
2078
  });
2079
+ if (operation.startsWith("posts.") && method !== "GET") {
2080
+ const created = !(reply instanceof Response) && operation === "posts.create" ? reply.body.data : void 0;
2081
+ const postId = created?.id ?? params[0];
2082
+ const groupId = created?.groupId ?? state.posts.find((post) => post.id === postId)?.groupId;
2083
+ sendWebhook("postsChanged", postsChangedData(postId ? [postId] : [], groupId ? [groupId] : []));
2084
+ }
1895
2085
  break;
1896
2086
  }
1897
2087
  if (reply && !(reply instanceof Response) && reply.status === 0) {
@@ -1908,7 +2098,7 @@ function build(options) {
1908
2098
  state.files.push(row);
1909
2099
  reply = ok(fileDto(row), 201);
1910
2100
  }
1911
- } else reply = machine(method, url);
2101
+ } else reply = machine(method, url, url.pathname.startsWith("/v1/webhooks") ? await readBody(request) : void 0);
1912
2102
  if (!reply) refuse(501, "NOT_IMPLEMENTED", `Dev platform does not answer ${method} ${url.pathname}`);
1913
2103
  return reply instanceof Response ? reply : Response.json(reply.body, { status: reply.status });
1914
2104
  } catch (error) {
@@ -2147,7 +2337,20 @@ function build(options) {
2147
2337
  if (!id) throw new Error(`[dev-platform] no ${kind} with key "${key}" in the seed`);
2148
2338
  return id;
2149
2339
  },
2340
+ webhookDeliveries,
2341
+ settled: async () => {
2342
+ let seen = null;
2343
+ while (seen !== webhookQueue) {
2344
+ seen = webhookQueue;
2345
+ await seen;
2346
+ }
2347
+ },
2348
+ emitPostsChanged: async (input = {}) => {
2349
+ sendWebhook("postsChanged", postsChangedData(input.postIds ?? [], input.groupIds ?? []));
2350
+ await webhookQueue;
2351
+ },
2150
2352
  reset: () => {
2353
+ webhookDeliveries.length = 0;
2151
2354
  state = seedState(options);
2152
2355
  plantSubmissions();
2153
2356
  requests.length = 0;
@@ -2179,6 +2382,7 @@ function seedState(options) {
2179
2382
  customerFields: [],
2180
2383
  notifications: [],
2181
2384
  tables: [],
2385
+ webhooks: [],
2182
2386
  ids: /* @__PURE__ */ new Map(),
2183
2387
  counter: 0,
2184
2388
  clock: start
@@ -1,4 +1,4 @@
1
- import { l as SDK_VERSION, n as PlatformApiError } from "./errors-DKMC4kId.js";
1
+ import { l as SDK_VERSION, n as PlatformApiError } from "./errors-Cnh-XDtf.js";
2
2
 
3
3
  //#region src/workspace/transport.ts
4
4
  function parseRetryAfter(value) {
@@ -189,4 +189,4 @@ function createTransport(config) {
189
189
 
190
190
  //#endregion
191
191
  export { readPlatformFailure as n, createTransport as t };
192
- //# sourceMappingURL=transport-BEwY_twi.js.map
192
+ //# sourceMappingURL=transport-C8zLAgkC.js.map
@@ -16,6 +16,10 @@
16
16
  * if (event.data.origin === "my-app") return; // 내가 일으킨 변경
17
17
  * await syncStage(event.data);
18
18
  * },
19
+ * postsChanged: ({ data }) => {
20
+ * revalidatePath("/news"); // 글이 바뀌었다 — 캐시를 다시 굽는다
21
+ * for (const post of data.published) revalidatePath(`/news/${post.slug}`);
22
+ * },
19
23
  * },
20
24
  * });
21
25
  * ```
@@ -49,9 +53,38 @@ type WorkTaskStageChangedData = {
49
53
  label: string | null;
50
54
  }>;
51
55
  };
56
+ /**
57
+ * `postsChanged` — 이 워크스페이스의 글이 바뀌었다(발행·게시 중 수정·내림·삭제·순서·태그·그룹).
58
+ *
59
+ * 무엇이 어떻게 바뀌었는지가 아니라 **"다시 읽어라"**는 신호다. 받는 쪽은 글 목록 캐시를 버리고, `published`의
60
+ * 주소로 글 페이지를 다시 굽는다. 초안만 바뀐 경우에도 올 수 있고, 한 요청의 변경은 한 번으로 묶여 온다.
61
+ *
62
+ * ```ts
63
+ * postsChanged: ({ data }) => {
64
+ * revalidatePath("/news", "layout"); // 목록과 그 아래 전부 — 내렸거나 지운 글의 옛 주소는 사건에 없다
65
+ * },
66
+ * ```
67
+ */
68
+ type PostsChangedData = {
69
+ /** 바뀐 글의 id(100개까지). 지워진 글·초안도 여기에는 있다. 그룹이나 브랜드를 통째로 지우면 글 id 없이 `groupIds`만 온다 */
70
+ postIds: string[];
71
+ /** 바뀐 글 그룹의 id(100개까지) */
72
+ groupIds: string[];
73
+ /** `postIds` 가운데 **지금 게시 중인** 글 — 여기 없는 것은 내렸거나 지웠거나 초안이다 */
74
+ published: Array<{
75
+ id: string;
76
+ groupId: string;
77
+ slug: string;
78
+ }>;
79
+ /** id가 100개를 넘어 잘렸다 — 주소별이 아니라 통째로 다시 굽는다 */
80
+ truncated: boolean;
81
+ /** 보낸 시각(ms). 순서를 보는 값이다 — 이 값이 작다고 사건을 버리지 않는다(늦게 온 재전송도 자기 id를 싣고 있다) */
82
+ version: number;
83
+ };
52
84
  /** 사건 종류 → `data` 모양. 여기 없는 종류는 `data: unknown`으로 온다(새 종류가 생겨도 받는 쪽이 깨지지 않는다). */
53
85
  type WebhookEventDataMap = {
54
86
  workTaskStageChanged: WorkTaskStageChangedData;
87
+ postsChanged: PostsChangedData;
55
88
  };
56
89
  type WebhookEventType = keyof WebhookEventDataMap;
57
90
  type WebhookEvent<Type extends string = string, Data = Type extends WebhookEventType ? WebhookEventDataMap[Type] : unknown> = {
@@ -85,6 +118,33 @@ declare function verifyWebhookSignature(input: {
85
118
  signature: string;
86
119
  body: string;
87
120
  }): Promise<boolean>;
121
+ /**
122
+ * 리옵트와 **같은 형식으로 서명한 요청**을 만든다 — 수신 핸들러를 따로 시험할 때 쓴다(틀린 서명·오래된 시각·
123
+ * 중복 전달). 개발 에뮬레이터(`/testing`)도 등록한 주소로 보낼 때 이 함수를 쓴다.
124
+ *
125
+ * ```ts
126
+ * const request = await signWebhookRequest({
127
+ * url: "http://localhost:3000/api/webhooks/reopt",
128
+ * secret: process.env.REOPT_WEBHOOK_SECRET!,
129
+ * type: "postsChanged",
130
+ * data: { postIds: [], groupIds: [], published: [], truncated: false, version: Date.now() },
131
+ * });
132
+ * await fetch(request); // 띄워 둔 앱에 보내거나
133
+ * await POST(request); // 핸들러를 직접 부른다
134
+ * ```
135
+ */
136
+ declare function signWebhookRequest<Type extends string>(input: {
137
+ url: string;
138
+ secret: string;
139
+ type: Type;
140
+ data: Type extends WebhookEventType ? WebhookEventDataMap[Type] : unknown;
141
+ /** 사건 id — 중복 전달을 시험할 때 같은 값을 준다. 기본은 새 UUID */
142
+ id?: string;
143
+ entityType?: string;
144
+ entityId?: string;
145
+ /** 서명에 들어가는 시각(ms). 기본은 지금 — 오래된 요청의 거절을 시험할 때 옛 값을 준다 */
146
+ timestamp?: number;
147
+ }): Promise<Request>;
88
148
  /**
89
149
  * 요청 하나를 읽어 검증한다 — 서명 → 시각 → 본문 순. 통과하면 사건을, 아니면 거절 이유와 응답 상태를 돌려준다.
90
150
  * 프레임워크에 맞춰 직접 응답을 만들 때 쓴다(그대로 쓰려면 `createWebhookHandler`).
@@ -141,5 +201,5 @@ type WebhookHandlerOptions = {
141
201
  */
142
202
  declare function createWebhookHandler(options: WebhookHandlerOptions): (request: Request) => Promise<Response>;
143
203
  //#endregion
144
- export { DEFAULT_WEBHOOK_TOLERANCE_MS, ReadWebhookResult, WebhookEvent, WebhookEventDataMap, WebhookEventType, WebhookHandlerOptions, WebhookRejection, WebhookSeenStore, WorkTaskStageChangedData, createMemoryWebhookSeenStore, createWebhookHandler, readWebhook, verifyWebhookSignature };
204
+ export { DEFAULT_WEBHOOK_TOLERANCE_MS, PostsChangedData, ReadWebhookResult, WebhookEvent, WebhookEventDataMap, WebhookEventType, WebhookHandlerOptions, WebhookRejection, WebhookSeenStore, WorkTaskStageChangedData, createMemoryWebhookSeenStore, createWebhookHandler, readWebhook, signWebhookRequest, verifyWebhookSignature };
145
205
  //# sourceMappingURL=webhooks.d.ts.map
package/dist/webhooks.js CHANGED
@@ -16,6 +16,10 @@
16
16
  * if (event.data.origin === "my-app") return; // 내가 일으킨 변경
17
17
  * await syncStage(event.data);
18
18
  * },
19
+ * postsChanged: ({ data }) => {
20
+ * revalidatePath("/news"); // 글이 바뀌었다 — 캐시를 다시 굽는다
21
+ * for (const post of data.published) revalidatePath(`/news/${post.slug}`);
22
+ * },
19
23
  * },
20
24
  * });
21
25
  * ```
@@ -57,6 +61,48 @@ async function verifyWebhookSignature(input) {
57
61
  return false;
58
62
  }
59
63
  }
64
+ /**
65
+ * 리옵트와 **같은 형식으로 서명한 요청**을 만든다 — 수신 핸들러를 따로 시험할 때 쓴다(틀린 서명·오래된 시각·
66
+ * 중복 전달). 개발 에뮬레이터(`/testing`)도 등록한 주소로 보낼 때 이 함수를 쓴다.
67
+ *
68
+ * ```ts
69
+ * const request = await signWebhookRequest({
70
+ * url: "http://localhost:3000/api/webhooks/reopt",
71
+ * secret: process.env.REOPT_WEBHOOK_SECRET!,
72
+ * type: "postsChanged",
73
+ * data: { postIds: [], groupIds: [], published: [], truncated: false, version: Date.now() },
74
+ * });
75
+ * await fetch(request); // 띄워 둔 앱에 보내거나
76
+ * await POST(request); // 핸들러를 직접 부른다
77
+ * ```
78
+ */
79
+ async function signWebhookRequest(input) {
80
+ const timestamp = String(input.timestamp ?? Date.now());
81
+ const body = JSON.stringify({
82
+ id: input.id ?? crypto.randomUUID(),
83
+ type: input.type,
84
+ entityType: input.entityType ?? "workspace",
85
+ entityId: input.entityId ?? "",
86
+ createdAt: new Date(Number(timestamp)).toISOString(),
87
+ data: input.data
88
+ });
89
+ const key = await crypto.subtle.importKey("raw", encoder.encode(input.secret), {
90
+ name: "HMAC",
91
+ hash: "SHA-256"
92
+ }, false, ["sign"]);
93
+ const signature = toHex(await crypto.subtle.sign("HMAC", key, encoder.encode(`${timestamp}.${body}`)));
94
+ return new Request(input.url, {
95
+ method: "POST",
96
+ headers: {
97
+ "content-type": "application/json",
98
+ "user-agent": "reopt-webhooks/1.0",
99
+ "x-reopt-event": input.type,
100
+ "x-reopt-timestamp": timestamp,
101
+ "x-reopt-signature": `sha256=${signature}`
102
+ },
103
+ body
104
+ });
105
+ }
60
106
  function isEvent(value) {
61
107
  if (!value || typeof value !== "object") return false;
62
108
  const event = value;
@@ -195,5 +241,5 @@ function createWebhookHandler(options) {
195
241
  }
196
242
 
197
243
  //#endregion
198
- export { DEFAULT_WEBHOOK_TOLERANCE_MS, createMemoryWebhookSeenStore, createWebhookHandler, readWebhook, verifyWebhookSignature };
244
+ export { DEFAULT_WEBHOOK_TOLERANCE_MS, createMemoryWebhookSeenStore, createWebhookHandler, readWebhook, signWebhookRequest, verifyWebhookSignature };
199
245
  //# sourceMappingURL=webhooks.js.map