刘光辉
8 小时以前 cf11e63b659afcc9792ab3e395f1b45d844431a8
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
64
65
export const PLUGIN_GUID = 'asc.{7F4E8F35-5D66-47F8-A5B4-6AB3FAACF565}';
export const PLUGIN_VERSION = '0.1.0';
export const RECORD_FILL_SCOPE = 'onlyoffice:eln-record-fill';
export const RECORD_FILL_BIZ_MODULE = 'eln.record';
export const RECORD_FILL_BIZ_SCENE = 'eln.record.fill';
 
interface PluginContextBase {
  apiBaseUrl: string;
  bizDataId: string;
  canFill: boolean;
  documentId: string;
  pluginVersion: typeof PLUGIN_VERSION;
  ticket: string;
}
 
export type PluginContext = PluginContextBase & {
  bizModule: typeof RECORD_FILL_BIZ_MODULE;
  bizScene: typeof RECORD_FILL_BIZ_SCENE;
  scope: typeof RECORD_FILL_SCOPE;
};
 
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('插件运行上下文无效');
  const isRecordFill = options.scope === RECORD_FILL_SCOPE && options.bizModule === RECORD_FILL_BIZ_MODULE && options.bizScene === RECORD_FILL_BIZ_SCENE;
  if (
    !isHttpUrl(options.apiBaseUrl) ||
    !isNonEmptyString(options.ticket) ||
    !isNonEmptyString(options.documentId) ||
    !isNonEmptyString(options.bizDataId) ||
    !isRecordFill ||
    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,
  } as PluginContext;
}