@jchat/addon-sdk 1.0.0-alpha.2 → 1.0.0-alpha.20

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.
@@ -1,19 +0,0 @@
1
- import type { AddonManifest } from "./contracts";
2
- export type AddonDiagnosticStatus = "pass" | "warning" | "error";
3
- export interface AddonPackageDiagnostic {
4
- id: string;
5
- label: string;
6
- status: AddonDiagnosticStatus;
7
- message: string;
8
- }
9
- export interface AddonPackageDiagnosticOptions {
10
- buildDir: string;
11
- manifest: AddonManifest;
12
- jchatVersion: string;
13
- addonSdkVersion: string;
14
- productionPackage?: boolean;
15
- maxBytes?: number;
16
- }
17
- export declare function createCompatibleMajorRange(version: string): string;
18
- export declare function diagnoseAddonPackage(options: AddonPackageDiagnosticOptions): AddonPackageDiagnostic[];
19
- export declare function hasAddonDiagnosticErrors(diagnostics: readonly AddonPackageDiagnostic[]): boolean;
@@ -1,106 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import * as fs from "node:fs"
3
- import * as os from "node:os"
4
- import * as path from "node:path"
5
- import {
6
- createCompatibleMajorRange,
7
- diagnoseAddonPackage,
8
- hasAddonDiagnosticErrors
9
- } from "./diagnostics"
10
-
11
- describe("addon package diagnostics", () => {
12
- test("accepts compatible builds with every declared file", () => {
13
- const buildDir = fs.mkdtempSync(path.join(os.tmpdir(), "jchat-addon-diagnostics-"))
14
- fs.writeFileSync(path.join(buildDir, "ui.js"), "export default function Addon() {}")
15
- fs.writeFileSync(path.join(buildDir, "api.js"), "export default () => {}")
16
-
17
- try {
18
- const diagnostics = diagnoseAddonPackage({
19
- buildDir,
20
- manifest: {
21
- id: "sample-addon",
22
- name: "Sample addon",
23
- version: "1.0.0",
24
- compatibility: {
25
- jchat: ">=1.0.0-alpha.0 <2.0.0",
26
- addonSdk: "^1.0.0"
27
- },
28
- frontend: { bundle: "./ui.js", mountPoints: ["chat-toolbar"] },
29
- server: { bundle: "./api.js" }
30
- },
31
- jchatVersion: "1.0.0-alpha.0",
32
- addonSdkVersion: "1.0.0"
33
- })
34
-
35
- expect(hasAddonDiagnosticErrors(diagnostics)).toBe(false)
36
- expect(diagnostics.find(({ id }) => id === "jchat")?.status).toBe("pass")
37
- expect(diagnostics.find(({ id }) => id === "server-bundle")?.status).toBe("pass")
38
- } finally {
39
- fs.rmSync(buildDir, { recursive: true })
40
- }
41
- })
42
-
43
- test("reports incompatible versions, missing files, and unsafe references", () => {
44
- const buildDir = fs.mkdtempSync(path.join(os.tmpdir(), "jchat-addon-diagnostics-"))
45
- try {
46
- const diagnostics = diagnoseAddonPackage({
47
- buildDir,
48
- manifest: {
49
- id: "sample-addon",
50
- name: "Sample addon",
51
- version: "1.0.0",
52
- compatibility: { jchat: "^2.0.0", addonSdk: "^1.0.0" },
53
- frontend: { bundle: "../ui.js", mountPoints: [] },
54
- server: { bundle: "./missing-api.js" }
55
- },
56
- jchatVersion: "1.0.0-alpha.0",
57
- addonSdkVersion: "1.0.0"
58
- })
59
-
60
- expect(hasAddonDiagnosticErrors(diagnostics)).toBe(true)
61
- expect(diagnostics.find(({ id }) => id === "jchat")?.status).toBe("error")
62
- expect(diagnostics.find(({ id }) => id === "frontend-bundle")?.status).toBe("error")
63
- expect(diagnostics.find(({ id }) => id === "server-bundle")?.status).toBe("error")
64
- } finally {
65
- fs.rmSync(buildDir, { recursive: true })
66
- }
67
- })
68
-
69
- test("creates a prerelease-compatible range for the current major", () => {
70
- expect(createCompatibleMajorRange("1.0.0-alpha.0")).toBe(">=1.0.0-alpha.0 <2.0.0")
71
- })
72
-
73
- test("rejects malformed versions using Bun semver validation", () => {
74
- expect(() => createCompatibleMajorRange("1.invalid.0")).toThrow(
75
- "Invalid semantic version: 1.invalid.0"
76
- )
77
- })
78
-
79
- test("measures the distributable archive for production package size", () => {
80
- const buildDir = fs.mkdtempSync(path.join(os.tmpdir(), "jchat-addon-diagnostics-"))
81
- fs.writeFileSync(path.join(buildDir, "ui.js"), "unpacked content is intentionally larger")
82
- fs.writeFileSync(path.join(buildDir, "sample-addon-1.0.0.zip"), "zip")
83
-
84
- try {
85
- const diagnostics = diagnoseAddonPackage({
86
- buildDir,
87
- manifest: {
88
- id: "sample-addon",
89
- name: "Sample addon",
90
- version: "1.0.0",
91
- compatibility: { jchat: "^1.0.0", addonSdk: "^1.0.0" },
92
- frontend: { bundle: "./ui.js", mountPoints: ["chat-toolbar"] }
93
- },
94
- jchatVersion: "1.0.0",
95
- addonSdkVersion: "1.0.0",
96
- productionPackage: true,
97
- maxBytes: 3
98
- })
99
-
100
- expect(diagnostics.find(({ id }) => id === "package-size")?.status).toBe("pass")
101
- expect(diagnostics.find(({ id }) => id === "production-archive")?.status).toBe("pass")
102
- } finally {
103
- fs.rmSync(buildDir, { recursive: true })
104
- }
105
- })
106
- })
@@ -1,182 +0,0 @@
1
- import * as fs from "node:fs"
2
- import * as path from "node:path"
3
- import type { AddonManifest } from "./contracts"
4
-
5
- export type AddonDiagnosticStatus = "pass" | "warning" | "error"
6
-
7
- export interface AddonPackageDiagnostic {
8
- id: string
9
- label: string
10
- status: AddonDiagnosticStatus
11
- message: string
12
- }
13
-
14
- export interface AddonPackageDiagnosticOptions {
15
- buildDir: string
16
- manifest: AddonManifest
17
- jchatVersion: string
18
- addonSdkVersion: string
19
- productionPackage?: boolean
20
- maxBytes?: number
21
- }
22
-
23
- export function createCompatibleMajorRange(version: string): string {
24
- try {
25
- Bun.semver.order(version, version)
26
- } catch {
27
- throw new Error(`Invalid semantic version: ${version}`)
28
- }
29
-
30
- const majorComponent = /^(?:v|=)?(\d+)\./.exec(version)?.[1]
31
- const major = majorComponent ? Number(majorComponent) : Number.NaN
32
- if (!Number.isSafeInteger(major)) throw new Error(`Invalid semantic version: ${version}`)
33
-
34
- return `>=${version} <${major + 1}.0.0`
35
- }
36
-
37
- export function diagnoseAddonPackage(
38
- options: AddonPackageDiagnosticOptions
39
- ): AddonPackageDiagnostic[] {
40
- const { buildDir, manifest } = options
41
- const diagnostics: AddonPackageDiagnostic[] = []
42
- diagnostics.push(
43
- compatibilityDiagnostic(
44
- "jchat",
45
- "JChat compatibility",
46
- options.jchatVersion,
47
- manifest.compatibility?.jchat
48
- ),
49
- compatibilityDiagnostic(
50
- "addon-sdk",
51
- "Addon SDK compatibility",
52
- options.addonSdkVersion,
53
- manifest.compatibility?.addonSdk
54
- )
55
- )
56
-
57
- const references = [
58
- ["frontend-bundle", "Frontend bundle", manifest.frontend?.bundle],
59
- ["server-bundle", "Server bundle", manifest.server?.bundle],
60
- ...(manifest.server?.migrations ?? []).map(
61
- (file) => [`migration:${file}`, `Migration ${file}`, file] as const
62
- ),
63
- ...(manifest.server?.seeds ?? []).map((file) => [`seed:${file}`, `Seed ${file}`, file] as const)
64
- ] as const
65
-
66
- for (const [id, label, reference] of references) {
67
- if (!reference) continue
68
- const file = resolveBuildFile(buildDir, reference)
69
- diagnostics.push({
70
- id,
71
- label,
72
- status: file && fs.existsSync(file) && fs.statSync(file).isFile() ? "pass" : "error",
73
- message:
74
- file && fs.existsSync(file) && fs.statSync(file).isFile()
75
- ? reference
76
- : `Missing or unsafe build file: ${reference}`
77
- })
78
- }
79
-
80
- const files = listRegularFiles(buildDir)
81
- const productionArchive = path.join(buildDir, `${manifest.id}-${manifest.version}.zip`)
82
- const hasProductionArchive =
83
- fs.existsSync(productionArchive) && fs.statSync(productionArchive).isFile()
84
- const totalBytes =
85
- options.productionPackage && hasProductionArchive
86
- ? fs.statSync(productionArchive).size
87
- : files
88
- .filter((file) => file !== productionArchive)
89
- .reduce((total, file) => total + fs.statSync(file).size, 0)
90
- const maxBytes = options.maxBytes ?? 25 * 1024 * 1024
91
- diagnostics.push({
92
- id: "package-size",
93
- label: "Package size",
94
- status: totalBytes <= maxBytes ? "pass" : "error",
95
- message: `${totalBytes} of ${maxBytes} bytes`
96
- })
97
-
98
- const sourceMaps = files.filter((file) => file.endsWith(".map"))
99
- diagnostics.push({
100
- id: "source-maps",
101
- label: "Source maps",
102
- status: options.productionPackage && sourceMaps.length ? "warning" : "pass",
103
- message: sourceMaps.length ? `${sourceMaps.length} source map(s) present` : "No source maps"
104
- })
105
-
106
- const hasDatabaseFiles = Boolean(
107
- manifest.server?.migrations?.length || manifest.server?.seeds?.length
108
- )
109
- diagnostics.push({
110
- id: "database-signature",
111
- label: "Database file signature",
112
- status:
113
- hasDatabaseFiles && options.productionPackage && !manifest.signature?.value
114
- ? "error"
115
- : hasDatabaseFiles && !manifest.signature?.value
116
- ? "warning"
117
- : "pass",
118
- message:
119
- hasDatabaseFiles && !manifest.signature?.value
120
- ? options.productionPackage
121
- ? "Production database files require a publisher signature"
122
- : "Unsigned database files are allowed only in the developer sandbox"
123
- : hasDatabaseFiles
124
- ? "Publisher signature present"
125
- : "No database files declared"
126
- })
127
-
128
- if (options.productionPackage) {
129
- diagnostics.push({
130
- id: "production-archive",
131
- label: "Production archive",
132
- status: hasProductionArchive ? "pass" : "error",
133
- message: hasProductionArchive
134
- ? path.basename(productionArchive)
135
- : "Production archive is missing"
136
- })
137
- }
138
-
139
- return diagnostics
140
- }
141
-
142
- export function hasAddonDiagnosticErrors(diagnostics: readonly AddonPackageDiagnostic[]): boolean {
143
- return diagnostics.some(({ status }) => status === "error")
144
- }
145
-
146
- function compatibilityDiagnostic(
147
- id: string,
148
- label: string,
149
- version: string,
150
- range: string | undefined
151
- ): AddonPackageDiagnostic {
152
- const compatible = Boolean(range && Bun.semver.satisfies(version, range))
153
- return {
154
- id,
155
- label,
156
- status: compatible ? "pass" : "error",
157
- message: range
158
- ? `${version} ${compatible ? "satisfies" : "does not satisfy"} ${range}`
159
- : "Compatibility range is missing"
160
- }
161
- }
162
-
163
- function resolveBuildFile(buildDir: string, reference: string): string | null {
164
- if (
165
- path.isAbsolute(reference) ||
166
- reference.includes("\\") ||
167
- reference.split("/").includes("..")
168
- ) {
169
- return null
170
- }
171
- const target = path.resolve(buildDir, ...reference.replace(/^\.\//, "").split("/"))
172
- const relative = path.relative(path.resolve(buildDir), target)
173
- return relative && !relative.startsWith("..") && !path.isAbsolute(relative) ? target : null
174
- }
175
-
176
- function listRegularFiles(root: string): string[] {
177
- if (!fs.existsSync(root)) return []
178
- return fs
179
- .readdirSync(root, { recursive: true, withFileTypes: true })
180
- .filter((entry) => entry.isFile())
181
- .map((entry) => path.join(entry.parentPath, entry.name))
182
- }
package/src/index.d.ts DELETED
@@ -1,249 +0,0 @@
1
- import type { IconPack } from "@jchat/icon";
2
- import type { Elysia } from "elysia";
3
- import type { Kysely } from "kysely";
4
- import type { AddonManifest, AddonPermission, MountPoint } from "./contracts";
5
- export { MOUNT_POINTS, type AddonManifest, type AddonPermission, type AddonPermissionDefinition, type ConfigSchemaField, type MountPoint } from "./contracts";
6
- export type AddonJsonBody = Record<string, unknown> | unknown[] | null;
7
- /**
8
- * @jchat/addon-sdk
9
- *
10
- * Lightweight SDK for Jchat addon developers. Provides TypeScript types for addon props, manifest
11
- * schema, and host API access. This package is always EXTERNALISED from addon bundles — the host
12
- * app provides the runtime implementation.
13
- */
14
- /** Minimal user profile accessible to addon backends. */
15
- export interface AddonUser {
16
- /** Unique user identifier */
17
- id: string;
18
- /** Display name */
19
- name: string;
20
- /** Full display name */
21
- displayName: string;
22
- /** Full URL to the user's avatar image */
23
- avatar: string;
24
- /** User's gender identifier */
25
- gender: string;
26
- }
27
- export interface AddonRequestUser {
28
- id?: string;
29
- permissions?: string[];
30
- siteId?: string;
31
- }
32
- /**
33
- * Typed, schema-scoped database facade for an addon. The host deliberately omits raw execution,
34
- * schema switching, dialect/connection access, and lifecycle methods.
35
- */
36
- export type AddonDatabase<TDatabase = Record<string, Record<string, unknown>>> = Pick<Kysely<TDatabase>, "deleteFrom" | "fn" | "insertInto" | "selectFrom" | "transaction" | "updateTable">;
37
- /**
38
- * Context provided to an addon's server-side factory. Parameterize it with the addon's table
39
- * interface: `AddonServerContext<MyAddonDatabase>`.
40
- */
41
- export interface AddonServerContext<TDatabase = Record<string, Record<string, unknown>>> {
42
- /**
43
- * Retrieve the encrypted settings for this addon for a specific site. Internal secrets are
44
- * automatically decrypted using the host's master key.
45
- */
46
- getConfig: (siteId: string) => Promise<Record<string, unknown>>;
47
- /** Fetch a specific user's public profile */
48
- getUser: (userId: string) => Promise<AddonUser | null>;
49
- /** Efficiently fetch multiple user profiles in a single query. Returns a Map keyed by user ID. */
50
- getUsers: (userIds: string[]) => Promise<Map<string, AddonUser>>;
51
- /**
52
- * Check whether the request user holds a given permission. Provides autocomplete for core Jchat
53
- * permissions while also accepting any custom addon permission string.
54
- *
55
- * @param user - The user object from the request context
56
- * @param permission - The permission to check, e.g., 'message.send' or 'addon.stories.view'
57
- */
58
- hasPermission: (user: AddonRequestUser | null | undefined, permission: AddonPermission) => boolean;
59
- /**
60
- * A Kysely database instance scoped entirely to your addon's tables. You cannot access core Jchat
61
- * tables (Users, Rooms, etc.) through this instance.
62
- */
63
- db: AddonDatabase<TDatabase>;
64
- }
65
- /**
66
- * The entry point for your addon's server bundle. You should default-export a function matching
67
- * this signature.
68
- *
69
- * @example
70
- * ;```ts
71
- * import { type AddonServerFactory } from '@jchat/addon-sdk'
72
- *
73
- * const factory: AddonServerFactory = ({ db, hasPermission }, app) => {
74
- * return app.get('/trending', async () => { ... })
75
- * }
76
- * export default factory
77
- * ```
78
- */
79
- export type AddonServerFactory<TDatabase = Record<string, Record<string, unknown>>> = (ctx: AddonServerContext<TDatabase>, app: Elysia) => Elysia;
80
- /** Props passed to your addon's root React component by the Jchat host. */
81
- export interface AddonProps {
82
- /** The mount point where this addon instance is rendered (e.g., 'chat-sidebar') */
83
- mountPoint: MountPoint;
84
- /** Information about the currently logged-in user (if any) */
85
- user?: {
86
- id: string;
87
- name: string;
88
- displayName?: string;
89
- avatar?: string;
90
- gender?: string;
91
- };
92
- /** The ID of the room the user is currently viewing (if applicable) */
93
- roomId?: string;
94
- /** The ID of the active Jchat site */
95
- siteId?: string;
96
- }
97
- export interface AddonApi {
98
- get: <TResponse = unknown>(path: string) => Promise<TResponse>;
99
- post: <TResponse = unknown>(path: string, body?: AddonJsonBody) => Promise<TResponse>;
100
- put: <TResponse = unknown>(path: string, body?: AddonJsonBody) => Promise<TResponse>;
101
- delete: <TResponse = unknown>(path: string) => Promise<TResponse>;
102
- }
103
- export type AddonEventListener = (data: unknown) => void;
104
- /** A font option provided by the JChat host. */
105
- export interface AddonFont {
106
- /** Display label shown to users (e.g. 'Modern', 'Elegant') */
107
- label: string;
108
- /** Font identifier stored in the database (e.g. 'poppins', 'lato') */
109
- value: string;
110
- /** CSS font-family string ready for use in inline styles */
111
- family: string;
112
- /** Google Fonts name for loading the font via a <link> tag */
113
- googleName: string;
114
- /** Relative size multiplier — apply this to base font sizes to match the host's rendering */
115
- scale: number;
116
- }
117
- /**
118
- * The bridge between your addon and the Jchat host application. Use the `useAddonSDK()` hook to
119
- * access this interface in your components.
120
- */
121
- export interface AddonSDK {
122
- /**
123
- * Make authenticated API calls to your addon's backend or core Jchat endpoints. All calls
124
- * automatically include the current user's sessionId and site validation headers.
125
- */
126
- api: AddonApi;
127
- /**
128
- * Display a temporary notification toast in the host UI.
129
- *
130
- * @param message - The text content to display
131
- * @param variant - Visual style: 'default' (blue), 'success' (green), or 'error' (red)
132
- */
133
- toast: (message: string, variant?: "default" | "success" | "error") => void;
134
- /**
135
- * Navigate the host application to a different internal route.
136
- *
137
- * @param path - The target location, e.g., '/settings' or '/addons/store'
138
- */
139
- navigate: (path: string) => void;
140
- /**
141
- * Interaction utilities for the active Slate message editor. Only available if your addon is
142
- * mounted near the chat input.
143
- */
144
- editor: {
145
- /**
146
- * Trigger a specialized editor command defined by the host.
147
- *
148
- * @example
149
- * sdk.editor.dispatchCommand("INSERT_YOUTUBE_COMMAND", "dQw4w9WgXcQ")
150
- */
151
- dispatchCommand: (command: string, payload?: unknown) => void;
152
- /**
153
- * Insert a low-level Slate node directly at the user's cursor position.
154
- *
155
- * @param node - A valid Slate Descendant or Fragment object
156
- */
157
- insertNode: (node: unknown) => void;
158
- /**
159
- * Upload and attach a file to the current message without inserting it inline. Users will see
160
- * the file in the attachment bar below the editor.
161
- */
162
- addAttachment: (attachment: {
163
- url: string;
164
- name: string;
165
- type: string;
166
- }) => void;
167
- /** Force the browser focus back to the editor input */
168
- focus: () => void;
169
- };
170
- /** Event Bus for reacting to real-time application state changes. */
171
- events: {
172
- /**
173
- * Register a persistent listener for a specific event.
174
- *
175
- * @param event - Event name, e.g., 'room.message', 'user.typing'
176
- */
177
- on: (event: string, callback: AddonEventListener) => void;
178
- /** Unregister a previously attached listener */
179
- off: (event: string, callback: AddonEventListener) => void;
180
- };
181
- /**
182
- * The list of fonts available in this JChat deployment, as configured by the site administrator.
183
- * Use this to build a font picker or apply a matching font family in your addon UI.
184
- */
185
- supportedFonts?: AddonFont[];
186
- }
187
- /**
188
- * Seed data for your addon's tables, provided inside the addon's isolated schema.
189
- *
190
- * These documents are inserted into the addon's dedicated schema on installation and can be used to
191
- * provide default values, references, or supporting data. The host guarantees that these documents
192
- * do not conflict with core schemas or other addons.
193
- */
194
- export interface AddonSeedDocument {
195
- /** Addon-owned table name. Core prefixes the addon's isolated PostgreSQL schema. */
196
- table: string;
197
- /** Behavior when a row conflicts with an existing unique or primary key. */
198
- conflict?: "error" | "ignore" | "update";
199
- /** Required for update behavior; identifies the unique key used by ON CONFLICT. */
200
- conflictColumns?: string[];
201
- /** JSON-compatible rows inserted using parameterized values. */
202
- rows: Record<string, unknown>[];
203
- }
204
- /** Define a manifest with full validation-friendly typing while preserving literal values. */
205
- export declare function defineAddonManifest<const TManifest extends AddonManifest>(manifest: TManifest): TManifest;
206
- /** Define a typed server factory without widening its addon database interface. */
207
- export declare function defineAddonServer<TDatabase = Record<string, Record<string, unknown>>>(factory: AddonServerFactory<TDatabase>): AddonServerFactory<TDatabase>;
208
- /**
209
- * Access the host application's SDK. Provides authenticated API access, toast notifications, and
210
- * navigation.
211
- *
212
- * This function is a shell; the real implementation is provided by the Jchat host environment at
213
- * runtime.
214
- *
215
- * @example
216
- * ;```tsx
217
- * import { useAddonSDK } from "@jchat/addon-sdk"
218
- *
219
- * export default function MyAddon({ mountPoint }: AddonProps) {
220
- * const sdk = useAddonSDK()
221
- *
222
- * const handleClick = async () => {
223
- * const data = await sdk.api.get("/trending")
224
- * sdk.toast("Fetched trending posts!", "success")
225
- * }
226
- * }
227
- * ```
228
- */
229
- export declare function useAddonSDK(): AddonSDK;
230
- /**
231
- * Access the host application's active icon pack. Returns the icon set matching the site's
232
- * configured icon pack preference.
233
- *
234
- * This function is a shell; the real implementation is provided by the Jchat host environment at
235
- * runtime.
236
- *
237
- * @example
238
- * ;```tsx
239
- * import { useIcons } from "@jchat/addon-sdk"
240
- *
241
- * export default function MyAddon() {
242
- * const { Icons } = useIcons()
243
- * return <Icons.Send className="size-5" />
244
- * }
245
- * ```
246
- */
247
- export declare function useIcons(): {
248
- Icons: IconPack;
249
- };
package/src/index.test.ts DELETED
@@ -1,35 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { Elysia } from "elysia"
3
- import {
4
- defineAddonManifest,
5
- defineAddonServer,
6
- MOUNT_POINTS,
7
- type AddonManifest,
8
- type AddonServerContext
9
- } from "./index"
10
-
11
- describe("addon SDK definition helpers", () => {
12
- test("defineAddonManifest preserves the manifest", () => {
13
- const manifest = {
14
- id: "example-addon",
15
- name: "Example addon",
16
- version: "1.0.0",
17
- description: "An example addon",
18
- author: "Jchat",
19
- compatibility: { jchat: "^1.0.0", addonSdk: "^1.0.0" },
20
- permissions: ["message.read"]
21
- } as const satisfies AddonManifest
22
-
23
- expect(defineAddonManifest(manifest)).toBe(manifest)
24
- })
25
-
26
- test("keeps manifest mount points available from the public entry", () => {
27
- expect(MOUNT_POINTS.CHAT_HEADER).toBe("chat-header")
28
- })
29
-
30
- test("defineAddonServer preserves the server factory", () => {
31
- const factory = (_context: AddonServerContext) => new Elysia()
32
-
33
- expect(defineAddonServer(factory)).toBe(factory)
34
- })
35
- })