刘光辉
14 小时以前 0dfe84494048ce27ba8449831782128412d3eb13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
export const PLUGIN_GUID = 'asc.{7F4E8F35-5D66-47F8-A5B4-6AB3FAACF565}';
export const PLUGIN_VERSION = '0.1.0';
export const PLUGIN_SCOPE = 'onlyoffice:eln-template-fill';
export const PLUGIN_BIZ_MODULE = 'eln.template';
export const PLUGIN_BIZ_SCENE = 'eln.template.fill';
 
export interface PluginContext {
  apiBaseUrl: string;
  bizDataId: string;
  bizModule: typeof PLUGIN_BIZ_MODULE;
  bizScene: typeof PLUGIN_BIZ_SCENE;
  canFill: boolean;
  documentId: string;
  pluginVersion: typeof PLUGIN_VERSION;
  scope: typeof PLUGIN_SCOPE;
  ticket: string;
}
 
function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}
 
function isNonEmptyString(value: unknown): value is string {
  return typeof value === 'string' && value.trim().length > 0;
}
 
function isHttpUrl(value: unknown): value is string {
  if (!isNonEmptyString(value)) return false;
  try {
    const parsed = new URL(value);
    return ['http:', 'https:'].includes(parsed.protocol) && !parsed.username && !parsed.password && !parsed.search && !parsed.hash;
  } catch {
    return false;
  }
}
 
export function parsePluginContext(options: unknown): PluginContext {
  if (!isRecord(options)) throw new Error('插件运行上下文无效');
  if (
    !isHttpUrl(options.apiBaseUrl) ||
    !isNonEmptyString(options.ticket) ||
    options.scope !== PLUGIN_SCOPE ||
    !isNonEmptyString(options.documentId) ||
    !isNonEmptyString(options.bizDataId) ||
    options.bizModule !== PLUGIN_BIZ_MODULE ||
    options.bizScene !== PLUGIN_BIZ_SCENE ||
    options.pluginVersion !== PLUGIN_VERSION ||
    typeof options.canFill !== 'boolean'
  ) {
    throw new Error('插件运行上下文无效');
  }
  return {
    apiBaseUrl: options.apiBaseUrl.replace(/\/+$/u, ''),
    ticket: options.ticket,
    scope: options.scope,
    documentId: options.documentId,
    bizDataId: options.bizDataId,
    bizModule: options.bizModule,
    bizScene: options.bizScene,
    pluginVersion: options.pluginVersion,
    canFill: options.canFill,
  };
}