@vite-hub/realtime 0.0.3

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.
@@ -0,0 +1,42 @@
1
+ import { WorkspaceSnapshot } from "@vite-hub/workspace";
2
+
3
+ //#region src/types.d.ts
4
+ interface RealtimeDefinition {
5
+ auth?: boolean;
6
+ document: {
7
+ workspace: string;
8
+ };
9
+ history?: {
10
+ checkpoint: true | {
11
+ message?: string;
12
+ };
13
+ };
14
+ }
15
+ interface RealtimeCheckpoint {
16
+ content: string;
17
+ snapshot: WorkspaceSnapshot;
18
+ }
19
+ interface RealtimeModuleOptions {
20
+ authority?: "auto" | "cloudflare" | "memory";
21
+ projectRoot?: string;
22
+ }
23
+ interface RealtimePerson {
24
+ clientId: number;
25
+ color: string;
26
+ id: string;
27
+ image?: string;
28
+ name: string;
29
+ }
30
+ type RealtimeWorkspaceChange = {
31
+ operation: "create" | "delete" | "update";
32
+ path: string;
33
+ } | {
34
+ operation: "move";
35
+ from: string;
36
+ to: string;
37
+ };
38
+ type RealtimeRegistry = Record<string, () => Promise<{
39
+ default: RealtimeDefinition;
40
+ }>>;
41
+ //#endregion
42
+ export { RealtimeRegistry as a, RealtimePerson as i, RealtimeDefinition as n, RealtimeWorkspaceChange as o, RealtimeModuleOptions as r, RealtimeCheckpoint as t };
package/dist/vite.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { r as RealtimeModuleOptions } from "./types-BSDtKw5d.js";
2
+ import { Plugin } from "vite";
3
+
4
+ //#region src/vite.d.ts
5
+ interface RealtimeVitePluginOptions extends RealtimeModuleOptions {
6
+ importBase?: string;
7
+ }
8
+ declare function hubRealtime(options?: RealtimeVitePluginOptions): Plugin;
9
+ //#endregion
10
+ export { RealtimeVitePluginOptions, hubRealtime };
package/dist/vite.js ADDED
@@ -0,0 +1,286 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, parse, relative, resolve } from "node:path";
3
+ import { existsSync, readdirSync, statSync } from "node:fs";
4
+ import { relative as relative$1, resolve as resolve$1 } from "pathe";
5
+ import { tmpdir } from "node:os";
6
+ //#region ../internal/src/definition-catalog.ts
7
+ const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
8
+ const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
9
+ const ignoredDirs = new Set([
10
+ "node_modules",
11
+ "dist",
12
+ ".output",
13
+ ".nuxt",
14
+ ".vercel",
15
+ ".git",
16
+ ".vitehub"
17
+ ]);
18
+ function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
19
+ return {
20
+ ...options,
21
+ kind: "directory",
22
+ scanDirs,
23
+ source,
24
+ subdir
25
+ };
26
+ }
27
+ function readDirEntries(root) {
28
+ try {
29
+ return readdirSync(root, { withFileTypes: true });
30
+ } catch (error) {
31
+ if (error.code === "ENOENT") return [];
32
+ throw error;
33
+ }
34
+ }
35
+ function isGitRepositoryDirectory(directory) {
36
+ return existsSync(resolve$1(directory, ".git"));
37
+ }
38
+ function listMatchingFiles(root, predicate, options = {}) {
39
+ const files = [];
40
+ for (const entry of readDirEntries(root)) {
41
+ const absolute = resolve$1(root, entry.name);
42
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
43
+ if (isGitRepositoryDirectory(absolute)) continue;
44
+ if (entry.name.startsWith(".")) continue;
45
+ if (ignoredDirs.has(entry.name)) continue;
46
+ files.push(...listMatchingFiles(absolute, predicate, options));
47
+ continue;
48
+ }
49
+ if (entry.name.startsWith(".") && !options.includeHidden) continue;
50
+ if (entry.isFile() && predicate(entry.name)) files.push(absolute);
51
+ }
52
+ return files.sort();
53
+ }
54
+ function listSourceFiles(root, options = {}) {
55
+ return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
56
+ }
57
+ function normalizePathDefinitionName(rootDir, file) {
58
+ return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
59
+ }
60
+ function sortDefinitions(definitions) {
61
+ return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
62
+ }
63
+ function registerDefinition(definitions, definition, sourceLabel) {
64
+ const existing = definitions.get(definition.name);
65
+ if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
66
+ definitions.set(definition.name, definition);
67
+ }
68
+ function mergeDefinitions(feature, ...sources) {
69
+ const definitions = /* @__PURE__ */ new Map();
70
+ for (const source of sources) {
71
+ if (!source) continue;
72
+ for (const definition of source) {
73
+ const existing = definitions.get(definition.name);
74
+ if (existing && existing.handler !== definition.handler) throw new Error(`Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})`);
75
+ if (!existing) definitions.set(definition.name, definition);
76
+ }
77
+ }
78
+ return sortDefinitions(definitions);
79
+ }
80
+ function createDefinition(source, file, name) {
81
+ if (source.createDefinition) return source.createDefinition({
82
+ file,
83
+ name
84
+ });
85
+ return {
86
+ handler: file,
87
+ name,
88
+ source: source.source
89
+ };
90
+ }
91
+ function scanSuffixDefinitions(feature, source) {
92
+ const definitions = /* @__PURE__ */ new Map();
93
+ for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
94
+ const name = source.normalizeName(root, file);
95
+ if (!name) continue;
96
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
97
+ }
98
+ return sortDefinitions(definitions);
99
+ }
100
+ function scanDirectoryDefinitions(feature, source) {
101
+ const definitions = /* @__PURE__ */ new Map();
102
+ for (const scanDir of source.scanDirs) {
103
+ const directory = resolve$1(scanDir, source.subdir);
104
+ for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
105
+ const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
106
+ if (!name) continue;
107
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
108
+ }
109
+ }
110
+ return sortDefinitions(definitions);
111
+ }
112
+ function discoverDefinitions(feature, sources) {
113
+ return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
114
+ }
115
+ function createImportExpression(registryFile, file) {
116
+ const importPath = relative$1(resolve$1(registryFile, ".."), file);
117
+ return `import(${JSON.stringify(importPath.startsWith(".") ? importPath : `./${importPath}`)})`;
118
+ }
119
+ function createRuntimeRegistryContents(registryFile, definitions) {
120
+ return [
121
+ "",
122
+ "const registry = {",
123
+ ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: async () => ${createImportExpression(registryFile, definition.handler)},`),
124
+ "}",
125
+ "",
126
+ "export default registry",
127
+ ""
128
+ ].join("\n");
129
+ }
130
+ function deploymentPresetFromNitro(value) {
131
+ const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
132
+ if (!normalized) return;
133
+ if (normalized.startsWith("cloudflare")) return "cloudflare";
134
+ if (normalized.startsWith("deno")) return "deno";
135
+ if (normalized.startsWith("netlify")) return "netlify";
136
+ if (normalized === "node" || normalized.startsWith("node-")) return "node";
137
+ if (normalized.startsWith("vercel")) return "vercel";
138
+ }
139
+ //#endregion
140
+ //#region ../internal/src/build/vite.ts
141
+ const projectRootDirectoryMarkers = [
142
+ ["server", "agents"],
143
+ ["server", "channels"],
144
+ ["server", "browsers"],
145
+ ["server", "emails"],
146
+ ["server", "schedules"],
147
+ ["server", "workspaces"]
148
+ ];
149
+ const projectRootFileMarkers = [["package.json"]];
150
+ const VITEHUB_SERVER_DIRS = "__vitehubServerDirs";
151
+ function resolveViteHubProjectRoot(root, options = {}) {
152
+ const resolvedRoot = resolve(root);
153
+ const temporaryRoot = resolve(tmpdir());
154
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
155
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
156
+ if (basename(resolvedRoot) === "app") {
157
+ const parent = dirname(resolvedRoot);
158
+ if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
159
+ }
160
+ let current = resolvedRoot;
161
+ while (true) {
162
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
163
+ if (hasProjectRootMarker(current)) return current;
164
+ const parent = dirname(current);
165
+ if (parent === current) return resolvedRoot;
166
+ current = parent;
167
+ }
168
+ }
169
+ function hasProjectRootDirectoryMarker(root) {
170
+ for (const marker of projectRootDirectoryMarkers) try {
171
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
172
+ } catch (error) {
173
+ if (error.code !== "ENOENT") throw error;
174
+ }
175
+ return false;
176
+ }
177
+ function hasProjectRootMarker(root) {
178
+ if (hasProjectRootDirectoryMarker(root)) return true;
179
+ for (const marker of projectRootFileMarkers) try {
180
+ if (statSync(resolve(root, ...marker)).isFile()) return true;
181
+ } catch (error) {
182
+ if (error.code !== "ENOENT") throw error;
183
+ }
184
+ return false;
185
+ }
186
+ //#endregion
187
+ //#region ../internal/src/hosting.ts
188
+ function getHostingProvider(hosting) {
189
+ const preset = deploymentPresetFromNitro(hosting);
190
+ if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
191
+ }
192
+ //#endregion
193
+ //#region src/discovery.ts
194
+ function discoverRealtimeDefinitions(rootDir, serverDirs) {
195
+ return discoverDefinitions("realtime", [createDirectoryDefinitionSource("server-realtime", serverDirs ?? [resolve(rootDir, "server")], "realtime", {
196
+ createDefinition: ({ file, name }) => ({
197
+ handler: file,
198
+ name,
199
+ source: "server-realtime"
200
+ }),
201
+ normalizeName: normalizePathDefinitionName
202
+ })]);
203
+ }
204
+ //#endregion
205
+ //#region src/vite.ts
206
+ function record(value) {
207
+ return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
208
+ }
209
+ function configureCloudflareRealtime(nitro) {
210
+ nitro.preset = "cloudflare-durable";
211
+ const cloudflare = record(nitro.cloudflare);
212
+ const wrangler = record(cloudflare.wrangler);
213
+ const durableObjects = record(wrangler.durable_objects);
214
+ const bindings = Array.isArray(durableObjects.bindings) ? durableObjects.bindings : [];
215
+ if (!bindings.some((binding) => record(binding).name === "$DurableObject")) durableObjects.bindings = [...bindings, {
216
+ class_name: "$DurableObject",
217
+ name: "$DurableObject"
218
+ }];
219
+ const migrations = Array.isArray(wrangler.migrations) ? wrangler.migrations : [];
220
+ if (!migrations.some((migration) => record(migration).tag === "vitehub-realtime-v1")) wrangler.migrations = [...migrations, {
221
+ new_sqlite_classes: ["$DurableObject"],
222
+ tag: "vitehub-realtime-v1"
223
+ }];
224
+ wrangler.durable_objects = durableObjects;
225
+ cloudflare.wrangler = wrangler;
226
+ nitro.cloudflare = cloudflare;
227
+ }
228
+ function moduleSpecifier(from, to) {
229
+ const value = relative(dirname(from), to).replaceAll("\\", "/");
230
+ return value.startsWith(".") ? value : `./${value}`;
231
+ }
232
+ function applicationBaseURL(base) {
233
+ return base?.startsWith("/") && !base.startsWith("//") ? base : "/";
234
+ }
235
+ function hubRealtime(options = {}) {
236
+ const importBase = options.importBase ?? "@vite-hub/realtime";
237
+ return {
238
+ name: "@vite-hub/realtime/vite",
239
+ enforce: "pre",
240
+ async config(config, environment) {
241
+ const root = resolveViteHubProjectRoot(resolve(config.root || process.cwd()), options);
242
+ const serverDirs = config[VITEHUB_SERVER_DIRS];
243
+ const definitions = discoverRealtimeDefinitions(root, serverDirs);
244
+ if (definitions.length === 0) return;
245
+ config.resolve = {
246
+ ...config.resolve,
247
+ dedupe: [...new Set([...config.resolve?.dedupe || [], "yjs"])]
248
+ };
249
+ config.define = {
250
+ __VITEHUB_APP_BASE_URL__: JSON.stringify(applicationBaseURL(config.base)),
251
+ ...config.define
252
+ };
253
+ const directory = resolve(root, ".vitehub/nitro/realtime");
254
+ const registryFile = resolve(directory, "registry.mjs");
255
+ const handlerFile = resolve(directory, "handler.ts");
256
+ await mkdir(directory, { recursive: true });
257
+ await Promise.all([writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions)), writeFile(handlerFile, [
258
+ `import registry from ${JSON.stringify(moduleSpecifier(handlerFile, registryFile))}`,
259
+ `import { createRealtimeHandler } from ${JSON.stringify(`${importBase}/server`)}`,
260
+ "",
261
+ "export default createRealtimeHandler(registry)",
262
+ ""
263
+ ].join("\n"))]);
264
+ const nitro = { ...config.nitro || {} };
265
+ const configuredPreset = nitro.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING;
266
+ const deploymentPreset = deploymentPresetFromNitro(configuredPreset);
267
+ const provider = getHostingProvider(configuredPreset);
268
+ const authority = options.authority || "auto";
269
+ if (authority === "cloudflare" && deploymentPreset && deploymentPreset !== "cloudflare") throw new Error(`[vitehub] Realtime authority "cloudflare" conflicts with the ${deploymentPreset} deployment preset.`);
270
+ if (authority === "cloudflare" || authority === "auto" && provider === "cloudflare") configureCloudflareRealtime(nitro);
271
+ else if (environment?.command === "build" && authority === "auto") throw new Error("[vitehub] Realtime production builds require one room authority. Deploy to Cloudflare Durable Objects or explicitly set realtime.authority to \"memory\" for a single-process server.");
272
+ else if (authority === "memory" && deploymentPreset && deploymentPreset !== "node") throw new Error(`[vitehub] Realtime authority "memory" is single-process only and cannot use the ${deploymentPreset} deployment preset.`);
273
+ nitro.features = {
274
+ ...nitro.features,
275
+ websocket: true
276
+ };
277
+ nitro.handlers = [...nitro.handlers || [], {
278
+ handler: handlerFile,
279
+ route: "/api/_vitehub/realtime/**"
280
+ }];
281
+ config.nitro = nitro;
282
+ }
283
+ };
284
+ }
285
+ //#endregion
286
+ export { hubRealtime };