@vite-hub/comments 0.0.0 → 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.
Files changed (59) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +243 -0
  3. package/dist/anchor.d.ts +40 -0
  4. package/dist/anchor.js +128 -0
  5. package/dist/client.d.ts +101 -0
  6. package/dist/client.js +553 -0
  7. package/dist/console-BIz9t2cO.d.ts +243 -0
  8. package/dist/database/postgres.d.ts +1011 -0
  9. package/dist/database/postgres.js +60 -0
  10. package/dist/database-BSnVrwHn.js +60 -0
  11. package/dist/database-C-ktS9Do.js +95 -0
  12. package/dist/database-Cb2xjC1V.d.ts +1096 -0
  13. package/dist/database.d.ts +104 -0
  14. package/dist/database.js +3 -0
  15. package/dist/define-BzW2Ychn.d.ts +46 -0
  16. package/dist/define-Cbhl6QVJ.js +32 -0
  17. package/dist/errors-BAQYcy3_.d.ts +89 -0
  18. package/dist/errors-DeD6wTCl.js +77 -0
  19. package/dist/h3-v1-request-DDGXJ9E7.js +166 -0
  20. package/dist/identity-3qtVC4rF.js +34 -0
  21. package/dist/index-DklG2Etf.d.ts +111 -0
  22. package/dist/index.d.ts +7 -0
  23. package/dist/index.js +5 -0
  24. package/dist/operations-0B0QTVWX.d.ts +138 -0
  25. package/dist/operations-NZG5dB8y.js +732 -0
  26. package/dist/operations.d.ts +7 -0
  27. package/dist/operations.js +2 -0
  28. package/dist/overlay/overlay.js +195 -0
  29. package/dist/page/loader.js +22 -0
  30. package/dist/page-BtXADR6d.d.ts +21 -0
  31. package/dist/page-BuroSMXO.js +38 -0
  32. package/dist/page-tools-shared-D-amu6sx.js +53 -0
  33. package/dist/plugin-QElKQYkA.js +725 -0
  34. package/dist/realtime.d.ts +18 -0
  35. package/dist/realtime.js +48 -0
  36. package/dist/request-DVc3M_AG.js +14 -0
  37. package/dist/rpc.d.ts +29 -0
  38. package/dist/rpc.js +75 -0
  39. package/dist/runtime/auth.d.ts +6 -0
  40. package/dist/runtime/auth.js +15 -0
  41. package/dist/runtime/connect/node.d.ts +1 -0
  42. package/dist/runtime/connect/node.js +2 -0
  43. package/dist/runtime/connect.d.ts +1 -0
  44. package/dist/runtime/connect.js +2 -0
  45. package/dist/runtime/console.d.ts +5 -0
  46. package/dist/runtime/console.js +59 -0
  47. package/dist/runtime/index.d.ts +222 -0
  48. package/dist/runtime/index.js +665 -0
  49. package/dist/server-BomGg3Gb.js +63 -0
  50. package/dist/server.d.ts +94 -0
  51. package/dist/server.js +326 -0
  52. package/dist/src-CRTwnaEG.js +1362 -0
  53. package/dist/testing.d.ts +30 -0
  54. package/dist/testing.js +175 -0
  55. package/dist/types-Cj8K7Vx7.d.ts +176 -0
  56. package/dist/types-Un2dcJWD.d.ts +288 -0
  57. package/dist/vite.d.ts +304 -0
  58. package/dist/vite.js +1921 -0
  59. package/package.json +156 -4
@@ -0,0 +1,104 @@
1
+ import { i as commentsSchema, n as commentMessages, r as commentThreads, t as commentCounters } from "./database-Cb2xjC1V.js";
2
+ import { AnySQLiteColumn, SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
3
+ //#region src/tables.d.ts
4
+ /**
5
+ * The tables of `commentsSchema` as SQLite statements that are safe to run on every start. A database that Comments
6
+ * opens itself gets them on first use; a ViteHub Database gets the same tables from `vitehub db generate` instead.
7
+ */
8
+ export declare const commentsTables: readonly string[];
9
+ //#endregion
10
+ //#region src/database.d.ts
11
+ type Column<Table extends string, Data, NotNull extends boolean, PrimaryKey extends boolean = false, HasDefault extends boolean = false> = AnySQLiteColumn<{
12
+ data: Data;
13
+ hasDefault: HasDefault;
14
+ isPrimaryKey: PrimaryKey;
15
+ notNull: NotNull;
16
+ tableName: Table;
17
+ }> & {
18
+ _: {
19
+ generated: undefined;
20
+ };
21
+ };
22
+ type ThreadColumn<Data, NotNull extends boolean, PrimaryKey extends boolean = false, HasDefault extends boolean = false> = Column<"vitehub_comment_threads", Data, NotNull, PrimaryKey, HasDefault>;
23
+ type CommentColumn<Data, NotNull extends boolean, PrimaryKey extends boolean = false> = Column<"vitehub_comments", Data, NotNull, PrimaryKey>;
24
+ type ForgeColumn<Data, NotNull extends boolean, PrimaryKey extends boolean = false, HasDefault extends boolean = false> = Column<"vitehub_comment_forge", Data, NotNull, PrimaryKey, HasDefault>;
25
+ /** The `vitehub_comment_forge` table, typed explicitly so its declaration can be emitted. */
26
+ export type CommentForgeTable = SQLiteTableWithColumns<{
27
+ columns: {
28
+ id: ForgeColumn<string, true, true>;
29
+ threadId: ForgeColumn<string, false>;
30
+ repository: ForgeColumn<string, true>;
31
+ pullRequest: ForgeColumn<number, true>;
32
+ remoteId: ForgeColumn<string, false>;
33
+ nodeId: ForgeColumn<string, false>;
34
+ url: ForgeColumn<string, false>;
35
+ digest: ForgeColumn<string, false>;
36
+ postedAs: ForgeColumn<"author" | "app", false>;
37
+ minimized: ForgeColumn<boolean, true, false, true>;
38
+ error: ForgeColumn<string, false>;
39
+ updatedAt: ForgeColumn<number, true>;
40
+ };
41
+ dialect: "sqlite";
42
+ name: "vitehub_comment_forge";
43
+ schema: undefined;
44
+ }>;
45
+ /** The `vitehub_comment_threads` table, typed explicitly so its declaration can be emitted. */
46
+ export type CommentThreadsTable = SQLiteTableWithColumns<{
47
+ columns: {
48
+ id: ThreadColumn<string, true, true>;
49
+ scope: ThreadColumn<string, true, false, true>;
50
+ number: ThreadColumn<number, true, false, true>;
51
+ page: ThreadColumn<string, true>;
52
+ anchor: ThreadColumn<string, true>;
53
+ context: ThreadColumn<string, false>;
54
+ metadata: ThreadColumn<string, false>;
55
+ status: ThreadColumn<"open" | "resolved", true>;
56
+ createdBy: ThreadColumn<string, true>;
57
+ resolvedBy: ThreadColumn<string, false>;
58
+ resolvedAt: ThreadColumn<number, false>;
59
+ createdAt: ThreadColumn<number, true>;
60
+ updatedAt: ThreadColumn<number, true>;
61
+ };
62
+ dialect: "sqlite";
63
+ name: "vitehub_comment_threads";
64
+ schema: undefined;
65
+ }>;
66
+ /** Allocation history survives thread and scope deletion. */
67
+ export type CommentScopeCountersTable = SQLiteTableWithColumns<{
68
+ columns: {
69
+ scope: Column<"vitehub_comment_scope_counters", string, true, true>;
70
+ lastNumber: Column<"vitehub_comment_scope_counters", number, true>;
71
+ };
72
+ dialect: "sqlite";
73
+ name: "vitehub_comment_scope_counters";
74
+ schema: undefined;
75
+ }>;
76
+ /** The `vitehub_comments` table, typed explicitly so its declaration can be emitted. */
77
+ export type CommentsTable = SQLiteTableWithColumns<{
78
+ columns: {
79
+ id: CommentColumn<string, true, true>;
80
+ threadId: CommentColumn<string, true>;
81
+ body: CommentColumn<string, true>;
82
+ mentions: CommentColumn<string, true>;
83
+ author: CommentColumn<string, true>;
84
+ createdAt: CommentColumn<number, true>;
85
+ editedAt: CommentColumn<number, false>;
86
+ };
87
+ dialect: "sqlite";
88
+ name: "vitehub_comments";
89
+ schema: undefined;
90
+ }>;
91
+ /**
92
+ * The tables behind Comments, including forge links and scope numbering. ViteHub adds them to the Database of
93
+ * `defineComments({ database })` for you; add them yourself only to a Database configured without ViteHub.
94
+ * For existing tables, follow https://vitehub.dev/docs/comments/configure#upgrade-existing-comments before
95
+ * applying the migration that `vitehub db generate` writes.
96
+ */
97
+ declare const commentsSchema$1: {
98
+ vitehubCommentThreads: CommentThreadsTable;
99
+ vitehubComments: CommentsTable;
100
+ vitehubCommentForge: CommentForgeTable;
101
+ vitehubCommentScopeCounters: CommentScopeCountersTable;
102
+ };
103
+ //#endregion
104
+ export { commentCounters, commentMessages, commentThreads, commentsSchema as commentsOperationsSchema, commentsSchema$1 as commentsSchema };
@@ -0,0 +1,3 @@
1
+ import { i as commentsSchema, n as commentMessages, r as commentThreads, t as commentCounters } from "./database-BSnVrwHn.js";
2
+ import { n as commentsTables, t as commentsSchema$1 } from "./database-C-ktS9Do.js";
3
+ export { commentCounters, commentMessages, commentThreads, commentsSchema as commentsOperationsSchema, commentsSchema$1 as commentsSchema, commentsTables };
@@ -0,0 +1,46 @@
1
+ import { _ as CommentUser, d as CommentMessage, g as CommentThread, h as CommentSubject, n as CommentActor } from "./types-Cj8K7Vx7.js";
2
+ //#region src/operations-core/define.d.ts
3
+ type CommentAction = "read" | "write" | "resolve" | "delete";
4
+ interface CommentsAuthorizeContext {
5
+ /** The signed-in user, including application fields such as `role`, or null. */
6
+ user: (CommentUser & Record<string, unknown>) | null;
7
+ /** The Agent Actor when an agent acts for `user`. */
8
+ actor?: CommentActor;
9
+ action: CommentAction;
10
+ /** The thread that the action is about. Not set for `create`, `list`, and `users`. */
11
+ thread?: CommentThread;
12
+ /**
13
+ * What the action is about: the subject of `thread`, the subject that `create` starts a thread on, or the subject
14
+ * that a `list` filters by. Not set for a `list` with no filter and for `users`.
15
+ */
16
+ subject?: CommentSubject;
17
+ }
18
+ /** Decides whether a person or an Agent may take an action. Comments are private: without it, nobody can read. */
19
+ type CommentsAuthorize = (context: CommentsAuthorizeContext) => boolean | Promise<boolean>;
20
+ /** A kind of subject that threads can be about. */
21
+ interface CommentSubjectDefinition {
22
+ kind: string;
23
+ /** The numbering scope of a subject id. `n` is unique inside a scope. */
24
+ scope: (subjectId: string) => string;
25
+ }
26
+ interface CommentMentionEvent {
27
+ thread: CommentThread;
28
+ message: CommentMessage;
29
+ /** The users that this message mentions for the first time. */
30
+ mentioned: CommentUser[];
31
+ }
32
+ interface CommentsDefinition {
33
+ authorize?: CommentsAuthorize;
34
+ /** Subject kinds in addition to `page` (scope `site`) and `content` (scope `site`). */
35
+ subjects?: readonly CommentSubjectDefinition[];
36
+ /** Runs after a message that mentions someone is saved. A failure is logged and never fails the comment. */
37
+ onMention?: (event: CommentMentionEvent) => void | Promise<void>;
38
+ }
39
+ /** Validate the imported application module before installing its runtime. */
40
+ declare function validateCommentsDefinition(value: unknown, file: string): CommentsDefinition;
41
+ /** A subject kind of your own, such as `drop`. */
42
+ declare function defineCommentSubject(subject: CommentSubjectDefinition): CommentSubjectDefinition;
43
+ /** Subjects that exist without a definition. */
44
+ declare const builtinCommentSubjects: readonly CommentSubjectDefinition[];
45
+ //#endregion
46
+ export { CommentsAuthorizeContext as a, defineCommentSubject as c, CommentsAuthorize as i, validateCommentsDefinition as l, CommentMentionEvent as n, CommentsDefinition as o, CommentSubjectDefinition as r, builtinCommentSubjects as s, CommentAction as t };
@@ -0,0 +1,32 @@
1
+ import { t as commentsErrorDiagnostics } from "./errors-DeD6wTCl.js";
2
+ //#region src/operations-core/define.ts
3
+ const marker = Symbol.for("vitehub.comments.definition");
4
+ /** The definition that `server/comments.ts` default-exports. */
5
+ function defineComments(definition = {}) {
6
+ return Object.freeze({
7
+ ...definition,
8
+ [marker]: true
9
+ });
10
+ }
11
+ function isCommentsDefinition(value) {
12
+ return value !== null && Object(value) === value && Reflect.get(Object(value), marker) === true;
13
+ }
14
+ /** Validate the imported application module before installing its runtime. */
15
+ function validateCommentsDefinition(value, file) {
16
+ if (!isCommentsDefinition(value)) throw commentsErrorDiagnostics.COMMENTS_B0002({ file });
17
+ return value;
18
+ }
19
+ /** A subject kind of your own, such as `drop`. */
20
+ function defineCommentSubject(subject) {
21
+ return Object.freeze({ ...subject });
22
+ }
23
+ /** Subjects that exist without a definition. */
24
+ const builtinCommentSubjects = [defineCommentSubject({
25
+ kind: "page",
26
+ scope: () => "site"
27
+ }), defineCommentSubject({
28
+ kind: "content",
29
+ scope: () => "site"
30
+ })];
31
+ //#endregion
32
+ export { validateCommentsDefinition as i, defineCommentSubject as n, defineComments as r, builtinCommentSubjects as t };
@@ -0,0 +1,89 @@
1
+ //#region src/operations-core/errors.d.ts
2
+ declare const commentsErrorDiagnostics: import("nostics").Diagnostics<{
3
+ readonly COMMENTS_R0001: {
4
+ readonly why: ({ target }: {
5
+ target: string;
6
+ }) => string;
7
+ readonly fix: "Pass an element, a non-empty selection, or a point that is over an element of the page.";
8
+ };
9
+ readonly COMMENTS_R0002: {
10
+ readonly why: ({ id }: {
11
+ id: string;
12
+ }) => string;
13
+ readonly fix: "List the threads again, because someone may have deleted this one.";
14
+ };
15
+ readonly COMMENTS_R0003: {
16
+ readonly why: ({ messageId }: {
17
+ messageId: string;
18
+ }) => string;
19
+ readonly fix: "Read the thread again, because someone may have deleted the message.";
20
+ };
21
+ readonly COMMENTS_R0004: {
22
+ readonly why: "Only the author of a message can edit or delete it.";
23
+ readonly fix: "Sign in as the author, or ask them to change the message.";
24
+ };
25
+ readonly COMMENTS_R0005: {
26
+ readonly why: "A comment needs some text.";
27
+ readonly fix: "Write at least one character before you send.";
28
+ };
29
+ readonly COMMENTS_R0006: {
30
+ readonly why: "server/comments.ts defines no authorize policy, so nobody can read or write comments.";
31
+ readonly fix: "Pass authorize to defineComments({ authorize }) and return true for the people and Agents that may take the action.";
32
+ };
33
+ readonly COMMENTS_R0007: {
34
+ readonly why: ({ message }: {
35
+ message: string;
36
+ }) => string;
37
+ readonly fix: "Mention only people that users() finds, and write @ and their name in the text.";
38
+ };
39
+ readonly COMMENTS_R0008: {
40
+ readonly why: ({ kind }: {
41
+ kind: string;
42
+ }) => string;
43
+ readonly fix: "Use page or content, or add defineCommentSubject({ kind, scope }) to defineComments({ subjects }).";
44
+ };
45
+ readonly COMMENTS_R0009: {
46
+ readonly why: ({ action }: {
47
+ action: string;
48
+ }) => string;
49
+ readonly fix: "Ask for access, or allow the action in defineComments({ authorize }).";
50
+ };
51
+ readonly COMMENTS_R0010: {
52
+ readonly why: "The comments runtime is not installed.";
53
+ readonly fix: "Add server/comments.ts and enable the Database with vitehub({ database: true }). `vite dev` and builds install the runtime for you.";
54
+ };
55
+ readonly COMMENTS_R0011: {
56
+ readonly why: "The comment numbers of this scope are busy.";
57
+ readonly fix: "Try again. Several people created a comment at the same moment.";
58
+ };
59
+ readonly COMMENTS_R0012: {
60
+ readonly why: "Writing a comment needs a signed-in user.";
61
+ readonly fix: "Sign in, then try again. In `vite dev` without sign-in, set console.auth so comments know who writes.";
62
+ };
63
+ readonly COMMENTS_R0013: {
64
+ readonly why: "The comments request did not get an answer from the server.";
65
+ readonly fix: "Check the connection and the app URL, then try again.";
66
+ };
67
+ readonly COMMENTS_R0014: {
68
+ readonly why: "Attachments are not supported yet: no operation uploads a file for a comment.";
69
+ readonly fix: "Send the comment without attachments. They arrive with the upload operation.";
70
+ };
71
+ readonly COMMENTS_R0015: {
72
+ readonly why: "The comment list kept changing while its pages were loading.";
73
+ readonly fix: "Refresh again. The previous cache is kept until two complete scans agree.";
74
+ };
75
+ readonly COMMENTS_B0001: {
76
+ readonly why: ({ file }: {
77
+ file: string;
78
+ }) => string;
79
+ readonly fix: "Remove `database: false` from vitehub(), or set `database: true`. vitehub() turns the Database on for comments when the option is unset.";
80
+ };
81
+ readonly COMMENTS_B0002: {
82
+ readonly why: ({ file }: {
83
+ file: string;
84
+ }) => string;
85
+ readonly fix: "Write `export default defineComments({ authorize })` in server/comments.ts.";
86
+ };
87
+ }, readonly import("nostics").AnyDiagnosticReporter[], never>;
88
+ //#endregion
89
+ export { commentsErrorDiagnostics as t };
@@ -0,0 +1,77 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/operations-core/errors.ts
3
+ const commentsErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
4
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
5
+ codes: {
6
+ COMMENTS_R0001: {
7
+ why: ({ target }) => `createAnchor() found nothing to anchor to for ${target}.`,
8
+ fix: "Pass an element, a non-empty selection, or a point that is over an element of the page."
9
+ },
10
+ COMMENTS_R0002: {
11
+ why: ({ id }) => `The comment thread "${id}" does not exist.`,
12
+ fix: "List the threads again, because someone may have deleted this one."
13
+ },
14
+ COMMENTS_R0003: {
15
+ why: ({ messageId }) => `The comment message "${messageId}" does not exist in this thread.`,
16
+ fix: "Read the thread again, because someone may have deleted the message."
17
+ },
18
+ COMMENTS_R0004: {
19
+ why: "Only the author of a message can edit or delete it.",
20
+ fix: "Sign in as the author, or ask them to change the message."
21
+ },
22
+ COMMENTS_R0005: {
23
+ why: "A comment needs some text.",
24
+ fix: "Write at least one character before you send."
25
+ },
26
+ COMMENTS_R0006: {
27
+ why: "server/comments.ts defines no authorize policy, so nobody can read or write comments.",
28
+ fix: "Pass authorize to defineComments({ authorize }) and return true for the people and Agents that may take the action."
29
+ },
30
+ COMMENTS_R0007: {
31
+ why: ({ message }) => message,
32
+ fix: "Mention only people that users() finds, and write @ and their name in the text."
33
+ },
34
+ COMMENTS_R0008: {
35
+ why: ({ kind }) => `The comment subject kind "${kind}" is not defined.`,
36
+ fix: "Use page or content, or add defineCommentSubject({ kind, scope }) to defineComments({ subjects })."
37
+ },
38
+ COMMENTS_R0009: {
39
+ why: ({ action }) => `This user or Agent may not ${action} this comment.`,
40
+ fix: "Ask for access, or allow the action in defineComments({ authorize })."
41
+ },
42
+ COMMENTS_R0010: {
43
+ why: "The comments runtime is not installed.",
44
+ fix: "Add server/comments.ts and enable the Database with vitehub({ database: true }). `vite dev` and builds install the runtime for you."
45
+ },
46
+ COMMENTS_R0011: {
47
+ why: "The comment numbers of this scope are busy.",
48
+ fix: "Try again. Several people created a comment at the same moment."
49
+ },
50
+ COMMENTS_R0012: {
51
+ why: "Writing a comment needs a signed-in user.",
52
+ fix: "Sign in, then try again. In `vite dev` without sign-in, set console.auth so comments know who writes."
53
+ },
54
+ COMMENTS_R0013: {
55
+ why: "The comments request did not get an answer from the server.",
56
+ fix: "Check the connection and the app URL, then try again."
57
+ },
58
+ COMMENTS_R0014: {
59
+ why: "Attachments are not supported yet: no operation uploads a file for a comment.",
60
+ fix: "Send the comment without attachments. They arrive with the upload operation."
61
+ },
62
+ COMMENTS_R0015: {
63
+ why: "The comment list kept changing while its pages were loading.",
64
+ fix: "Refresh again. The previous cache is kept until two complete scans agree."
65
+ },
66
+ COMMENTS_B0001: {
67
+ why: ({ file }) => `${file} needs a Database, but the Database is off for this app.`,
68
+ fix: "Remove `database: false` from vitehub(), or set `database: true`. vitehub() turns the Database on for comments when the option is unset."
69
+ },
70
+ COMMENTS_B0002: {
71
+ why: ({ file }) => `${file} must default-export defineComments().`,
72
+ fix: "Write `export default defineComments({ authorize })` in server/comments.ts."
73
+ }
74
+ }
75
+ });
76
+ //#endregion
77
+ export { commentsErrorDiagnostics as t };
@@ -0,0 +1,166 @@
1
+ //#region ../internal/src/runtime/h3-v1-request.ts
2
+ const payloadMethods = /* @__PURE__ */ new Set([
3
+ "DELETE",
4
+ "PATCH",
5
+ "POST",
6
+ "PUT"
7
+ ]);
8
+ const rawBodySymbol = Symbol.for("h3RawBody");
9
+ const nodeEventRequests = /* @__PURE__ */ new WeakMap();
10
+ /** Return true for an event with an own `node.req` object, such as an H3 1 event. */
11
+ function isH3V1Event(input) {
12
+ if (!Object.hasOwn(input, "node")) return false;
13
+ const node = Reflect.get(input, "node");
14
+ return isObjectLike(node) && isObjectLike(Reflect.get(node, "req"));
15
+ }
16
+ function isObjectLike(value) {
17
+ return value !== null && (typeof value === "object" || typeof value === "function");
18
+ }
19
+ function isWebRequest(value) {
20
+ if (!isObjectLike(value)) return false;
21
+ const headers = Reflect.get(value, "headers");
22
+ return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObjectLike(headers) && typeof Reflect.get(headers, "get") === "function";
23
+ }
24
+ function firstHeader(value) {
25
+ return Array.isArray(value) ? value[0] : value;
26
+ }
27
+ function readNodeRequestHeaders(request) {
28
+ const headers = new Headers();
29
+ for (const [name, value] of Object.entries(request.headers)) if (Array.isArray(value)) for (const item of value) headers.append(name, item);
30
+ else if (value !== void 0) headers.set(name, value);
31
+ return headers;
32
+ }
33
+ /** Rebuild the public URL. H3 1 removes the app base path from `url` and keeps it in `originalUrl`. */
34
+ function readNodeRequestURL(request) {
35
+ const host = firstHeader(request.headers.host) || "localhost";
36
+ const encrypted = request.socket?.encrypted || request.connection?.encrypted;
37
+ const protocol = firstHeader(request.headers["x-forwarded-proto"]) === "https" || encrypted ? "https" : "http";
38
+ const path = (request.originalUrl || request.url || "/").replace(/^[/\\]+/, "/");
39
+ return new URL(path, `${protocol}://${host}`);
40
+ }
41
+ function toBodyStream(value) {
42
+ if (value instanceof ReadableStream) return value;
43
+ if (value instanceof Uint8Array) return new ReadableStream({ start(controller) {
44
+ controller.enqueue(value);
45
+ controller.close();
46
+ } });
47
+ if (typeof value === "string") return new Blob([value]).stream();
48
+ if (value instanceof URLSearchParams) return new Blob([value.toString()]).stream();
49
+ if (value instanceof Object && Object.getPrototypeOf(value) === Object.prototype) return new Blob([JSON.stringify(value)]).stream();
50
+ }
51
+ async function openNodeRequestBody(event) {
52
+ const request = event.node.req;
53
+ const stored = event._requestBody ?? request[rawBodySymbol] ?? request.rawBody ?? request.body;
54
+ if (stored !== void 0 && stored !== null) {
55
+ const stream = toBodyStream(await stored);
56
+ if (stream) {
57
+ const reader = stream.getReader();
58
+ return () => reader.read();
59
+ }
60
+ }
61
+ const iterator = request[Symbol.asyncIterator]?.();
62
+ if (!iterator) return void 0;
63
+ const chunks = [];
64
+ const collected = [];
65
+ let total = 0;
66
+ let ended = false;
67
+ let failed = false;
68
+ let failure;
69
+ let waiting;
70
+ const produce = async () => {
71
+ try {
72
+ for await (const chunk of { [Symbol.asyncIterator]: () => iterator }) {
73
+ let bytes;
74
+ if (typeof chunk === "string") bytes = new TextEncoder().encode(chunk);
75
+ else if (chunk instanceof Uint8Array) bytes = chunk;
76
+ else throw new TypeError("[vitehub] Request body chunks must be strings or bytes.");
77
+ collected.push(bytes);
78
+ total += bytes.byteLength;
79
+ if (waiting) {
80
+ waiting.resolve({ value: bytes });
81
+ waiting = void 0;
82
+ } else chunks.push(bytes);
83
+ }
84
+ ended = true;
85
+ waiting?.resolve({ done: true });
86
+ waiting = void 0;
87
+ } catch (error) {
88
+ failed = true;
89
+ failure = error;
90
+ ended = true;
91
+ waiting?.reject(error);
92
+ waiting = void 0;
93
+ throw error;
94
+ }
95
+ const bytes = new Uint8Array(total);
96
+ let offset = 0;
97
+ for (const chunk of collected) {
98
+ bytes.set(chunk, offset);
99
+ offset += chunk.byteLength;
100
+ }
101
+ return bytes;
102
+ };
103
+ let body;
104
+ const start = () => body ??= produce();
105
+ event._requestBody = { then: (resolve, reject) => start().then(resolve, reject) };
106
+ return async () => {
107
+ start();
108
+ body?.catch(() => {});
109
+ if (failed) throw failure;
110
+ if (chunks.length) return { value: chunks.shift() };
111
+ if (ended) return { done: true };
112
+ return new Promise((resolve, reject) => {
113
+ waiting = {
114
+ resolve,
115
+ reject
116
+ };
117
+ });
118
+ };
119
+ }
120
+ /** Read the body lazily, from a value a host already read or from the Node request stream. */
121
+ function readNodeRequestBody(event) {
122
+ let reader;
123
+ return new ReadableStream({ async pull(controller) {
124
+ const chunk = await (await (reader ??= openNodeRequestBody(event)))?.();
125
+ if (!chunk || chunk.done) {
126
+ controller.close();
127
+ return;
128
+ }
129
+ const value = chunk.value;
130
+ if (typeof value === "string") controller.enqueue(new TextEncoder().encode(value));
131
+ else if (value instanceof Uint8Array) controller.enqueue(value);
132
+ else controller.error(/* @__PURE__ */ new TypeError("[vitehub] Request body chunks must be strings or bytes."));
133
+ } }, { highWaterMark: 0 });
134
+ }
135
+ /** Return one Web Request per H3 1 event. The body is read only when a caller reads the Request body. */
136
+ function toH3V1Request(event) {
137
+ const cached = nodeEventRequests.get(event);
138
+ if (cached) return cached;
139
+ if (isWebRequest(event.web?.request)) return event.web.request;
140
+ const request = event.node.req;
141
+ const method = (request.method || "GET").toUpperCase();
142
+ const init = {
143
+ headers: readNodeRequestHeaders(request),
144
+ method
145
+ };
146
+ if (payloadMethods.has(method)) {
147
+ init.body = readNodeRequestBody(event);
148
+ init.duplex = "half";
149
+ }
150
+ const webRequest = new Request(readNodeRequestURL(request), init);
151
+ nodeEventRequests.set(event, webRequest);
152
+ return webRequest;
153
+ }
154
+ /**
155
+ * Return the Web Request of a request, an H3 2 event with an own `req` request, or an H3 1 event such as Nuxt 4's.
156
+ * H3 1 events have no `url`, so read the URL from the request this returns. Throws a `TypeError` for any other value.
157
+ */
158
+ function toEventRequest(event) {
159
+ if (isWebRequest(event)) return event;
160
+ const req = Object.hasOwn(event, "req") ? Reflect.get(event, "req") : void 0;
161
+ if (isWebRequest(req)) return req;
162
+ if (isH3V1Event(event)) return toH3V1Request(event);
163
+ throw new TypeError("[vitehub] Expected a Request, an H3 2 event, or an H3 1 event.");
164
+ }
165
+ //#endregion
166
+ export { toEventRequest as n, toH3V1Request as r, isH3V1Event as t };
@@ -0,0 +1,34 @@
1
+ //#region src/identity.ts
2
+ /** A non-empty string, or undefined. User records come from apps and Auth, so their fields are untrusted. */
3
+ function text(value) {
4
+ return typeof value === "string" && value ? value : void 0;
5
+ }
6
+ /** The author that a comment keeps for a user: the name, else the email, else "Someone", and the image. */
7
+ function authorOf(user) {
8
+ const author = {
9
+ id: user.id,
10
+ name: (text(user.name) ?? text(user.email) ?? "Someone").slice(0, 256)
11
+ };
12
+ const image = text(user.image);
13
+ if (image) author.image = image;
14
+ if (user.guest === true) author.guest = true;
15
+ return author;
16
+ }
17
+ /** The guest that the overlay names in its request headers after a person without an account types a name. */
18
+ function guestFromHeaders(headers) {
19
+ const id = headers.get("x-vitehub-comments-guest-id");
20
+ const name = headers.get("x-vitehub-comments-guest-name");
21
+ if (!id || !name || id.length > 64) return;
22
+ try {
23
+ const decoded = decodeURIComponent(name).trim().slice(0, 64);
24
+ return decoded ? {
25
+ id: `guest:${id}`,
26
+ name: decoded,
27
+ guest: true
28
+ } : void 0;
29
+ } catch {
30
+ return;
31
+ }
32
+ }
33
+ //#endregion
34
+ export { guestFromHeaders as n, text as r, authorOf as t };
@@ -0,0 +1,111 @@
1
+ import { C as DefineCommentsOptions$1, D as ReplyOptions, E as ReplyInput, S as CreateCommentThreadInput, T as ListCommentThreadsOptions, d as CommentThread, h as CommentsErrorCode, l as CommentMention, m as CommentsAuthorizeContext$1, o as CommentContext, r as CommentAuthor, t as Comment, w as EditCommentInput, x as CommentsUser } from "./types-Un2dcJWD.js";
2
+ import { a as CommentsAuthorizeContext$2, o as CommentsDefinition } from "./define-BzW2Ychn.js";
3
+ import { Result } from "@vite-hub/runtime";
4
+ import { RuntimeDrizzleDatabase } from "@vite-hub/database";
5
+ //#region src/definition.d.ts
6
+ /** Both entry forms share a factory; each runtime supplies its own action and thread shape. */
7
+ interface CommentsAuthorizeContext {
8
+ user: CommentsAuthorizeContext$1["user"];
9
+ action: CommentsAuthorizeContext$1["action"] | CommentsAuthorizeContext$2["action"];
10
+ /** The live-site thread scope. Operations use `subject` instead. */
11
+ scope?: CommentsAuthorizeContext$1["scope"];
12
+ thread?: CommentsAuthorizeContext$1["thread"] | CommentsAuthorizeContext$2["thread"];
13
+ actor?: CommentsAuthorizeContext$2["actor"];
14
+ subject?: CommentsAuthorizeContext$2["subject"];
15
+ }
16
+ type DefineCommentsOptions = Omit<DefineCommentsOptions$1, "authorize"> & Omit<CommentsDefinition, "authorize"> & {
17
+ authorize?: (context: CommentsAuthorizeContext) => boolean | void | Promise<boolean | void>;
18
+ };
19
+ //#endregion
20
+ //#region src/store.d.ts
21
+ type CommentsDatabase = RuntimeDrizzleDatabase<Record<string, unknown>>;
22
+ //#endregion
23
+ //#region src/context.d.ts
24
+ /**
25
+ * The context of a thread as label and value pairs, in the order a person reads them: page, element, components,
26
+ * browser, build. The Console and Agent tools show these.
27
+ */
28
+ declare function describeCommentContext(context: CommentContext | null): Array<{
29
+ label: string;
30
+ value: string;
31
+ }>;
32
+ //#endregion
33
+ //#region src/index.d.ts
34
+ type Codes<T extends CommentsErrorCode> = T;
35
+ /** The Comments runtime of an app: the `comments` export of `server/comments.ts`. */
36
+ interface Comments {
37
+ readonly options: DefineCommentsOptions$1;
38
+ /** Threads with their comments, newest activity first. */
39
+ list(options?: ListCommentThreadsOptions): Promise<Result<CommentThread[], Codes<"COMMENTS_NOT_INSTALLED">>>;
40
+ get(id: string): Promise<Result<CommentThread, Codes<"COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND">>>;
41
+ /** The thread that holds a comment, for a route that has only the comment id. */
42
+ getByComment(commentId: string): Promise<Result<CommentThread, Codes<"COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND">>>;
43
+ /** Thread `#number` of a scope. */
44
+ getByNumber(scope: string, number: number): Promise<Result<CommentThread, Codes<"COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND">>>;
45
+ /**
46
+ * Starts a thread with its first comment, numbered next in its scope. Runs `onComment`. A thread of the `"pages"`
47
+ * scope needs an `anchor`; other scopes keep their own anchor in `metadata`.
48
+ */
49
+ create(input: CreateCommentThreadInput): Promise<Result<CommentThread, Codes<"COMMENTS_NOT_INSTALLED" | "COMMENTS_INVALID_INPUT">>>;
50
+ /** Adds a comment to an open thread. Runs `onComment`. */
51
+ reply(threadId: string, input: ReplyInput, options?: ReplyOptions): Promise<Result<Comment, Codes<"COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND" | "COMMENTS_INVALID_INPUT" | "COMMENTS_RESOLVED">>>;
52
+ resolve(threadId: string, options: {
53
+ by: CommentAuthor;
54
+ }): Promise<Result<CommentThread, Codes<"COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND">>>;
55
+ reopen(threadId: string): Promise<Result<CommentThread, Codes<"COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND">>>;
56
+ /** Deletes a thread and all its comments. */
57
+ remove(threadId: string): Promise<Result<void, Codes<"COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND">>>;
58
+ /** Deletes one comment. Deleting the first comment deletes the thread. */
59
+ removeComment(commentId: string): Promise<Result<void, Codes<"COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND">>>;
60
+ /** Changes the text of a comment and sets `editedAt`. */
61
+ edit(commentId: string, input: EditCommentInput): Promise<Result<Comment, Codes<"COMMENTS_NOT_INSTALLED" | "COMMENTS_NOT_FOUND" | "COMMENTS_INVALID_INPUT">>>;
62
+ /** Deletes every thread of a scope, such as when app code deletes the document that the scope names. */
63
+ removeScope(scope: string): Promise<Result<{
64
+ removed: number;
65
+ }, Codes<"COMMENTS_NOT_INSTALLED">>>;
66
+ /**
67
+ * Whether the `authorize` policy allows an action. Without a policy, see `defaultPolicy()`. `scope` defaults to the
68
+ * thread's, else `"pages"`.
69
+ */
70
+ can(context: Omit<CommentsAuthorizeContext$1, "scope"> & {
71
+ scope?: string;
72
+ }): Promise<boolean>;
73
+ /**
74
+ * People that `@` suggests: the `people` option, or the authors of earlier comments in the scope, `"pages"` by
75
+ * default, so names from an app's own scopes never reach the overlay.
76
+ */
77
+ people(context: {
78
+ query: string;
79
+ user: CommentsAuthorizeContext$1["user"];
80
+ scope?: string;
81
+ }): Promise<Result<CommentMention[], Codes<"COMMENTS_NOT_INSTALLED">>>;
82
+ /**
83
+ * With `forge`: brings the thread's pull request comments in line with the thread now, and posts what failed
84
+ * before. Every change starts this on its own; `flush()` waits for it.
85
+ */
86
+ sync(threadId: string): Promise<void>;
87
+ /** Waits for the pull request syncs that earlier changes started. On Cloudflare, pass it to `waitUntil`. */
88
+ flush(): Promise<void>;
89
+ }
90
+ /**
91
+ * The policy without `authorize`, for every action: a person signed in with GitHub needs push access to the repository
92
+ * of the build; any other signed-in user may; anonymous people may only on the development server, as guests.
93
+ * `development` comes from Vite's command in the generated Nitro plugin, and defaults to false.
94
+ */
95
+ declare function defaultPolicy(user: CommentsUser | null, development?: boolean): boolean;
96
+ /**
97
+ * Defines Comments for the app. A default export from `server/comments.ts` selects numbered, authorized Operations.
98
+ * A named `comments` export selects the live-site API, overlay, and presence rooms.
99
+ */
100
+ declare function defineComments(input?: DefineCommentsOptions): Comments & CommentsDefinition;
101
+ declare function defineComments<T>(input: T & (T extends DefineCommentsOptions$1 | CommentsDefinition ? unknown : never)): Comments & CommentsDefinition;
102
+ /**
103
+ * Connects a Comments definition to its Database. The generated Nitro plugin calls it when the server starts; call it
104
+ * yourself only in tests or outside ViteHub. Only the Vite dev server enables `development`; it defaults to false.
105
+ */
106
+ declare function installComments(comments: Comments, runtime: {
107
+ database: CommentsDatabase;
108
+ development?: boolean;
109
+ }): void;
110
+ //#endregion
111
+ export { describeCommentContext as a, DefineCommentsOptions as c, installComments as i, defaultPolicy as n, CommentsDatabase as o, defineComments as r, CommentsAuthorizeContext as s, Comments as t };