oc-template-preact-compiler 0.2.0 → 0.3.0-beta.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,2 @@
1
+ export * from './lib/compile';
2
+ export * from 'oc-template-preact';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./lib/compile"), exports);
18
+ __exportStar(require("oc-template-preact"), exports);
@@ -0,0 +1,3 @@
1
+ import { createCompile } from 'oc-generic-template-compiler';
2
+ export type CompilerOptions = ReturnType<typeof createCompile>;
3
+ export declare const compile: CompilerOptions;
@@ -0,0 +1,36 @@
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.compile = void 0;
7
+ const oc_generic_template_compiler_1 = require("oc-generic-template-compiler");
8
+ const oc_statics_compiler_1 = __importDefault(require("oc-statics-compiler"));
9
+ const oc_template_preact_1 = require("oc-template-preact");
10
+ const oc_vite_compiler_1 = require("oc-vite-compiler");
11
+ const preset_vite_1 = require("@preact/preset-vite");
12
+ const preactOCProviderTemplate_1 = __importDefault(require("./preactOCProviderTemplate"));
13
+ const htmlTemplate_1 = __importDefault(require("./htmlTemplate"));
14
+ exports.compile = (0, oc_generic_template_compiler_1.createCompile)({
15
+ compileView: (options, cb) => (0, oc_vite_compiler_1.viteView)({
16
+ ...options,
17
+ plugins: [(0, preset_vite_1.preact)()],
18
+ viewWrapper: ({ viewPath }) => (0, preactOCProviderTemplate_1.default)({ viewPath }),
19
+ htmlTemplate: htmlTemplate_1.default,
20
+ externals: (0, oc_template_preact_1.getInfo)().externals
21
+ }, cb),
22
+ compileServer: oc_vite_compiler_1.viteServer,
23
+ compileStatics: oc_statics_compiler_1.default,
24
+ getInfo: oc_template_preact_1.getInfo
25
+ });
26
+ // OPTIONS
27
+ // =======
28
+ // componentPath
29
+ // componentPackage,
30
+ // logger,
31
+ // minify
32
+ // ocPackage
33
+ // publishPath
34
+ // verbose,
35
+ // watch,
36
+ // production
@@ -0,0 +1,6 @@
1
+ export default function viewTemplate({ templateId, css, bundle, hash }: {
2
+ templateId: string;
3
+ css: string;
4
+ bundle: string;
5
+ hash: string;
6
+ }): string;
@@ -1,4 +1,11 @@
1
- const viewTemplate = ({ templateId, css, bundle, hash }) => `function(model){
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
+ const cssesc_1 = __importDefault(require("cssesc"));
7
+ function viewTemplate({ templateId, css, bundle, hash }) {
8
+ return `function(model){
2
9
  var modelHTML = model.__html ? model.__html : '';
3
10
  var staticPath = model.preactComponent.props._staticPath;
4
11
  var props = JSON.stringify(model.preactComponent.props);
@@ -10,7 +17,7 @@ const viewTemplate = ({ templateId, css, bundle, hash }) => `function(model){
10
17
  var templateId = "${templateId}-" + count;
11
18
  window.oc.__typescriptReactTemplate.count++;
12
19
  return '<div id="' + templateId + '" class="${templateId}">' + modelHTML + '</div>' +
13
- '${css ? '<style>' + css + '</style>' : ''}' +
20
+ '${css ? '<style>' + (0, cssesc_1.default)(css) + '</style>' : ''}' +
14
21
  '<script>' +
15
22
  'window.oc = window.oc || {};' +
16
23
  'oc.cmd = oc.cmd || [];' +
@@ -22,5 +29,5 @@ const viewTemplate = ({ templateId, css, bundle, hash }) => `function(model){
22
29
  '});' +
23
30
  '</script>'
24
31
  }`;
25
-
26
- module.exports = viewTemplate;
32
+ }
33
+ exports.default = viewTemplate;
@@ -0,0 +1,3 @@
1
+ export default function preactOCProviderTemplate({ viewPath }: {
2
+ viewPath: string;
3
+ }): string;
@@ -1,10 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
1
3
  const removeExtension = (path) => path.replace(/\.(t|j)sx?$/, '');
2
-
3
- const preactOCProviderTemplate = ({ viewPath }) => `
4
+ function preactOCProviderTemplate({ viewPath }) {
5
+ return `
4
6
  import { render } from 'preact';
5
7
  import { useEffect } from 'preact/hooks';
6
8
  import View from '${removeExtension(viewPath)}';
7
- import { DataProvider } from 'oc-template-preact-compiler/utils/useData'
9
+ import { DataProvider } from 'oc-template-preact-compiler/dist/utils/useData'
8
10
 
9
11
  function OCProvider(props: any): any {
10
12
  const { _staticPath, _baseUrl, _componentName, _componentVersion, ...rest } = props;
@@ -23,7 +25,7 @@ const preactOCProviderTemplate = ({ viewPath }) => `
23
25
  if (err) {
24
26
  return cb(err);
25
27
  }
26
- cb(null, rest, data.preactComponent.props);
28
+ cb(null, rest, data.component.props);
27
29
  });
28
30
  }
29
31
 
@@ -53,5 +55,5 @@ const preactOCProviderTemplate = ({ viewPath }) => `
53
55
 
54
56
  export default renderer;
55
57
  `;
56
-
57
- module.exports = preactOCProviderTemplate;
58
+ }
59
+ exports.default = preactOCProviderTemplate;
@@ -0,0 +1,2 @@
1
+ declare const App: () => import("react/jsx-runtime").JSX.Element;
2
+ export default App;
@@ -0,0 +1,30 @@
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
+ const jsx_runtime_1 = require("react/jsx-runtime");
7
+ const hooks_1 = require("preact/hooks");
8
+ const useData_1 = require("oc-template-preact-compiler/utils/useData");
9
+ const styles_css_1 = __importDefault(require("./styles.css"));
10
+ const App = () => {
11
+ const { firstName, lastName, userId, getData, getSetting } = (0, useData_1.useData)();
12
+ const staticPath = getSetting('staticPath');
13
+ const [additionalData, setAdditionalData] = (0, hooks_1.useState)(null);
14
+ const [error, setError] = (0, hooks_1.useState)('');
15
+ const fetchMoreData = async () => {
16
+ setError('');
17
+ try {
18
+ const data = await getData({ userId, getMoreData: true });
19
+ setAdditionalData(data);
20
+ }
21
+ catch (err) {
22
+ setError(String(err));
23
+ }
24
+ };
25
+ if (error) {
26
+ return (0, jsx_runtime_1.jsx)("div", { children: "Something wrong happened!" });
27
+ }
28
+ return ((0, jsx_runtime_1.jsxs)("div", { className: styles_css_1.default.container, children: [(0, jsx_runtime_1.jsx)("img", { width: "50", height: "50", src: `${staticPath}/public/logo.png`, alt: "Logo" }), (0, jsx_runtime_1.jsxs)("h1", { style: { margin: '0 0 20px 0' }, children: ["Hello, ", (0, jsx_runtime_1.jsx)("span", { style: { textDecoration: 'underline' }, children: firstName }), " ", lastName] }), additionalData && ((0, jsx_runtime_1.jsxs)("div", { className: styles_css_1.default.info, children: [(0, jsx_runtime_1.jsxs)("div", { className: styles_css_1.default.block, children: ["Age: ", additionalData.age] }), (0, jsx_runtime_1.jsxs)("div", { className: styles_css_1.default.block, children: ["Hobbies: ", additionalData.hobbies.map((x) => x.toLowerCase()).join(', ')] })] })), (0, jsx_runtime_1.jsx)("button", { className: styles_css_1.default.button, onClick: fetchMoreData, children: "Get extra information" })] }));
29
+ };
30
+ exports.default = App;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
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
+ const jsx_runtime_1 = require("react/jsx-runtime");
7
+ const vitest_1 = require("vitest");
8
+ const react_1 = require("@testing-library/react");
9
+ const useData_1 = require("oc-template-preact-compiler/utils/useData");
10
+ const App_1 = __importDefault(require("./App"));
11
+ const getData = vitest_1.vi.fn();
12
+ (0, vitest_1.describe)('App - Page', () => {
13
+ (0, vitest_1.beforeEach)(() => {
14
+ window.oc = { events: { on: vitest_1.vi.fn(), fire: vitest_1.vi.fn() } };
15
+ });
16
+ (0, vitest_1.afterEach)(() => {
17
+ vitest_1.vi.restoreAllMocks();
18
+ });
19
+ (0, vitest_1.it)('Gets more data when clicking the button', () => {
20
+ getData.mockImplementationOnce(() => Promise.resolve({}));
21
+ (0, react_1.render)((0, jsx_runtime_1.jsx)(useData_1.DataProvider, { value: { firstName: 'firstName', lastName: 'lastName', userId: 0, getData }, children: (0, jsx_runtime_1.jsx)(App_1.default, { firstName: "firstName", lastName: "lastName", userId: 0 }) }));
22
+ const extraInfoButton = react_1.screen.getByText(/Get extra information/i);
23
+ (0, vitest_1.expect)(extraInfoButton).toBeTruthy();
24
+ });
25
+ });
@@ -0,0 +1,3 @@
1
+ import { Context } from 'oc-template-preact-compiler';
2
+ import { AdditionalData, ClientProps, OcParameters } from './types';
3
+ export declare function data(context: Context<OcParameters>, callback: (error: any, data: ClientProps | AdditionalData) => void): Promise<void>;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.data = void 0;
4
+ const database = [
5
+ { name: 'John Doe', age: 34, hobbies: ['Swimming', 'Basketball'] },
6
+ { name: 'Jane Doe', age: 35, hobbies: ['Running', 'Rugby'] }
7
+ ];
8
+ async function getUser(userId) {
9
+ return database[userId];
10
+ }
11
+ async function data(context, callback) {
12
+ const { userId } = context.params;
13
+ const user = await getUser(userId);
14
+ const shouldGetMoreData = context.params.getMoreData;
15
+ const [firstName, lastName] = user.name.split(/\s+/);
16
+ if (shouldGetMoreData) {
17
+ return callback(null, {
18
+ age: user.age,
19
+ hobbies: user.hobbies
20
+ });
21
+ }
22
+ return callback(null, {
23
+ userId,
24
+ firstName,
25
+ lastName
26
+ });
27
+ }
28
+ exports.data = data;
@@ -0,0 +1,13 @@
1
+ export interface OcParameters {
2
+ userId: number;
3
+ getMoreData?: boolean;
4
+ }
5
+ export interface AdditionalData {
6
+ hobbies: string[];
7
+ age: number;
8
+ }
9
+ export interface ClientProps extends Partial<AdditionalData> {
10
+ userId: number;
11
+ firstName: string;
12
+ lastName: string;
13
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("vite").UserConfig & Promise<import("vite").UserConfig> & import("vite").UserConfigFnObject & import("vite").UserConfigExport;
2
+ export default _default;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vite_1 = require("vite");
4
+ // https://vitejs.dev/config/
5
+ exports.default = (0, vite_1.defineConfig)({
6
+ // Add your own plugins here for thinkgs like eslint or typecheckers
7
+ plugins: [],
8
+ // @ts-ignore Missing test property
9
+ test: {
10
+ environment: 'jsdom'
11
+ }
12
+ });
@@ -0,0 +1,7 @@
1
+ type PromiseData<T = any> = T & {
2
+ getData<O = any>(parameters?: Partial<T>): Promise<O>;
3
+ getSetting(setting: 'name' | 'version' | 'baseUrl' | 'staticPath'): string;
4
+ };
5
+ export declare const DataProvider: ({ children, ...props }: any) => import("react/jsx-runtime").JSX.Element;
6
+ export declare function useData<T = any>(): PromiseData<T>;
7
+ export {};
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useData = exports.DataProvider = void 0;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const preact_1 = require("preact");
6
+ const hooks_1 = require("preact/hooks");
7
+ const DataContext = (0, preact_1.createContext)({});
8
+ const DataProvider = ({ children, ...props }) => {
9
+ // @ts-ignore children props
10
+ return (0, jsx_runtime_1.jsx)(DataContext.Provider, { value: props, children: children });
11
+ };
12
+ exports.DataProvider = DataProvider;
13
+ function useData() {
14
+ const { value: { getData, ...rest } } = (0, hooks_1.useContext)(DataContext);
15
+ const asyncGetData = (0, hooks_1.useCallback)((data) => {
16
+ return new Promise((resolve, reject) => {
17
+ // @ts-ignore
18
+ getData({ ...rest, ...data }, (err, newData) => {
19
+ if (err) {
20
+ reject(err);
21
+ }
22
+ else {
23
+ resolve(newData);
24
+ }
25
+ });
26
+ });
27
+ }, []);
28
+ // @ts-ignore
29
+ return { getData: asyncGetData, ...rest };
30
+ }
31
+ exports.useData = useData;
package/package.json CHANGED
@@ -1,16 +1,22 @@
1
1
  {
2
2
  "name": "oc-template-preact-compiler",
3
- "version": "0.2.0",
3
+ "version": "0.3.0-beta.1",
4
4
  "description": "",
5
- "main": "index.js",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "prepare": "npm run build",
10
+ "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist"
11
+ },
6
12
  "repository": {
7
13
  "type": "git",
8
- "url": "https://github.com/guestlinelabs/oc-template-preact.git"
14
+ "url": "https://github.com/opencomponents/vite-templates.git"
9
15
  },
10
16
  "bugs": {
11
- "url": "https://github.com/guestlinelabs/oc-template-preact/issues"
17
+ "url": "https://github.com/opencomponents/vite-templates/issues"
12
18
  },
13
- "homepage": "https://github.com/guestlinelabs/oc-template-preact#readme",
19
+ "homepage": "https://github.com/opencomponents/vite-templates#readme",
14
20
  "keywords": [
15
21
  "oc",
16
22
  "opencomponents",
@@ -22,15 +28,15 @@
22
28
  "email": "mkredz@gmail.com"
23
29
  },
24
30
  "license": "MIT",
25
- "types": "./lib/oc-app.d.ts",
26
31
  "dependencies": {
27
32
  "@preact/preset-vite": "^2.5.0",
28
33
  "chalk": "^3.0.0",
34
+ "cssesc": "^3.0.0",
29
35
  "immer": "^9.0.6",
30
36
  "oc-generic-template-compiler": "2.1.0",
31
- "oc-statics-compiler": "2.0.10",
32
- "oc-template-preact": "0.0.2",
33
- "oc-vite-compiler": "^2.1.0",
37
+ "oc-statics-compiler": "2.1.1",
38
+ "oc-template-preact": "*",
39
+ "oc-vite-compiler": "3.0.0-beta.2",
34
40
  "preact": "^10",
35
41
  "resolve": "^1.20.0"
36
42
  },
@@ -38,15 +44,11 @@
38
44
  "preact": "^10"
39
45
  },
40
46
  "files": [
41
- "index.js",
42
- "lib",
43
- "utils",
44
- "scaffold",
45
- "README.md",
46
- "LICENSE"
47
+ "dist/**",
48
+ "scaffold"
47
49
  ],
48
50
  "devDependencies": {
49
- "fs-extra": "^10.0.0",
51
+ "@types/cssesc": "^3.0.2",
50
52
  "lodash": "^4.17.4",
51
53
  "prettier": "^2.3.2",
52
54
  "prettier-config-guestline": "2.0.0"
@@ -33,7 +33,6 @@
33
33
  "@testing-library/react": "^14.0.0",
34
34
  "@testing-library/user-event": "^14.4.3",
35
35
  "jsdom": "^21.1.1",
36
- "oc-template-preact": "0.0.2",
37
36
  "oc-template-preact-compiler": "0.2.0",
38
37
  "preact": "^10.13.2",
39
38
  "typescript": "5.0.2",
@@ -1,6 +1,6 @@
1
1
  import { describe, it, afterEach, beforeEach, expect, vi } from 'vitest';
2
2
  import { render, screen } from '@testing-library/react';
3
- import { DataProvider } from 'oc-template-preact-compiler/utils/useData';
3
+ import { DataProvider } from 'oc-template-preact-compiler/dist/utils/useData';
4
4
 
5
5
  import App from './App';
6
6
 
@@ -1,5 +1,5 @@
1
1
  import { useState } from 'preact/hooks';
2
- import { useData } from 'oc-template-preact-compiler/utils/useData';
2
+ import { useData } from 'oc-template-preact-compiler/dist/utils/useData';
3
3
  import styles from './styles.css';
4
4
  import type { AdditionalData, ClientProps } from './types';
5
5
 
@@ -1,2 +1 @@
1
- /// <reference types="oc-template-preact" />
2
- /// <reference types="vite/client" />
1
+ /// <reference types="oc-vite/client" />
package/index.js DELETED
@@ -1,11 +0,0 @@
1
- 'use strict';
2
-
3
- const compile = require('./lib/compile');
4
- const template = require('oc-template-preact');
5
-
6
- module.exports = {
7
- compile,
8
- getCompiledTemplate: template.getCompiledTemplate,
9
- getInfo: template.getInfo,
10
- render: template.render
11
- };
package/lib/compile.js DELETED
@@ -1,55 +0,0 @@
1
- 'use strict';
2
-
3
- const createCompile = require('oc-generic-template-compiler').createCompile;
4
- const compileStatics = require('oc-statics-compiler');
5
- const getInfo = require('oc-template-preact').getInfo;
6
- const { preact } = require('@preact/preset-vite');
7
- const { viteView, viteServer } = require('oc-vite-compiler');
8
-
9
- const verifyTypeScriptSetup = require('./verifyConfig');
10
- const higherOrderServerTemplate = require('./higherOrderServerTemplate');
11
- const preactOCProviderTemplate = require('./preactOCProviderTemplate');
12
- const htmlTemplate = require('./htmlTemplate');
13
-
14
- const compiler = createCompile({
15
- compileView: (options, cb) =>
16
- viteView(
17
- {
18
- ...options,
19
- plugins: [preact()],
20
- viewWrapper: ({ viewPath }) => preactOCProviderTemplate({ viewPath }),
21
- htmlTemplate,
22
- externals: getInfo().externals
23
- },
24
- cb
25
- ),
26
- compileServer: (options, cb) =>
27
- viteServer({ ...options, serverWrapper: higherOrderServerTemplate }, cb),
28
- compileStatics,
29
- getInfo
30
- });
31
-
32
- const hasTsExtension = (file) => !!file.match(/\.tsx?$/);
33
-
34
- // OPTIONS
35
- // =======
36
- // componentPath
37
- // componentPackage,
38
- // logger,
39
- // minify
40
- // ocPackage
41
- // publishPath
42
- // verbose,
43
- // watch,
44
- // production
45
- module.exports = function compile(options, callback) {
46
- const viewFileName = options.componentPackage.oc.files.template.src;
47
- const serverFileName = options.componentPackage.oc.files.data;
48
- const usingTypescript = hasTsExtension(viewFileName) || hasTsExtension(serverFileName);
49
-
50
- if (usingTypescript) {
51
- verifyTypeScriptSetup(options.componentPath);
52
- }
53
-
54
- return compiler(options, callback);
55
- };
@@ -1,28 +0,0 @@
1
- const removeExtension = (path) => path.replace(/\.(j|t)sx?$/, '');
2
-
3
- const higherOrderServerTemplate = ({ serverPath, componentName, componentVersion }) => `
4
- import { data as dataProvider } from '${removeExtension(serverPath)}';
5
-
6
- export const data = (context : any, callback : (error: any, data?: any) => void) => {
7
- dataProvider(context, (error: any, model: any) => {
8
- if (error) {
9
- return callback(error);
10
- }
11
- const props = Object.assign({}, model, {
12
- _staticPath: context.staticPath,
13
- _baseUrl: context.baseUrl,
14
- _componentName: "${componentName}",
15
- _componentVersion: "${componentVersion}"
16
- });
17
- const srcPathHasProtocol = context.staticPath.indexOf("http") === 0;
18
- const srcPath = srcPathHasProtocol ? context.staticPath : ("https:" + context.staticPath);
19
- return callback(null, Object.assign({}, {
20
- preactComponent: {
21
- props
22
- }
23
- }));
24
- });
25
- }
26
- `;
27
-
28
- module.exports = higherOrderServerTemplate;
package/lib/oc-app.d.ts DELETED
@@ -1,72 +0,0 @@
1
- interface OC {
2
- conf: {
3
- templates: Array<{
4
- type: string;
5
- externals: string[];
6
- }>;
7
- };
8
- cmd: {
9
- push: (cb: (oc: OC) => void) => void;
10
- };
11
- events: {
12
- on: (eventName: string, fn: (...data: any[]) => void) => void;
13
- off: (eventName: string, fn?: (...data: any[]) => void) => void;
14
- fire: (eventName: string, data?: any) => void;
15
- reset: () => void;
16
- };
17
- renderNestedComponent: (ocElement: HTMLElement, cb: () => void) => void;
18
- }
19
-
20
- declare global {
21
- interface Window {
22
- oc: OC;
23
- }
24
-
25
- namespace JSX {
26
- interface IntrinsicElements {
27
- 'oc-component': React.DetailedHTMLProps<
28
- React.HTMLAttributes<HTMLElement> & { href: string },
29
- HTMLElement
30
- >;
31
- }
32
- }
33
- }
34
-
35
- export interface AcceptLanguage {
36
- code: string;
37
- script?: any;
38
- region: string;
39
- quality: number;
40
- }
41
-
42
- export interface Env {
43
- name: string;
44
- }
45
-
46
- export interface Plugins {}
47
-
48
- export interface External {
49
- global: string;
50
- url: string;
51
- name: string;
52
- }
53
-
54
- export interface Template {
55
- type: string;
56
- version: string;
57
- externals: External[];
58
- }
59
-
60
- export interface Context<T = any, E = Env> {
61
- acceptLanguage: AcceptLanguage[];
62
- baseUrl: string;
63
- env: E;
64
- params: T;
65
- plugins: Plugins;
66
- requestHeaders: Record<string, string>;
67
- requestIp: string;
68
- setEmptyResponse: () => void;
69
- setHeader: (header: string, value: string) => void;
70
- staticPath: string;
71
- templates: Template[];
72
- }
@@ -1,211 +0,0 @@
1
- const chalk = require('chalk');
2
- const fs = require('fs');
3
- const resolve = require('resolve');
4
- const path = require('path');
5
- const os = require('os');
6
- const immer = require('immer').produce;
7
-
8
- function writeJson(fileName, object) {
9
- fs.writeFileSync(fileName, JSON.stringify(object, null, 2).replace(/\n/g, os.EOL) + os.EOL);
10
- }
11
-
12
- function verifyTypeScriptSetup(componentPath) {
13
- const paths = {
14
- appTsConfig: path.resolve(componentPath, 'tsconfig.json'),
15
- yarnLockFile: path.resolve(componentPath, 'yarn.lock'),
16
- appNodeModules: path.resolve(componentPath, 'node_modules'),
17
- appTypeDeclarations: path.resolve(componentPath, 'src', 'oc-app.d.ts')
18
- };
19
- let firstTimeSetup = false;
20
-
21
- if (!fs.existsSync(paths.appTsConfig)) {
22
- writeJson(paths.appTsConfig, {});
23
- firstTimeSetup = true;
24
- }
25
-
26
- const isYarn = fs.existsSync(paths.yarnLockFile);
27
-
28
- // Ensure typescript is installed
29
- let ts;
30
- try {
31
- ts = require(resolve.sync('typescript', {
32
- basedir: paths.appNodeModules
33
- }));
34
- } catch (_) {
35
- console.error(
36
- chalk.bold.red(
37
- `It looks like you're trying to use TypeScript but do not have ${chalk.bold(
38
- 'typescript'
39
- )} installed.`
40
- )
41
- );
42
- console.error(
43
- chalk.bold(
44
- 'Please install',
45
- chalk.cyan.bold('typescript'),
46
- 'by running',
47
- chalk.cyan.bold(isYarn ? 'yarn add typescript' : 'npm install typescript') + '.'
48
- )
49
- );
50
- console.error();
51
- process.exit(1);
52
- }
53
-
54
- const compilerOptions = {
55
- // These are suggested values and will be set when not present in the
56
- // tsconfig.json
57
- // 'parsedValue' matches the output value from ts.parseJsonConfigFileContent()
58
- target: {
59
- parsedValue: ts.ScriptTarget.ES5,
60
- suggested: 'es5'
61
- },
62
- lib: { suggested: ['dom', 'dom.iterable', 'esnext'] },
63
- allowJs: { suggested: true },
64
- skipLibCheck: { suggested: true },
65
- esModuleInterop: { suggested: true },
66
- allowSyntheticDefaultImports: { suggested: true },
67
- strict: { suggested: true },
68
- forceConsistentCasingInFileNames: { suggested: true },
69
- // TODO: Enable for v4.0 (#6936)
70
- // noFallthroughCasesInSwitch: { suggested: true },
71
-
72
- // These values are required and cannot be changed by the user
73
- // Keep this in sync with the rollup config
74
- module: {
75
- parsedValue: ts.ModuleKind.ESNext,
76
- value: 'esnext',
77
- reason: 'for import() and import/export'
78
- },
79
- moduleResolution: {
80
- parsedValue: ts.ModuleResolutionKind.NodeJs,
81
- value: 'node',
82
- reason: 'to match rollup resolution'
83
- },
84
- resolveJsonModule: { value: true, reason: 'to match rollup loader' },
85
- isolatedModules: { value: true, reason: 'implementation limitation' },
86
- jsx: {
87
- parsedValue: ts.JsxEmit.ReactJSX,
88
- suggested: 'react-jsx'
89
- },
90
- paths: { value: undefined, reason: 'aliased imports are not supported' }
91
- };
92
-
93
- const formatDiagnosticHost = {
94
- getCanonicalFileName: (fileName) => fileName,
95
- getCurrentDirectory: ts.sys.getCurrentDirectory,
96
- getNewLine: () => os.EOL
97
- };
98
-
99
- const messages = [];
100
- let appTsConfig;
101
- let parsedTsConfig;
102
- let parsedCompilerOptions;
103
- try {
104
- const { config: readTsConfig, error } = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile);
105
-
106
- if (error) {
107
- throw new Error(ts.formatDiagnostic(error, formatDiagnosticHost));
108
- }
109
-
110
- appTsConfig = readTsConfig;
111
-
112
- // Get TS to parse and resolve any "extends"
113
- // Calling this function also mutates the tsconfig above,
114
- // adding in "include" and "exclude", but the compilerOptions remain untouched
115
- let result;
116
- parsedTsConfig = immer(readTsConfig, (config) => {
117
- result = ts.parseJsonConfigFileContent(config, ts.sys, path.dirname(paths.appTsConfig));
118
- });
119
-
120
- if (result.errors && result.errors.length) {
121
- throw new Error(ts.formatDiagnostic(result.errors[0], formatDiagnosticHost));
122
- }
123
-
124
- parsedCompilerOptions = result.options;
125
- } catch (e) {
126
- if (e && e.name === 'SyntaxError') {
127
- console.error(
128
- chalk.red.bold(
129
- 'Could not parse',
130
- chalk.cyan('tsconfig.json') + '.',
131
- 'Please make sure it contains syntactically correct JSON.'
132
- )
133
- );
134
- }
135
-
136
- console.log(e && e.message ? `${e.message}` : '');
137
- process.exit(1);
138
- }
139
-
140
- if (appTsConfig.compilerOptions == null) {
141
- appTsConfig.compilerOptions = {};
142
- firstTimeSetup = true;
143
- }
144
-
145
- for (const option of Object.keys(compilerOptions)) {
146
- const { parsedValue, value, suggested, reason } = compilerOptions[option];
147
-
148
- const valueToCheck = parsedValue === undefined ? value : parsedValue;
149
- const coloredOption = chalk.cyan('compilerOptions.' + option);
150
-
151
- if (suggested != null) {
152
- if (parsedCompilerOptions[option] === undefined) {
153
- appTsConfig.compilerOptions[option] = suggested;
154
- messages.push(
155
- `${coloredOption} to be ${chalk.bold('suggested')} value: ${chalk.cyan.bold(
156
- suggested
157
- )} (this can be changed)`
158
- );
159
- }
160
- } else if (parsedCompilerOptions[option] !== valueToCheck) {
161
- appTsConfig.compilerOptions[option] = value;
162
- messages.push(
163
- `${coloredOption} ${chalk.bold(valueToCheck == null ? 'must not' : 'must')} be ${valueToCheck == null ? 'set' : chalk.cyan.bold(value)
164
- }` + (reason != null ? ` (${reason})` : '')
165
- );
166
- }
167
- }
168
-
169
- // tsconfig will have the merged "include" and "exclude" by this point
170
- if (parsedTsConfig.include == null) {
171
- appTsConfig.include = ['src'];
172
- messages.push(`${chalk.cyan('include')} should be ${chalk.cyan.bold('src')}`);
173
- }
174
-
175
- if (parsedTsConfig.exclude == null) {
176
- appTsConfig.exclude = ['src/_package'];
177
- messages.push(`${chalk.cyan('exclude')} should have ${chalk.cyan.bold('src/_package')}`);
178
- }
179
-
180
- if (messages.length > 0) {
181
- if (firstTimeSetup) {
182
- console.log(
183
- chalk.bold('Your', chalk.cyan('tsconfig.json'), 'has been populated with default values.')
184
- );
185
- console.log();
186
- } else {
187
- console.warn(
188
- chalk.bold(
189
- 'The following changes are being made to your',
190
- chalk.cyan('tsconfig.json'),
191
- 'file:'
192
- )
193
- );
194
- messages.forEach((message) => {
195
- console.warn(' - ' + message);
196
- });
197
- console.warn();
198
- }
199
- writeJson(paths.appTsConfig, appTsConfig);
200
- }
201
-
202
- // Reference `oc-template-preact-compiler` types
203
- if (!fs.existsSync(paths.appTypeDeclarations)) {
204
- fs.writeFileSync(
205
- paths.appTypeDeclarations,
206
- `/// <reference types="oc-template-preact" />${os.EOL}`
207
- );
208
- }
209
- }
210
-
211
- module.exports = verifyTypeScriptSetup;
@@ -1,13 +0,0 @@
1
- module.exports = {
2
- env: {
3
- commonjs: false
4
- },
5
- parserOptions: {
6
- ecmaVersion: 'latest',
7
- sourceType: 'module',
8
- ecmaFeatures: {
9
- jsx: true
10
- }
11
- },
12
- extends: '../../../.eslintrc.js'
13
- };
package/utils/useData.tsx DELETED
@@ -1,40 +0,0 @@
1
- import { createContext } from 'preact';
2
- import { useCallback, useContext } from 'preact/hooks';
3
-
4
- const DataContext = createContext<any>({});
5
-
6
- type Data<T = any> = T & {
7
- getData(parameters: T, cb: (err: Error | null, data: any) => void): void;
8
- getSetting(setting: 'name' | 'version' | 'baseUrl' | 'staticPath'): string;
9
- };
10
-
11
- type PromiseData<T = any> = T & {
12
- getData<O = any>(parameters?: Partial<T>): Promise<O>;
13
- getSetting(setting: 'name' | 'version' | 'baseUrl' | 'staticPath'): string;
14
- };
15
-
16
- export const DataProvider = ({ children, ...props }: any) => {
17
- // @ts-ignore children props
18
- return <DataContext.Provider value={props}>{children}</DataContext.Provider>;
19
- };
20
-
21
- export function useData<T = any>(): PromiseData<T> {
22
- const {
23
- value: { getData, ...rest }
24
- }: { value: Data<T> } = useContext(DataContext);
25
- const asyncGetData = useCallback(<O = any, I = any>(data: I) => {
26
- return new Promise<O>((resolve, reject) => {
27
- // @ts-ignore
28
- getData({ ...rest, ...data }, (err, newData) => {
29
- if (err) {
30
- reject(err);
31
- } else {
32
- resolve(newData);
33
- }
34
- });
35
- });
36
- }, []);
37
-
38
- // @ts-ignore
39
- return { getData: asyncGetData, ...rest };
40
- }