oc-server 3.2.1 → 4.0.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/dist/Server.d.ts CHANGED
@@ -102,8 +102,6 @@ export type ComponentSettings = {
102
102
  name: string;
103
103
  version: string;
104
104
  };
105
- export declare const getInitialData: () => InitialData;
106
- export declare const getSettings: () => ComponentSettings;
107
105
  type ErrorCodes = 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511;
108
106
  export declare class ServerError extends Error {
109
107
  statusCode: ErrorCodes;
package/dist/Server.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ServerError = exports.getSettings = exports.getInitialData = exports.Server = void 0;
3
+ exports.ServerError = exports.Server = void 0;
4
4
  // Simple ANSI color utility function
5
5
  const styleText = (color, text) => {
6
6
  const colors = {
@@ -84,12 +84,6 @@ class HandledServer {
84
84
  };
85
85
  }
86
86
  }
87
- const getInitialData = () => typeof __$$oc_initialData__ !== 'undefined'
88
- ? __$$oc_initialData__
89
- : {};
90
- exports.getInitialData = getInitialData;
91
- const getSettings = () => typeof __$$oc_Settings__ !== 'undefined' ? __$$oc_Settings__ : {};
92
- exports.getSettings = getSettings;
93
87
  class ServerError extends Error {
94
88
  statusCode;
95
89
  constructor(statusCode, message) {
@@ -1,2 +1 @@
1
1
  #!/usr/bin/env node
2
- export {};
package/dist/cli.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ console.warn('\x1b[33m%s\x1b[0m', 'WARNING: The "oc-server" command is deprecated. Please use the Vite plugin instead by adding oc() to your vite.config.ts. See documentation for migration guide.');
@@ -0,0 +1,2 @@
1
+ export { type ActionOutput, serverClient, getInitialData, getSettings, } from './serverClient';
2
+ export { type Action, type InitialData } from './Server';
package/dist/client.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSettings = exports.getInitialData = exports.serverClient = void 0;
4
+ var serverClient_1 = require("./serverClient");
5
+ Object.defineProperty(exports, "serverClient", { enumerable: true, get: function () { return serverClient_1.serverClient; } });
6
+ Object.defineProperty(exports, "getInitialData", { enumerable: true, get: function () { return serverClient_1.getInitialData; } });
7
+ Object.defineProperty(exports, "getSettings", { enumerable: true, get: function () { return serverClient_1.getSettings; } });
package/dist/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
- export * from './Server';
2
- export * from './serverClient';
1
+ export { Server, ServerError, type ServerContext, type Register, } from './Server';
3
2
  export { DataProvider, Template, External, DataContext } from './types';
package/dist/index.js CHANGED
@@ -1,18 +1,6 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
2
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./Server"), exports);
18
- __exportStar(require("./serverClient"), exports);
3
+ exports.ServerError = exports.Server = void 0;
4
+ var Server_1 = require("./Server");
5
+ Object.defineProperty(exports, "Server", { enumerable: true, get: function () { return Server_1.Server; } });
6
+ Object.defineProperty(exports, "ServerError", { enumerable: true, get: function () { return Server_1.ServerError; } });
@@ -1,5 +1,7 @@
1
- import { AnyServer, RegisteredServer, Action, GetMiddlewareInput } from './Server';
2
- import { IsAnyOrUnknown, Prettify, ToPrettyJson } from './types';
1
+ import type { AnyServer, RegisteredServer, Action, GetMiddlewareInput, ComponentSettings, InitialData } from './Server';
2
+ import type { IsAnyOrUnknown, Prettify, ToPrettyJson } from './types';
3
+ export declare const getInitialData: () => InitialData;
4
+ export declare const getSettings: () => ComponentSettings;
3
5
  type InferInput<R> = R extends Action<infer I, any, any, any, any> ? I : any;
4
6
  type InferOutput<R> = R extends Action<any, infer O, any, any, any> ? ToPrettyJson<O> : never;
5
7
  type IsEmptyObject<T> = keyof T extends never ? true : false;
@@ -1,14 +1,19 @@
1
1
  "use strict";
2
2
  /// <reference types="oc-vite/client" />
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.serverClient = void 0;
5
- const Server_1 = require("./Server");
4
+ exports.serverClient = exports.getSettings = exports.getInitialData = void 0;
5
+ const getInitialData = () => typeof __$$oc_initialData__ !== 'undefined'
6
+ ? __$$oc_initialData__
7
+ : {};
8
+ exports.getInitialData = getInitialData;
9
+ const getSettings = () => typeof __$$oc_Settings__ !== 'undefined' ? __$$oc_Settings__ : {};
10
+ exports.getSettings = getSettings;
6
11
  exports.serverClient = new Proxy({}, {
7
12
  get(_target, prop) {
8
13
  return (data, options) => {
9
14
  const componentName = 'COMPONENT_NAME';
10
15
  const componentVersion = 'COMPONENT_VERSION';
11
- const baseUrl = (0, Server_1.getSettings)().baseUrl ??
16
+ const baseUrl = (0, exports.getSettings)().baseUrl ??
12
17
  window.oc?.renderedComponents?.[componentName]?.baseUrl;
13
18
  return window.oc.getAction({
14
19
  action: prop,
@@ -0,0 +1,6 @@
1
+ import type { Plugin } from 'vite';
2
+ interface OcVitePluginOptions {
3
+ port?: number;
4
+ }
5
+ export declare function oc(options?: OcVitePluginOptions): Plugin;
6
+ export {};
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.oc = oc;
4
+ function oc(options = {}) {
5
+ const moduleRequire = typeof require !== 'undefined' ? require : null;
6
+ if (!moduleRequire) {
7
+ throw new Error('oc-vite-plugin requires a CommonJS environment with require() available');
8
+ }
9
+ return {
10
+ name: 'oc-vite-plugin',
11
+ async configureServer(server) {
12
+ const fs = moduleRequire('node:fs');
13
+ const path = moduleRequire('node:path');
14
+ const vm = moduleRequire('node:vm');
15
+ const esbuild = moduleRequire('esbuild');
16
+ const { loadConfigFromFile } = moduleRequire('vite');
17
+ const ocClientBrowser = moduleRequire('oc-client-browser');
18
+ const { getContext, getDefaultParams, parsePkg } = moduleRequire('./oc');
19
+ const getMockedPlugins = moduleRequire('./get-mocked-plugins').default;
20
+ const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf-8'));
21
+ const parsedPkg = parsePkg(pkg);
22
+ const templateType = parsedPkg.templateType;
23
+ const { createRequire } = moduleRequire('module');
24
+ const projectRequire = createRequire(path.join(process.cwd(), 'package.json'));
25
+ const tryRequire = (name) => {
26
+ try {
27
+ return { success: true, value: projectRequire(name) };
28
+ }
29
+ catch (e) {
30
+ return { success: false, value: e };
31
+ }
32
+ };
33
+ const result = tryRequire(`${templateType}-compiler/dist/lib/hmr`);
34
+ if (!result.success) {
35
+ const code = String(result.value.code);
36
+ if (code === 'ERR_REQUIRE_ESM') {
37
+ throw new Error('You are using an older version of node that does not support ESM on require. Please update to the latest 22.x or higher');
38
+ }
39
+ else if (code === 'MODULE_NOT_FOUND') {
40
+ const baseResult = tryRequire(`${templateType}-compiler`);
41
+ if (baseResult.success) {
42
+ throw new Error(`The template ${templateType} is not supported. Try updating to the last version`);
43
+ }
44
+ else {
45
+ throw new Error(`Could not find the template compiler library: ${templateType}-compiler in your project`);
46
+ }
47
+ }
48
+ else {
49
+ throw result.value;
50
+ }
51
+ }
52
+ const template = result.value;
53
+ const promisify = (fn) => (...args) => new Promise((resolve, reject) => fn(...args, (err, data) => err ? reject(err) : resolve(data)));
54
+ const getDataProvider = (serverEntry) => {
55
+ if (!serverEntry) {
56
+ return {
57
+ dataProvider: async (context) => ({
58
+ ...(context.params ?? {}),
59
+ }),
60
+ };
61
+ }
62
+ const result = esbuild.buildSync({
63
+ entryPoints: [serverEntry],
64
+ bundle: true,
65
+ format: 'cjs',
66
+ write: false,
67
+ });
68
+ const code = result.outputFiles[0].text;
69
+ const backend = vm.runInNewContext(code, {
70
+ ...globalThis,
71
+ exports: {},
72
+ console,
73
+ module: { exports: {} },
74
+ });
75
+ const dataProvider = backend.data || backend.server.getData();
76
+ return {
77
+ dataProvider: promisify(dataProvider),
78
+ parametersSchema: backend.server?._parameters,
79
+ };
80
+ };
81
+ const getBaseTemplate = (appBlock, name, version, appEntry, imports = {}) => {
82
+ return `
83
+ <!DOCTYPE html>
84
+ <html>
85
+ <head>
86
+ <meta name="robots" content="index, follow" />
87
+ <meta charset="utf-8" />
88
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
89
+ <style>
90
+ html, body {
91
+ width: 100%;
92
+ height: 100%;
93
+ margin: 0;
94
+ }
95
+ </style>
96
+ ${imports
97
+ ? `<script type="importmap">{"imports": ${JSON.stringify(imports)}}</script>`
98
+ : ''}
99
+ </head>
100
+ <body>
101
+ <script src="/oc-client/client.js"></script>
102
+ ${appBlock({ name, version, entry: appEntry })}
103
+ </body>
104
+ </html>
105
+ `;
106
+ };
107
+ const getHtmlTemplate = async (appBlock, name, version, appEntry, imports = {}, filePath = 'index.html') => {
108
+ let htmlTemplate;
109
+ try {
110
+ htmlTemplate = fs.readFileSync(path.resolve(process.cwd(), filePath), 'utf-8');
111
+ if (!htmlTemplate.includes('</body>')) {
112
+ throw new Error('If you use a custom html entry it has to have a closing body tag');
113
+ }
114
+ htmlTemplate = htmlTemplate.replace('</body>', `<script>
115
+ if (!window.oc?.status) {
116
+ const script = document.createElement('script');
117
+ script.src = '/oc-client/client.js';
118
+ document.body.appendChild(script);
119
+ }
120
+ </script>
121
+ ${appBlock({ name, version, entry: appEntry })}</body>`);
122
+ }
123
+ catch (error) {
124
+ htmlTemplate = getBaseTemplate(appBlock, name, version, appEntry, imports);
125
+ }
126
+ return htmlTemplate;
127
+ };
128
+ const name = parsedPkg.name;
129
+ const version = parsedPkg.version;
130
+ const appEntry = parsedPkg.appEntry;
131
+ const serverEntry = parsedPkg.serverEntry;
132
+ const dpResult = getDataProvider(serverEntry);
133
+ const dataProvider = dpResult.dataProvider;
134
+ const parametersSchema = dpResult.parametersSchema;
135
+ const plugins = getMockedPlugins(path.join(process.cwd(), '..'));
136
+ for (const plugin of plugins) {
137
+ plugin.register.register(null, null, () => { });
138
+ }
139
+ const defaultParams = getDefaultParams(pkg.oc?.parameters ?? parametersSchema);
140
+ const baseConfig = await loadConfigFromFile({
141
+ command: 'build',
142
+ mode: 'development',
143
+ }, undefined, process.cwd()).catch(() => null);
144
+ const baseConfigImports = baseConfig?.config?.resolve?.alias;
145
+ const { dev: clientJs } = ocClientBrowser.compileSync();
146
+ server.middlewares.use('/oc-client/client.js', (req, res) => {
147
+ res.statusCode = 200;
148
+ res.setHeader('Content-Type', 'text/javascript');
149
+ res.end(clientJs);
150
+ });
151
+ server.middlewares.use(async (req, res, next) => {
152
+ if (req.method === 'POST' && req.url === '/') {
153
+ try {
154
+ let body = '';
155
+ req.on('data', (chunk) => {
156
+ body += chunk.toString();
157
+ });
158
+ req.on('end', async () => {
159
+ const { action, parameters } = JSON.parse(body).components[0];
160
+ const { context, responseHeaders } = getContext(plugins, req, parameters, action);
161
+ const props = await dataProvider(context);
162
+ const response = [
163
+ {
164
+ status: 200,
165
+ response: {
166
+ data: {
167
+ component: {
168
+ props,
169
+ },
170
+ },
171
+ },
172
+ },
173
+ ];
174
+ for (const [key, value] of Object.entries(responseHeaders)) {
175
+ res.setHeader(key, value);
176
+ }
177
+ res.statusCode = 200;
178
+ res.setHeader('Content-Type', 'application/json');
179
+ res.end(JSON.stringify(response));
180
+ });
181
+ }
182
+ catch (e) {
183
+ server.ssrFixStacktrace(e);
184
+ res.statusCode = 500;
185
+ res.end(JSON.stringify({ error: e.message }));
186
+ }
187
+ }
188
+ else {
189
+ next();
190
+ }
191
+ });
192
+ server.middlewares.use(async (req, res, next) => {
193
+ if (req.method === 'GET' && req.url === '/') {
194
+ try {
195
+ const params = defaultParams;
196
+ const { context, responseHeaders } = getContext(plugins, req, params);
197
+ let htmlTemplate = await getHtmlTemplate(template.appBlock, name, version, appEntry, typeof baseConfigImports === 'object' && !!baseConfigImports
198
+ ? baseConfigImports
199
+ : {});
200
+ const data = await dataProvider(context);
201
+ htmlTemplate = htmlTemplate.replace('__INITIAL_DATA__', JSON.stringify(data));
202
+ const transformedHtml = await server.transformIndexHtml(req.url || '/', htmlTemplate);
203
+ for (const [key, value] of Object.entries(responseHeaders)) {
204
+ res.setHeader(key, value);
205
+ }
206
+ res.statusCode = 200;
207
+ res.setHeader('Content-Type', 'text/html');
208
+ res.end(transformedHtml);
209
+ }
210
+ catch (e) {
211
+ server.ssrFixStacktrace(e);
212
+ next(e);
213
+ }
214
+ }
215
+ else {
216
+ next();
217
+ }
218
+ });
219
+ },
220
+ };
221
+ }
package/package.json CHANGED
@@ -1,14 +1,31 @@
1
1
  {
2
2
  "name": "oc-server",
3
- "version": "3.2.1",
3
+ "version": "4.0.0",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
- "bin": "dist/cli/index.js",
7
+ "bin": "dist/cli.js",
8
8
  "scripts": {
9
9
  "build": "tsc",
10
10
  "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist"
11
11
  },
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "require": "./dist/index.js",
16
+ "types": "./dist/index.d.ts"
17
+ },
18
+ "./client": {
19
+ "import": "./dist/client.js",
20
+ "require": "./dist/client.js",
21
+ "types": "./dist/client.d.ts"
22
+ },
23
+ "./vite": {
24
+ "import": "./dist/vite/plugin.js",
25
+ "require": "./dist/vite/plugin.js",
26
+ "types": "./dist/vite/plugin.d.ts"
27
+ }
28
+ },
12
29
  "keywords": [
13
30
  "oc",
14
31
  "opencomponents"
@@ -25,5 +42,11 @@
25
42
  "@fastify/express": "^3.0.0",
26
43
  "fastify": "^4.28.1",
27
44
  "oc-client-browser": "^1.8.0"
45
+ },
46
+ "peerDependencies": {
47
+ "vite": "^5.0.0 || ^6.0.0"
48
+ },
49
+ "devDependencies": {
50
+ "typescript": "^5.1.3"
28
51
  }
29
52
  }
package/dist/cli/cli.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare function cli(): void;
package/dist/cli/cli.js DELETED
@@ -1,86 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.cli = cli;
7
- const node_path_1 = __importDefault(require("node:path"));
8
- const node_util_1 = require("node:util");
9
- const oc_1 = require("./oc");
10
- const server_1 = require("./server");
11
- const pkg = require(node_path_1.default.join(process.cwd(), 'package.json'));
12
- const { templateType } = (0, oc_1.parsePkg)(pkg);
13
- function cli() {
14
- const { positionals: [command], values: { help, port = '5000' }, } = (0, node_util_1.parseArgs)({
15
- allowPositionals: true,
16
- options: {
17
- port: {
18
- type: 'string',
19
- default: '5000',
20
- short: 'p',
21
- },
22
- help: {
23
- type: 'boolean',
24
- default: false,
25
- short: 'h',
26
- },
27
- },
28
- });
29
- if (help || !command) {
30
- console.log(`
31
- Usage:
32
- $ oc-server <command> [options]
33
-
34
- Commands:
35
- dev Start the development server
36
-
37
- Options:
38
- -h, --help Display this message
39
- `);
40
- if (help && command === 'dev') {
41
- console.log(`
42
- Usage:
43
- $ oc-server <command> [options]
44
-
45
- Commands:
46
- dev Start the development server
47
-
48
- Options:
49
- -h, --help Display this message
50
- -p, --port Port to use (default: 5000)
51
- `);
52
- }
53
- process.exit(0);
54
- }
55
- function tryRequire(name) {
56
- try {
57
- return { success: true, value: require(name) };
58
- }
59
- catch (e) {
60
- return { success: false, value: e };
61
- }
62
- }
63
- const result = tryRequire(`${templateType}-compiler/dist/lib/hmr`);
64
- if (!result.success) {
65
- const code = String(result.value.code);
66
- if (code === 'ERR_REQUIRE_ESM') {
67
- console.error('You are using an older version of node that does not support ESM on require. Please update to the latest 22.x or higher');
68
- }
69
- else if (code === 'MODULE_NOT_FOUND') {
70
- const baseResult = tryRequire(`${templateType}-compiler`);
71
- if (baseResult.success) {
72
- console.error(`The template ${templateType} is not supported. Try updating to the last version`);
73
- }
74
- else {
75
- console.error(`Could not find the template compiler library: ${templateType}-compiler in your project`);
76
- }
77
- }
78
- else {
79
- console.error(result.value);
80
- }
81
- process.exit(1);
82
- }
83
- if (command === 'dev') {
84
- (0, server_1.createServer)({ template: result.value, port });
85
- }
86
- }
package/dist/cli/index.js DELETED
@@ -1,6 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- process.env.VITE_CJS_IGNORE_WARNING = 'true';
5
- const cli_1 = require("./cli");
6
- (0, cli_1.cli)();
package/dist/errors.d.ts DELETED
@@ -1,6 +0,0 @@
1
- type ErrorCodes = 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 510 | 511;
2
- export declare class ServerError extends Error {
3
- statusCode: ErrorCodes;
4
- constructor(statusCode: ErrorCodes, message: string);
5
- }
6
- export {};
package/dist/errors.js DELETED
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ServerError = void 0;
4
- class ServerError extends Error {
5
- statusCode;
6
- constructor(statusCode, message) {
7
- super(message);
8
- this.statusCode = statusCode;
9
- }
10
- }
11
- exports.ServerError = ServerError;
@@ -1,16 +0,0 @@
1
- import type { DataContext } from './types';
2
- export type ServerContext<E = {
3
- name: string;
4
- }, P = any, S = any> = Omit<DataContext<any, E, P, S>, 'params' | 'action' | 'setEmptyResponse'>;
5
- export type Action<I, O, E, P, S> = (params: I, ctx: ServerContext<E, P, S>) => Promise<O> | O;
6
- export interface Register {
7
- }
8
- export type AnyServer = {
9
- actions: Record<string, Action<any, any, any, any, any>>;
10
- };
11
- export type RegisteredServer = Register extends {
12
- server: infer TServer extends AnyServer;
13
- } ? TServer : AnyServer;
14
- export type GetMiddlewareInput<TServer extends AnyServer> = TServer extends {
15
- _middlewareInput: infer I;
16
- } ? I : any;
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,10 +0,0 @@
1
- export type ComponentSettings = {
2
- id: string;
3
- element: HTMLElement;
4
- staticPath: string;
5
- baseUrl: string;
6
- name: string;
7
- version: string;
8
- };
9
- export declare const getInitialData: <T = any>() => T;
10
- export declare const getSettings: () => ComponentSettings;
package/dist/settings.js DELETED
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getSettings = exports.getInitialData = void 0;
4
- const getInitialData = () => typeof __$$oc_initialData__ !== 'undefined'
5
- ? __$$oc_initialData__
6
- : {};
7
- exports.getInitialData = getInitialData;
8
- const getSettings = () => typeof __$$oc_Settings__ !== 'undefined' ? __$$oc_Settings__ : {};
9
- exports.getSettings = getSettings;
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes