@kitcms/core 0.1.0 → 0.1.1

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,25 @@
1
+ import cloudflare from '@sveltejs/adapter-cloudflare';
2
+ import type { Adapter } from '@sveltejs/kit';
3
+ import type { PluginOption } from 'vite';
4
+ export declare const RPC_ENTRY_NAME = "kitcms-rpc";
5
+ export interface KitcmsViteOptions {
6
+ /** The RPC entry module (exports `KitcmsRPC`). Default `src/kitcms.rpc.ts`; `false` disables RPC. */
7
+ rpcEntry?: string | false;
8
+ /**
9
+ * Serve `KitcmsRPC` under `vite dev` through `@cloudflare/vite-plugin` (see the comment block at
10
+ * the top of this file). Default false. Requires the optional peer `@cloudflare/vite-plugin`.
11
+ */
12
+ devRpc?: boolean;
13
+ /** Wrangler config used to derive the dev RPC worker config. Default: wrangler's own lookup. */
14
+ wranglerConfig?: string;
15
+ /** Worker name of the dev RPC worker. Default `<wrangler name>-rpc` (see the header comment). */
16
+ devRpcName?: string;
17
+ }
18
+ export declare function kitcms(options?: KitcmsViteOptions): PluginOption[];
19
+ type CloudflareAdapterOptions = NonNullable<Parameters<typeof cloudflare>[0]>;
20
+ /**
21
+ * adapter-cloudflare + the RPC facade. When the app has no RPC entry, it behaves exactly like
22
+ * adapter-cloudflare.
23
+ */
24
+ export declare function kitcmsAdapter(options?: CloudflareAdapterOptions): Adapter;
25
+ export {};
@@ -0,0 +1,176 @@
1
+ /// <reference types="node" />
2
+ // @kitcms/core/vite: build-time pieces (Node only, never imported by runtime code). Decision 14:
3
+ // the SvelteKit Worker also exports the `KitcmsRPC` entrypoint.
4
+ //
5
+ // // vite.config.ts
6
+ // import { sveltekit } from '@sveltejs/kit/vite';
7
+ // import { kitcms, kitcmsAdapter } from '@kitcms/core/vite';
8
+ // export default defineConfig({
9
+ // plugins: [sveltekit({ adapter: kitcmsAdapter() }), kitcms()],
10
+ // });
11
+ //
12
+ // 1. `kitcms()` adds `src/kitcms.rpc.ts` as an extra input of SvelteKit's `ssr` environment, so it
13
+ // is compiled by Vite (aliases, `.svelte` imports) and SHARES CHUNKS with the app: config, the
14
+ // CMS instance and caches are one module graph.
15
+ // 2. `kitcmsAdapter()` wraps adapter-cloudflare: it moves the generated worker to
16
+ // `_sveltekit_worker.js`, writes a facade at wrangler `main` that re-exports both the default
17
+ // handler and the RPC entrypoint, and keeps the moved file out of the static assets.
18
+ // Verified in Phase 0 locally and in production (§2.2).
19
+ //
20
+ // OPT-IN dev-time RPC (`kitcms({ devRpc: true })`, off by default, Decision 16):
21
+ // Under `vite dev` SvelteKit SSR runs in Node with adapter-cloudflare's platform proxy, so the
22
+ // `KitcmsRPC` entrypoint is NOT served and a consumer Worker cannot call it. With `devRpc` the
23
+ // plugin adds `@cloudflare/vite-plugin` (`apply: 'serve'`, after `sveltekit()`) running a tiny
24
+ // generated worker (`.svelte-kit/kitcms/dev-rpc-worker.ts`, re-exporting `KitcmsRPC` from your RPC
25
+ // entry) in a second workerd (`rpc` Vite environment) with HMR. The dev wrangler config is your
26
+ // own wrangler config with only `main` (and `assets`) overridden, so D1/R2 bindings are shared.
27
+ // Costs: +0.3-0.5 s dev start, one more workerd, and the site and RPC have SEPARATE module state
28
+ // in dev. `@cloudflare/vite-plugin` is an optional peer dependency: install it yourself, pinned
29
+ // with the same `wrangler` version where possible.
30
+ // Consumer setup (verified): the dev RPC worker registers as `<wrangler name>-rpc` (override with
31
+ // `devRpcName`), NOT under the app's own name: the app's platform proxy registers the app name
32
+ // without the entrypoint and wins, so the consumer then fails with "does not export an entrypoint
33
+ // named KitcmsRPC". So in dev the consumer binds `{ service: "<name>-rpc", entrypoint: "KitcmsRPC" }`.
34
+ // Registry skew: the plugin's miniflare registers in `.../cloudflare/dev-registry/v5`, wrangler
35
+ // 4.162 reads `.../.wrangler/registry`. Until versions align, start BOTH processes with the same
36
+ // `CLOUDFLARE_DEV_REGISTRY_PATH=<dir> WRANGLER_REGISTRY_PATH=<dir>`.
37
+ import fs from 'node:fs';
38
+ import path from 'node:path';
39
+ import cloudflare from '@sveltejs/adapter-cloudflare';
40
+ export const RPC_ENTRY_NAME = 'kitcms-rpc';
41
+ const DEFAULT_RPC_ENTRY = 'src/kitcms.rpc.ts';
42
+ export function kitcms(options = {}) {
43
+ const plugins = [rpcEntryPlugin(options)];
44
+ // Order matters: `@cloudflare/vite-plugin` must come AFTER `sveltekit()` (before it, its
45
+ // catch-all middleware swallows every route), and kitcms() is listed after sveltekit().
46
+ if (options.devRpc && options.rpcEntry !== false)
47
+ plugins.push(devRpcPlugins(options));
48
+ return plugins;
49
+ }
50
+ /** Loads `@cloudflare/vite-plugin` lazily (only when `devRpc` is on); Vite awaits promised plugins. */
51
+ async function devRpcPlugins(options) {
52
+ const entry = resolveEntry(options);
53
+ if (!entry) {
54
+ throw new Error(`kitcms: devRpc needs an RPC entry (${options.rpcEntry || DEFAULT_RPC_ENTRY})`);
55
+ }
56
+ let mod;
57
+ try {
58
+ mod = await import('@cloudflare/vite-plugin');
59
+ }
60
+ catch {
61
+ throw new Error('kitcms: `devRpc: true` needs the optional peer dependency `@cloudflare/vite-plugin` (pnpm add -D @cloudflare/vite-plugin).');
62
+ }
63
+ const dir = path.resolve('.svelte-kit', 'kitcms');
64
+ const worker = path.join(dir, 'dev-rpc-worker.ts');
65
+ fs.mkdirSync(dir, { recursive: true });
66
+ const rel = path.relative(dir, entry).split(path.sep).join('/');
67
+ const source = `// Generated by @kitcms/core (devRpc). Do not edit.\n` +
68
+ `export { KitcmsRPC } from ${JSON.stringify(rel)};\n` +
69
+ `export default { fetch: () => new Response('kitcms dev RPC worker', { status: 404 }) };\n`;
70
+ if (!fs.existsSync(worker) || fs.readFileSync(worker, 'utf8') !== source) {
71
+ fs.writeFileSync(worker, source);
72
+ }
73
+ const plugins = mod.cloudflare({
74
+ configPath: options.wranglerConfig,
75
+ viteEnvironment: { name: 'rpc' },
76
+ config: (user) => ({
77
+ name: options.devRpcName ?? `${user.name}-rpc`,
78
+ main: worker,
79
+ assets: undefined,
80
+ }),
81
+ });
82
+ // Dev only: the production build keeps using kitcmsAdapter()'s facade.
83
+ return (Array.isArray(plugins) ? plugins : [plugins]).map((p) => ({ ...p, apply: 'serve' }));
84
+ }
85
+ const KITCMS_PACKAGES = [
86
+ '@kitcms/core',
87
+ '@kitcms/ui',
88
+ '@kitcms/client',
89
+ '@kitcms/plugin-seo',
90
+ '@kitcms/plugin-enquiries',
91
+ '@kitcms/plugin-entitlements',
92
+ ];
93
+ function rpcEntryPlugin(options) {
94
+ let entry;
95
+ return {
96
+ name: 'kitcms:rpc-entry',
97
+ enforce: 'post',
98
+ // One copy of Kit and Svelte, even when @kitcms/* are linked from another checkout
99
+ // (`link:` / workspaces): a second @sveltejs/kit makes thrown `redirect()`/`error()`
100
+ // unrecognisable, so /admin answered 500 instead of redirecting.
101
+ // @kitcms/* ship TypeScript sources, so Vite must compile them as app source, as it already
102
+ // does for workspace links. Installed from npm they'd otherwise be pre-bundled (the Svelte
103
+ // optimizer parses `.svelte.ts` as plain JS, and the SSR optimizer splits core's entries into
104
+ // separate bundles with separate module state) or externalized (Node can't strip types
105
+ // under node_modules).
106
+ config: () => ({
107
+ resolve: { dedupe: ['@sveltejs/kit', 'svelte'] },
108
+ optimizeDeps: { exclude: KITCMS_PACKAGES },
109
+ ssr: { noExternal: [/^@kitcms\//], optimizeDeps: { exclude: KITCMS_PACKAGES } },
110
+ }),
111
+ configResolved(config) {
112
+ if (options.rpcEntry === false)
113
+ return;
114
+ const file = path.resolve(config.root, options.rpcEntry ?? DEFAULT_RPC_ENTRY);
115
+ if (fs.existsSync(file))
116
+ entry = file;
117
+ else if (options.rpcEntry)
118
+ throw new Error(`kitcms: RPC entry not found: ${file}`);
119
+ },
120
+ configEnvironment(name, config) {
121
+ if (name !== 'ssr' || !config.build?.rolldownOptions?.input)
122
+ return;
123
+ const input = config.build.rolldownOptions.input;
124
+ if (typeof input !== 'object' || Array.isArray(input)) {
125
+ throw new Error('kitcms: unexpected SvelteKit SSR input shape (SvelteKit changed?)');
126
+ }
127
+ // configEnvironment runs before configResolved, so resolve the default here too.
128
+ const file = entry ?? resolveEntry(options);
129
+ if (file)
130
+ input[RPC_ENTRY_NAME] = file;
131
+ },
132
+ };
133
+ }
134
+ function resolveEntry(options) {
135
+ if (options.rpcEntry === false)
136
+ return undefined;
137
+ const file = path.resolve(options.rpcEntry ?? DEFAULT_RPC_ENTRY);
138
+ return fs.existsSync(file) ? file : undefined;
139
+ }
140
+ /**
141
+ * adapter-cloudflare + the RPC facade. When the app has no RPC entry, it behaves exactly like
142
+ * adapter-cloudflare.
143
+ */
144
+ export function kitcmsAdapter(options = {}) {
145
+ // Keep the inner adapter's other hooks (`emulate` = the dev platform proxy, `supports`).
146
+ const inner = cloudflare(options);
147
+ return {
148
+ ...inner,
149
+ name: 'kitcms-adapter-cloudflare',
150
+ async adapt(builder) {
151
+ await inner.adapt(builder);
152
+ const rpc = path.join(builder.getServerDirectory(), `${RPC_ENTRY_NAME}.js`);
153
+ if (!fs.existsSync(rpc))
154
+ return; // no RPC entry: plain adapter-cloudflare
155
+ const { unstable_readConfig } = (await import('wrangler'));
156
+ const main = unstable_readConfig({ config: options.config }).main;
157
+ if (!main)
158
+ throw new Error('kitcms: wrangler `main` is required to export KitcmsRPC');
159
+ const dir = path.dirname(main);
160
+ const moved = path.join(dir, '_sveltekit_worker.js');
161
+ fs.renameSync(main, moved);
162
+ const rel = (p) => {
163
+ const r = path.relative(dir, p).split(path.sep).join('/');
164
+ return r.startsWith('.') ? r : `./${r}`;
165
+ };
166
+ fs.writeFileSync(main, `export { default } from ${JSON.stringify(rel(moved))};\n` +
167
+ `export * from ${JSON.stringify(rel(rpc))};\n`);
168
+ // The worker dir may double as the assets dir: never upload the moved file as an asset.
169
+ const ignore = path.join(dir, '.assetsignore');
170
+ if (fs.existsSync(ignore))
171
+ fs.appendFileSync(ignore, '\n_sveltekit_worker.js\n');
172
+ else
173
+ fs.writeFileSync(ignore, '_sveltekit_worker.js\n');
174
+ },
175
+ };
176
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kitcms/core",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -43,8 +43,8 @@
43
43
  "default": "./src/richtext/index.ts"
44
44
  },
45
45
  "./vite": {
46
- "types": "./src/vite/index.ts",
47
- "default": "./src/vite/index.ts"
46
+ "types": "./dist/vite/index.d.ts",
47
+ "default": "./dist/vite/index.js"
48
48
  }
49
49
  },
50
50
  "bin": {
@@ -53,6 +53,7 @@
53
53
  "files": [
54
54
  "src",
55
55
  "bin",
56
+ "dist",
56
57
  "!src/**/*.test.ts"
57
58
  ],
58
59
  "peerDependencies": {
@@ -87,6 +88,7 @@
87
88
  }
88
89
  },
89
90
  "scripts": {
90
- "typecheck": "tsc --noEmit && tsc -p test/tsconfig.json && tsc -p src/cli/cli.tsconfig.json && tsc -p src/vite/tsconfig.json"
91
+ "typecheck": "tsc --noEmit && tsc -p test/tsconfig.json && tsc -p src/cli/cli.tsconfig.json && tsc -p src/vite/tsconfig.json",
92
+ "build:vite": "tsc -p src/vite/tsconfig.build.json"
91
93
  }
92
94
  }
package/src/vite/index.ts CHANGED
@@ -103,6 +103,15 @@ async function devRpcPlugins(options: KitcmsViteOptions): Promise<Plugin[]> {
103
103
  return (Array.isArray(plugins) ? plugins : [plugins]).map((p) => ({ ...p, apply: 'serve' as const }));
104
104
  }
105
105
 
106
+ const KITCMS_PACKAGES = [
107
+ '@kitcms/core',
108
+ '@kitcms/ui',
109
+ '@kitcms/client',
110
+ '@kitcms/plugin-seo',
111
+ '@kitcms/plugin-enquiries',
112
+ '@kitcms/plugin-entitlements',
113
+ ];
114
+
106
115
  function rpcEntryPlugin(options: KitcmsViteOptions): Plugin {
107
116
  let entry: string | undefined;
108
117
  return {
@@ -111,7 +120,16 @@ function rpcEntryPlugin(options: KitcmsViteOptions): Plugin {
111
120
  // One copy of Kit and Svelte, even when @kitcms/* are linked from another checkout
112
121
  // (`link:` / workspaces): a second @sveltejs/kit makes thrown `redirect()`/`error()`
113
122
  // unrecognisable, so /admin answered 500 instead of redirecting.
114
- config: () => ({ resolve: { dedupe: ['@sveltejs/kit', 'svelte'] } }),
123
+ // @kitcms/* ship TypeScript sources, so Vite must compile them as app source, as it already
124
+ // does for workspace links. Installed from npm they'd otherwise be pre-bundled (the Svelte
125
+ // optimizer parses `.svelte.ts` as plain JS, and the SSR optimizer splits core's entries into
126
+ // separate bundles with separate module state) or externalized (Node can't strip types
127
+ // under node_modules).
128
+ config: () => ({
129
+ resolve: { dedupe: ['@sveltejs/kit', 'svelte'] },
130
+ optimizeDeps: { exclude: KITCMS_PACKAGES },
131
+ ssr: { noExternal: [/^@kitcms\//], optimizeDeps: { exclude: KITCMS_PACKAGES } },
132
+ }),
115
133
  configResolved(config) {
116
134
  if (options.rpcEntry === false) return;
117
135
  const file = path.resolve(config.root, options.rpcEntry ?? DEFAULT_RPC_ENTRY);
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "noEmit": false,
5
+ "declaration": true,
6
+ "rootDir": ".",
7
+ "outDir": "../../dist/vite"
8
+ },
9
+ "include": ["index.ts"]
10
+ }