@aimarch/loom-feedback 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @aimarch/loom-feedback
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Loom 产品反馈服务端 SDK。Node.js >=20、ESM、TypeScript 类型,无运行时依赖。
4
+
5
+ ```ts
6
+ import { createLoomFeedbackClient, LoomFeedbackError } from '@aimarch/loom-feedback';
7
+
8
+ const feedback = createLoomFeedbackClient({
9
+ baseUrl: process.env.LOOM_API_URL!,
10
+ applicationSecret: process.env.LOOM_APPLICATION_SECRET!,
11
+ productCode: 'teaching', // studio 或 teaching
12
+ });
13
+ const options = { sessionToken }; // 同一应用的 Loom 登录会话
14
+ const { data } = await feedback.list({ page: 1 }, options);
15
+ ```
16
+
17
+ | 方法 | 输入 | scope |
18
+ | --- | --- | --- |
19
+ | submit | kind、body、contact、consent、requestKey、可选 context | feedback:write |
20
+ | list | page 或 id,空对象查询第一页 | feedback:read |
21
+ | messages | 仅会话选项 | feedback:read |
22
+ | readMessage | id | feedback:read |
23
+
24
+ submit/list/readMessage 的第二参数是会话选项;messages 仅接收会话选项。所有方法返回 `{ data, requestId }`。list 的 id 条件查询本人当前产品的反馈详情,找不到返回 NOT_FOUND。messages 返回 `{items}`,readMessage 返回 `{id}`,submit 返回 `{id,message}`。
25
+
26
+ 反馈类型为“问题反馈”“功能建议”“体验优化”“其他意见”;正文去除首尾空白后1–500字符,联系方式最多100字符。requestKey为8–100位字母、数字、下划线或连字符,相同提交重试沿用同一键。context只接受page、courseId、classId;page为不含查询串及片段的站内路径。账号由会话确定,产品绑定客户端配置,服务端执行授权与数据隔离。
27
+
28
+ 默认10秒超时,调用选项可传 `{sessionToken, timeoutMs, signal}`。例如查询可选通知时使用2秒超时。配置支持注入fetch;HTTPS为默认要求,本机开发需显式设置allowLoopbackHttp。请求禁用重定向和缓存,不自动重试。
29
+
30
+ `LoomFeedbackError` 提供code、status、requestId及可选retryAfter。本地错误INVALID_INPUT、NETWORK_ERROR、TIMEOUT、ABORTED的status为0;响应不符合契约时报PROTOCOL_ERROR。错误不包含服务端原始消息、凭据或响应正文,页面文案由接入方按错误码映射。
31
+
32
+ 仅从服务端模块导入,运行于浏览器时立即拒绝。接入方维护Cookie、Origin/CSRF检查和用户页面。反馈数据、处理结果及通知统一由Loom维护。读取结果仅投影公开字段。
33
+
34
+ 本地开发:`npm run build`,`npm pack`;发布后使用 `npm install @aimarch/loom-feedback`。
@@ -0,0 +1,19 @@
1
+ import type { LoomFeedbackClientOptions, FeedbackInput, FeedbackQuery, UserCallOptions } from './types.js';
2
+ export { LoomFeedbackError } from './transport.js';
3
+ export type * from './types.js';
4
+ export declare function createLoomFeedbackClient(options: LoomFeedbackClientOptions): {
5
+ list(input: FeedbackQuery, opts: UserCallOptions): Promise<import("./types.js").FeedbackResult<import("./types.js").FeedbackPage>>;
6
+ submit(input: FeedbackInput, opts: UserCallOptions): Promise<import("./types.js").FeedbackResult<{
7
+ id: string;
8
+ message: string;
9
+ }>>;
10
+ messages(opts: UserCallOptions): Promise<import("./types.js").FeedbackResult<{
11
+ items: import("./types.js").FeedbackNotice[];
12
+ }>>;
13
+ readMessage(input: {
14
+ id: string;
15
+ }, opts: UserCallOptions): Promise<import("./types.js").FeedbackResult<{
16
+ id: string;
17
+ }>>;
18
+ };
19
+ export type LoomFeedbackClient = ReturnType<typeof createLoomFeedbackClient>;
package/dist/index.js ADDED
@@ -0,0 +1,39 @@
1
+ import { transport, LoomFeedbackError } from './transport.js';
2
+ import * as schema from './schema.js';
3
+ export { LoomFeedbackError } from './transport.js';
4
+ if (typeof window !== 'undefined')
5
+ throw new Error('Loom feedback SDK is server-only');
6
+ export function createLoomFeedbackClient(options) {
7
+ const product = options.productCode;
8
+ if (!['studio', 'teaching'].includes(product))
9
+ throw new Error('Invalid productCode');
10
+ const call = transport(options);
11
+ const base = `/api/loom/v1/products/${product}/feedback`;
12
+ function checked(parse) {
13
+ try {
14
+ return parse();
15
+ }
16
+ catch {
17
+ throw new LoomFeedbackError('INVALID_INPUT', 0);
18
+ }
19
+ }
20
+ function headers(opts) {
21
+ if (!opts || typeof opts.sessionToken !== 'string' || !/^loom_as_[A-Za-z0-9_-]{43}$/.test(opts.sessionToken))
22
+ throw new LoomFeedbackError('INVALID_INPUT', 0);
23
+ return { 'X-Loom-Session': opts.sessionToken };
24
+ }
25
+ return {
26
+ async list(input, opts) {
27
+ return call('GET', base + checked(() => schema.query(input)), v => schema.page(v, product), headers(opts), undefined, opts);
28
+ },
29
+ async submit(input, opts) {
30
+ return call('POST', base, schema.submitted, headers(opts), checked(() => schema.input(input)), opts);
31
+ },
32
+ async messages(opts) {
33
+ return call('GET', base + '/messages', schema.notices, headers(opts), undefined, opts);
34
+ },
35
+ async readMessage(input, opts) {
36
+ return call('POST', base + '/messages/read', schema.receipt, headers(opts), { id: checked(() => schema.id(input.id)) }, opts);
37
+ },
38
+ };
39
+ }
@@ -0,0 +1,16 @@
1
+ import type { FeedbackInput, FeedbackNotice, FeedbackPage, ProductCode } from './types.js';
2
+ export declare const record: (v: unknown) => v is Record<string, unknown>;
3
+ export declare const id: (v: unknown) => string;
4
+ export declare function input(v: unknown): FeedbackInput;
5
+ export declare function query(v: unknown): string;
6
+ export declare function page(v: unknown, product: ProductCode): FeedbackPage;
7
+ export declare function notices(v: unknown): {
8
+ items: FeedbackNotice[];
9
+ };
10
+ export declare function receipt(v: unknown): {
11
+ id: string;
12
+ };
13
+ export declare function submitted(v: unknown): {
14
+ id: string;
15
+ message: string;
16
+ };
package/dist/schema.js ADDED
@@ -0,0 +1,67 @@
1
+ export const record = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
2
+ const fail = () => { throw new Error('Invalid feedback data'); };
3
+ const obj = (v) => record(v) ? v : fail();
4
+ const text = (v) => typeof v === 'string' ? v : fail();
5
+ export const id = (v) => typeof v === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v) ? v : fail();
6
+ const date = (v) => typeof v === 'string' && Number.isFinite(Date.parse(v)) ? v : fail();
7
+ const nullableDate = (v) => v === null ? null : date(v);
8
+ const kind = (v) => ['问题反馈', '功能建议', '体验优化', '其他意见'].includes(text(v)) ? v : fail();
9
+ const keys = (v, allowed) => { if (Object.keys(v).some(k => !allowed.includes(k)))
10
+ fail(); };
11
+ export function input(v) {
12
+ const o = obj(v);
13
+ keys(o, ['kind', 'body', 'contact', 'consent', 'requestKey', 'context']);
14
+ const body = text(o.body), contact = text(o.contact), requestKey = text(o.requestKey);
15
+ if ([...body.trim()].length < 1 || [...body.trim()].length > 500 || [...contact].length > 100 || typeof o.consent !== 'boolean' || !/^[A-Za-z0-9_-]{8,100}$/.test(requestKey))
16
+ fail();
17
+ let context;
18
+ if (o.context !== undefined) {
19
+ const c = obj(o.context);
20
+ keys(c, ['page', 'courseId', 'classId']);
21
+ context = {};
22
+ if (c.page !== undefined) {
23
+ const page = text(c.page);
24
+ if (page.length > 500 || !/^\/(?!\/)[^?#]*$/.test(page))
25
+ fail();
26
+ context.page = page;
27
+ }
28
+ if (c.courseId !== undefined)
29
+ context.courseId = id(c.courseId);
30
+ if (c.classId !== undefined)
31
+ context.classId = id(c.classId);
32
+ }
33
+ return { kind: kind(o.kind), body, contact, consent: o.consent, requestKey, ...(context === undefined ? {} : { context }) };
34
+ }
35
+ export function query(v) {
36
+ const q = obj(v);
37
+ keys(q, ['page', 'id']);
38
+ const params = new URLSearchParams();
39
+ if (q.page !== undefined) {
40
+ if (!Number.isInteger(q.page) || Number(q.page) < 1 || Number(q.page) > 100000)
41
+ fail();
42
+ params.set('page', String(q.page));
43
+ }
44
+ if (q.id !== undefined)
45
+ params.set('id', id(q.id));
46
+ return params.size ? '?' + params.toString() : '';
47
+ }
48
+ export function page(v, product) {
49
+ const p = obj(v);
50
+ if (!Array.isArray(p.items) || p.items.length > 20 || !Number.isInteger(p.page) || Number(p.page) < 1 || Number(p.page) > 100000 || typeof p.hasMore !== 'boolean')
51
+ fail();
52
+ const items = p.items.map((raw) => {
53
+ const x = obj(raw);
54
+ if (x.product_code !== product || !['submitted', 'handled'].includes(text(x.status)))
55
+ fail();
56
+ return { id: id(x.id), product_code: product, kind: kind(x.kind), body: text(x.body), status: x.status, reply: text(x.reply), created_at: date(x.created_at), handled_at: nullableDate(x.handled_at) };
57
+ });
58
+ return { items, page: p.page, hasMore: p.hasMore };
59
+ }
60
+ export function notices(v) {
61
+ const o = obj(v);
62
+ if (!Array.isArray(o.items))
63
+ fail();
64
+ return { items: o.items.map(raw => { const x = obj(raw); return { id: id(x.id), title: text(x.title), body: text(x.body), feedback_id: id(x.feedback_id), created_at: date(x.created_at), read_at: nullableDate(x.read_at) }; }) };
65
+ }
66
+ export function receipt(v) { return { id: id(obj(v).id) }; }
67
+ export function submitted(v) { return { ...receipt(v), message: text(obj(v).message) }; }
@@ -0,0 +1,9 @@
1
+ import type { LoomFeedbackClientOptions, FeedbackResult, CallOptions } from './types.js';
2
+ export declare class LoomFeedbackError extends Error {
3
+ readonly code: string;
4
+ readonly status: number;
5
+ readonly requestId?: string | undefined;
6
+ readonly retryAfter?: number | undefined;
7
+ constructor(code: string, status: number, requestId?: string | undefined, retryAfter?: number | undefined);
8
+ }
9
+ export declare function transport(options: LoomFeedbackClientOptions): <T>(method: string, path: string, parse: (v: unknown) => T, headers: Record<string, string>, body: unknown, opts?: CallOptions) => Promise<FeedbackResult<T>>;
@@ -0,0 +1,113 @@
1
+ import { record } from './schema.js';
2
+ export class LoomFeedbackError extends Error {
3
+ code;
4
+ status;
5
+ requestId;
6
+ retryAfter;
7
+ constructor(code, status, requestId, retryAfter) {
8
+ super(`Loom feedback request failed (${code})`);
9
+ this.code = code;
10
+ this.status = status;
11
+ this.requestId = requestId;
12
+ this.retryAfter = retryAfter;
13
+ this.name = 'LoomFeedbackError';
14
+ }
15
+ }
16
+ export function transport(options) {
17
+ const base = new URL(options.baseUrl);
18
+ if (base.username ||
19
+ base.password ||
20
+ base.search ||
21
+ base.hash ||
22
+ base.pathname !== '/' ||
23
+ (base.protocol !== 'https:' &&
24
+ !(options.allowLoopbackHttp &&
25
+ base.protocol === 'http:' &&
26
+ ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname))))
27
+ throw new Error('baseUrl must be an HTTPS origin (or explicit loopback HTTP)');
28
+ if (!/^[A-Za-z0-9_-]{32,256}$/.test(options.applicationSecret))
29
+ throw new Error('Invalid applicationSecret');
30
+ const defaultTimeoutMs = options.timeoutMs ?? 10000;
31
+ const timeoutMs = defaultTimeoutMs;
32
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647)
33
+ throw new Error('Invalid timeoutMs');
34
+ const fetcher = options.fetch ?? globalThis.fetch;
35
+ // Capture immutable credential/configuration values; callers cannot mutate a shared client.
36
+ const secret = options.applicationSecret;
37
+ return async function call(method, path, parse, headers, body, opts) {
38
+ const timeoutMs = opts?.timeoutMs ?? defaultTimeoutMs;
39
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647)
40
+ throw new LoomFeedbackError('INVALID_INPUT', 0);
41
+ const controller = new AbortController();
42
+ let timedOut = false;
43
+ let requestId;
44
+ const external = opts?.signal;
45
+ const abort = () => controller.abort();
46
+ external?.addEventListener('abort', abort, { once: true });
47
+ if (external?.aborted)
48
+ abort();
49
+ const timer = setTimeout(() => {
50
+ timedOut = true;
51
+ controller.abort();
52
+ }, timeoutMs);
53
+ try {
54
+ if (controller.signal.aborted)
55
+ throw new Error('aborted');
56
+ const response = await fetcher(new URL(path, base), {
57
+ method,
58
+ redirect: 'error',
59
+ cache: 'no-store',
60
+ signal: controller.signal,
61
+ headers: {
62
+ Authorization: `Bearer ${secret}`,
63
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
64
+ ...headers,
65
+ },
66
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
67
+ });
68
+ const rid = response.headers.get('x-request-id');
69
+ requestId = rid && /^[A-Za-z0-9_-]{1,128}$/.test(rid) ? rid : undefined;
70
+ if (response.headers.get('content-type')?.split(';')[0].trim() !== 'application/json')
71
+ throw new LoomFeedbackError('PROTOCOL_ERROR', response.status, requestId);
72
+ let value;
73
+ try {
74
+ value = await response.json();
75
+ }
76
+ catch {
77
+ if (controller.signal.aborted)
78
+ throw new Error('aborted');
79
+ throw new LoomFeedbackError('PROTOCOL_ERROR', response.status, requestId);
80
+ }
81
+ if (!response.ok) {
82
+ if (!record(value) ||
83
+ !record(value.error) ||
84
+ typeof value.error.code !== 'string' ||
85
+ !/^[A-Z][A-Z0-9_]{0,63}$/.test(value.error.code))
86
+ throw new LoomFeedbackError('PROTOCOL_ERROR', response.status, requestId);
87
+ const retry = response.headers.get('retry-after');
88
+ const seconds = retry && /^\d+$/.test(retry) ? Number(retry) : undefined;
89
+ throw new LoomFeedbackError(value.error.code, response.status, requestId, seconds !== undefined && Number.isSafeInteger(seconds) ? seconds : undefined);
90
+ }
91
+ if (response.status !== 200 ||
92
+ !record(value) ||
93
+ !requestId ||
94
+ value.requestId !== requestId)
95
+ throw new LoomFeedbackError('PROTOCOL_ERROR', response.status, requestId);
96
+ try {
97
+ return { data: parse(value.data), requestId };
98
+ }
99
+ catch {
100
+ throw new LoomFeedbackError('PROTOCOL_ERROR', response.status, requestId);
101
+ }
102
+ }
103
+ catch (error) {
104
+ if (error instanceof LoomFeedbackError)
105
+ throw error;
106
+ throw new LoomFeedbackError(timedOut ? 'TIMEOUT' : external?.aborted ? 'ABORTED' : 'NETWORK_ERROR', 0, requestId);
107
+ }
108
+ finally {
109
+ clearTimeout(timer);
110
+ external?.removeEventListener('abort', abort);
111
+ }
112
+ };
113
+ }
@@ -0,0 +1,60 @@
1
+ export type ProductCode = 'studio' | 'teaching';
2
+ export type FeedbackKind = '问题反馈' | '功能建议' | '体验优化' | '其他意见';
3
+ export interface FeedbackInput {
4
+ kind: FeedbackKind;
5
+ body: string;
6
+ contact: string;
7
+ consent: boolean;
8
+ requestKey: string;
9
+ context?: {
10
+ page?: string;
11
+ courseId?: string;
12
+ classId?: string;
13
+ };
14
+ }
15
+ export interface FeedbackItem {
16
+ id: string;
17
+ product_code: ProductCode;
18
+ kind: FeedbackKind;
19
+ body: string;
20
+ status: 'submitted' | 'handled';
21
+ reply: string;
22
+ created_at: string;
23
+ handled_at: string | null;
24
+ }
25
+ export interface FeedbackPage {
26
+ items: FeedbackItem[];
27
+ page: number;
28
+ hasMore: boolean;
29
+ }
30
+ export interface FeedbackNotice {
31
+ id: string;
32
+ title: string;
33
+ body: string;
34
+ feedback_id: string;
35
+ created_at: string;
36
+ read_at: string | null;
37
+ }
38
+ export interface FeedbackQuery {
39
+ page?: number;
40
+ id?: string;
41
+ }
42
+ export interface CallOptions {
43
+ signal?: AbortSignal;
44
+ timeoutMs?: number;
45
+ }
46
+ export interface UserCallOptions extends CallOptions {
47
+ sessionToken: string;
48
+ }
49
+ export interface FeedbackResult<T> {
50
+ data: T;
51
+ requestId: string;
52
+ }
53
+ export interface LoomFeedbackClientOptions {
54
+ baseUrl: string;
55
+ applicationSecret: string;
56
+ productCode: ProductCode;
57
+ timeoutMs?: number;
58
+ allowLoopbackHttp?: boolean;
59
+ fetch?: typeof globalThis.fetch;
60
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@aimarch/loom-feedback",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Server-only product-scoped Loom feedback HTTP client",
5
+ "type": "module",
6
+ "files": [
7
+ "dist",
8
+ "README.md"
9
+ ],
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "scripts": {
20
+ "build": "tsc -p tsconfig.json",
21
+ "prepack": "npm run build"
22
+ },
23
+ "devDependencies": {
24
+ "typescript": "^5.9.3"
25
+ },
26
+ "publishConfig": {
27
+ "registry": "https://registry.npmjs.org/"
28
+ }
29
+ }