@blocklet/pages-kit-runtime 0.1.2 → 0.1.5

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.
Files changed (31) hide show
  1. package/lib/cjs/tsconfig.tsbuildinfo +1 -1
  2. package/lib/esm/tsconfig.tsbuildinfo +1 -1
  3. package/lib/types/tsconfig.tsbuildinfo +1 -1
  4. package/package.json +3 -35
  5. package/lib/cjs/block-studio/build-lib.js +0 -95
  6. package/lib/cjs/block-studio/generate-wrapper-code.js +0 -123
  7. package/lib/cjs/block-studio/init-resource-router.js +0 -166
  8. package/lib/cjs/block-studio/plugins/_theme.js +0 -7
  9. package/lib/cjs/block-studio/plugins/index.js +0 -19
  10. package/lib/cjs/block-studio/plugins/vite-plugin-block-studio.js +0 -176
  11. package/lib/cjs/block-studio/plugins/vite-plugin-html-transform.js +0 -245
  12. package/lib/cjs/block-studio/plugins/vite-plugin-remote-script-localizer.js +0 -211
  13. package/lib/cjs/block-studio/utils.js +0 -53
  14. package/lib/esm/block-studio/build-lib.js +0 -89
  15. package/lib/esm/block-studio/generate-wrapper-code.js +0 -87
  16. package/lib/esm/block-studio/init-resource-router.js +0 -124
  17. package/lib/esm/block-studio/plugins/_theme.js +0 -4
  18. package/lib/esm/block-studio/plugins/index.js +0 -3
  19. package/lib/esm/block-studio/plugins/vite-plugin-block-studio.js +0 -140
  20. package/lib/esm/block-studio/plugins/vite-plugin-html-transform.js +0 -241
  21. package/lib/esm/block-studio/plugins/vite-plugin-remote-script-localizer.js +0 -175
  22. package/lib/esm/block-studio/utils.js +0 -43
  23. package/lib/types/block-studio/build-lib.d.ts +0 -3
  24. package/lib/types/block-studio/generate-wrapper-code.d.ts +0 -5
  25. package/lib/types/block-studio/init-resource-router.d.ts +0 -5
  26. package/lib/types/block-studio/plugins/_theme.d.ts +0 -1
  27. package/lib/types/block-studio/plugins/index.d.ts +0 -3
  28. package/lib/types/block-studio/plugins/vite-plugin-block-studio.d.ts +0 -6
  29. package/lib/types/block-studio/plugins/vite-plugin-html-transform.d.ts +0 -5
  30. package/lib/types/block-studio/plugins/vite-plugin-remote-script-localizer.d.ts +0 -8
  31. package/lib/types/block-studio/utils.d.ts +0 -14
@@ -1,175 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- /* eslint-disable no-console */
11
- import { createHash } from 'crypto';
12
- import { mkdir, rm, writeFile } from 'fs/promises';
13
- import * as path from 'path';
14
- export function initRemoteScriptLocalizerPlugin(options = {}) {
15
- const { tempDir = 'temp/remote-scripts', maxConcurrent = 5, timeout = 30000 } = options;
16
- let initialized = false;
17
- const downloadQueue = [];
18
- const initTempDir = () => __awaiter(this, void 0, void 0, function* () {
19
- try {
20
- yield rm(tempDir, { recursive: true, force: true });
21
- yield mkdir(tempDir, { recursive: true });
22
- initialized = true;
23
- }
24
- catch (error) {
25
- console.error('Failed to initialize temp directory:', error);
26
- throw error;
27
- }
28
- });
29
- const downloadWithTimeout = (url, ms) => __awaiter(this, void 0, void 0, function* () {
30
- const controller = new AbortController();
31
- const timeoutId = setTimeout(() => controller.abort(), ms);
32
- try {
33
- const response = yield fetch(url, { signal: controller.signal });
34
- clearTimeout(timeoutId);
35
- return response;
36
- }
37
- catch (error) {
38
- clearTimeout(timeoutId);
39
- throw error;
40
- }
41
- });
42
- const downloadScript = (url) => __awaiter(this, void 0, void 0, function* () {
43
- var _a;
44
- try {
45
- const response = yield downloadWithTimeout(url, timeout);
46
- if (!response.ok) {
47
- throw new Error(`Failed to fetch ${url}: ${response.statusText}`);
48
- }
49
- const content = yield response.text();
50
- const hash = createHash('md5').update(url).digest('hex').slice(0, 8);
51
- const filename = `${hash}-${((_a = url
52
- .split('/')
53
- .pop()) === null || _a === void 0 ? void 0 : _a.replace(/[^a-zA-Z0-9.-]/g, '_')) || 'script.js'}`;
54
- const localPath = path.join(tempDir, filename);
55
- yield writeFile(localPath, content, 'utf-8');
56
- return localPath;
57
- }
58
- catch (error) {
59
- console.error(`Error downloading script from ${url}:`, error);
60
- throw error;
61
- }
62
- });
63
- const processDownloads = (urls) => __awaiter(this, void 0, void 0, function* () {
64
- const results = new Map();
65
- // Process downloads in chunks to limit concurrency
66
- for (let i = 0; i < urls.length; i += maxConcurrent) {
67
- const chunk = urls.slice(i, i + maxConcurrent);
68
- const promises = chunk.map((url) => __awaiter(this, void 0, void 0, function* () {
69
- try {
70
- const localPath = yield downloadScript(url);
71
- results.set(url, localPath);
72
- }
73
- catch (error) {
74
- console.warn(`Failed to download ${url}:`, error);
75
- }
76
- }));
77
- downloadQueue.push(...promises);
78
- yield Promise.all(promises);
79
- }
80
- return results;
81
- });
82
- return {
83
- name: 'remote-script-localizer',
84
- enforce: 'pre',
85
- // 添加 resolveId 钩子来处理虚拟模块
86
- resolveId(id, importer) {
87
- console.log('[remote-script-localizer] resolveId:', { id, importer });
88
- return null; // 让其他插件继续处理
89
- },
90
- // 添加 load 钩子来处理虚拟模块的加载
91
- load(id) {
92
- console.log('[remote-script-localizer] load:', id);
93
- return null; // 让其他插件继续处理
94
- },
95
- transform(code, id) {
96
- return __awaiter(this, void 0, void 0, function* () {
97
- // 添加调试日志
98
- console.log('[remote-script-localizer] transform:', {
99
- id,
100
- isVirtual: id.includes('\0'),
101
- codeLength: code.length,
102
- });
103
- // 检查文件类型
104
- const isJS = /\.[jt]sx?$/.test(id);
105
- const isHTML = /\.html$/.test(id);
106
- if (!isJS && !isHTML)
107
- return null;
108
- // 匹配多种远程脚本模式,包括模板字符串中的内容
109
- const patterns = [
110
- // 动态导入
111
- /import\s*\(\s*['"]https?:\/\/[^'"]+['"]\s*\)/g,
112
- // HTML script 标签 (包括转义的版本)
113
- /<script[^>]*src=["'](https?:\/\/[^"']+)["'][^>]*>(?:<\\\/script>)?/g,
114
- // 模板字符串中的 script 标签
115
- /`[^`]*<script[^>]*src=["'](https?:\/\/[^"']+)["'][^>]*>(?:<\\\/script>)?[^`]*`/g,
116
- // HTML link 标签
117
- /<link[^>]*href=["'](https?:\/\/[^"']+)["'][^>]*>/g,
118
- ];
119
- let hasRemoteUrls = false;
120
- let newCode = code;
121
- const urls = new Set();
122
- // 收集所有远程 URL
123
- patterns.forEach((pattern) => {
124
- var _a, _b;
125
- const matches = code.matchAll(pattern);
126
- for (const match of matches) {
127
- hasRemoteUrls = true;
128
- // 提取 URL(处理不同的匹配组)
129
- const url = match[1] || ((_b = (_a = match[0].match(/['"]https?:\/\/[^'"]+['"]/)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.slice(1, -1));
130
- if (url)
131
- urls.add(url);
132
- }
133
- });
134
- if (hasRemoteUrls) {
135
- console.log(`[remote-script-localizer] Found remote URLs in ${id}:`, [...urls]);
136
- const downloadResults = yield processDownloads([...urls]);
137
- downloadResults.forEach((localPath, url) => {
138
- // 替换模板字符串中的 script 标签
139
- newCode = newCode.replace(new RegExp(`<script([^>]*)src=["']${url}["']([^>]*)>(?:<\\\\/script>)?`, 'g'), `<script$1src="/${localPath}"$2></script>`);
140
- // 替换其他情况
141
- newCode = newCode.replace(new RegExp(`(['"\`])${url}\\1`, 'g'), `$1/${localPath}$1`);
142
- console.log(`[remote-script-localizer] Localized: ${url} -> ${localPath}`);
143
- });
144
- return {
145
- code: newCode,
146
- map: null,
147
- };
148
- }
149
- return null;
150
- });
151
- },
152
- buildStart() {
153
- return __awaiter(this, void 0, void 0, function* () {
154
- if (!initialized) {
155
- yield initTempDir();
156
- }
157
- });
158
- },
159
- buildEnd() {
160
- return __awaiter(this, void 0, void 0, function* () {
161
- // Wait for any remaining downloads to complete
162
- yield Promise.all(downloadQueue);
163
- // Clean up temp directory
164
- try {
165
- // await rm(tempDir, { recursive: true, force: true });
166
- // console.log('Cleaned up temporary remote scripts directory');
167
- }
168
- catch (error) {
169
- console.error('Failed to clean up temp directory:', error);
170
- }
171
- });
172
- },
173
- };
174
- }
175
- export default initRemoteScriptLocalizerPlugin;
@@ -1,43 +0,0 @@
1
- import { globSync } from 'glob';
2
- import path from 'path';
3
- const DEFAULT_BLOCK_ENTRY_FILES_PATTERN = 'src/**/index.{ts,tsx,html}';
4
- if (!process.env.BLOCK_ENTRY_FILES_PATTERN) {
5
- process.env.BLOCK_ENTRY_FILES_PATTERN = DEFAULT_BLOCK_ENTRY_FILES_PATTERN;
6
- }
7
- function normalizePattern(pattern) {
8
- return pattern.replace(/^[/\\]+/, ''); // Remove leading slashes
9
- }
10
- export function setBlockEntryFilesPattern(pattern) {
11
- process.env.BLOCK_ENTRY_FILES_PATTERN = normalizePattern(pattern);
12
- }
13
- export function getBlockEntryFilesPattern() {
14
- return process.env.BLOCK_ENTRY_FILES_PATTERN || DEFAULT_BLOCK_ENTRY_FILES_PATTERN;
15
- }
16
- export function findComponentFiles(options = {}) {
17
- const { cwd = process.cwd(), filter } = options;
18
- const files = globSync(getBlockEntryFilesPattern(), { cwd });
19
- return files
20
- .map((file) => {
21
- const blockName = getBlockName(file);
22
- const fullPath = path.resolve(cwd, file);
23
- const isHtml = file.endsWith('.html');
24
- return {
25
- file,
26
- blockName,
27
- fullPath,
28
- isHtml,
29
- };
30
- })
31
- .filter(({ blockName }) => !(filter === null || filter === void 0 ? void 0 : filter.length) || filter.includes(blockName || ''));
32
- }
33
- export function getBlockName(entry) {
34
- // First try to match index.{ts,tsx,html} pattern
35
- const indexMatch = entry.match(/(.*)\/index\.(ts|tsx|html)$/);
36
- if (indexMatch) {
37
- const [, pathWithoutIndex] = indexMatch;
38
- return path.basename(pathWithoutIndex || 'unknown');
39
- }
40
- // If not an index file, return the filename without extension
41
- return path.basename(entry, path.extname(entry));
42
- }
43
- export const logger = console;
@@ -1,3 +0,0 @@
1
- export declare function buildLib(options: {
2
- cwd?: string;
3
- }): Promise<void>;
@@ -1,5 +0,0 @@
1
- export declare function generateWrapperCode({ project, state }: any): Promise<{
2
- fileName: string;
3
- content: string;
4
- }[]>;
5
- export default generateWrapperCode;
@@ -1,5 +0,0 @@
1
- export declare function copyFile(src: string, dest: string): Promise<void>;
2
- export declare function copyDirectory(src: string, dest: string): Promise<void>;
3
- export declare function copyRecursive(src: string, dest: string): Promise<void>;
4
- export declare const initResourceRouter: import("express-ws").Router;
5
- export default initResourceRouter;
@@ -1 +0,0 @@
1
- export default function Theme(): import("react/jsx-runtime").JSX.Element;
@@ -1,3 +0,0 @@
1
- export * from './vite-plugin-block-studio';
2
- export * from './vite-plugin-html-transform';
3
- export * from './vite-plugin-remote-script-localizer';
@@ -1,6 +0,0 @@
1
- import type { Plugin } from 'vite';
2
- export declare function initBlockStudioPlugins(options?: {
3
- cwd?: string;
4
- entryFilesPattern?: string;
5
- }): Plugin[];
6
- export default initBlockStudioPlugins;
@@ -1,5 +0,0 @@
1
- import { Plugin } from 'vite';
2
- export declare const VIRTUAL_MODULE_ID = "virtual:html-preview";
3
- export declare const RESOLVED_VIRTUAL_MODULE_ID = "\0virtual:html-preview";
4
- export declare function initHtmlPreviewTransformPlugin(): Plugin;
5
- export default initHtmlPreviewTransformPlugin;
@@ -1,8 +0,0 @@
1
- import { Plugin } from 'vite';
2
- interface RemoteScriptLocalizerOptions {
3
- tempDir?: string;
4
- maxConcurrent?: number;
5
- timeout?: number;
6
- }
7
- export declare function initRemoteScriptLocalizerPlugin(options?: RemoteScriptLocalizerOptions): Plugin;
8
- export default initRemoteScriptLocalizerPlugin;
@@ -1,14 +0,0 @@
1
- export interface GlobOptions {
2
- cwd?: string;
3
- filter?: string[];
4
- }
5
- export declare function setBlockEntryFilesPattern(pattern: string): void;
6
- export declare function getBlockEntryFilesPattern(): string;
7
- export declare function findComponentFiles(options?: GlobOptions): {
8
- file: string;
9
- blockName: string;
10
- fullPath: string;
11
- isHtml: boolean;
12
- }[];
13
- export declare function getBlockName(entry: string): string;
14
- export declare const logger: Console;