@next-core/runtime 1.56.1 → 1.57.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.
Files changed (39) hide show
  1. package/dist/cjs/internal/CustomTemplates/expandCustomTemplate.js +15 -5
  2. package/dist/cjs/internal/CustomTemplates/expandCustomTemplate.js.map +1 -1
  3. package/dist/cjs/internal/CustomTemplates/replaceSlotWithSlottedBricks.js +42 -0
  4. package/dist/cjs/internal/CustomTemplates/replaceSlotWithSlottedBricks.js.map +1 -0
  5. package/dist/cjs/internal/CustomTemplates/setupTemplateProxy.js +5 -1
  6. package/dist/cjs/internal/CustomTemplates/setupTemplateProxy.js.map +1 -1
  7. package/dist/cjs/internal/CustomTemplates/setupUseBrickInTemplate.js +13 -4
  8. package/dist/cjs/internal/CustomTemplates/setupUseBrickInTemplate.js.map +1 -1
  9. package/dist/cjs/internal/Renderer.js +5 -2
  10. package/dist/cjs/internal/Renderer.js.map +1 -1
  11. package/dist/cjs/internal/Router.js +9 -1
  12. package/dist/cjs/internal/Router.js.map +1 -1
  13. package/dist/cjs/internal/data/DataStore.js +23 -10
  14. package/dist/cjs/internal/data/DataStore.js.map +1 -1
  15. package/dist/cjs/internal/data/resolveDataStore.js +12 -5
  16. package/dist/cjs/internal/data/resolveDataStore.js.map +1 -1
  17. package/dist/cjs/internal/interfaces.js.map +1 -1
  18. package/dist/esm/internal/CustomTemplates/expandCustomTemplate.js +15 -5
  19. package/dist/esm/internal/CustomTemplates/expandCustomTemplate.js.map +1 -1
  20. package/dist/esm/internal/CustomTemplates/replaceSlotWithSlottedBricks.js +36 -0
  21. package/dist/esm/internal/CustomTemplates/replaceSlotWithSlottedBricks.js.map +1 -0
  22. package/dist/esm/internal/CustomTemplates/setupTemplateProxy.js +5 -2
  23. package/dist/esm/internal/CustomTemplates/setupTemplateProxy.js.map +1 -1
  24. package/dist/esm/internal/CustomTemplates/setupUseBrickInTemplate.js +13 -4
  25. package/dist/esm/internal/CustomTemplates/setupUseBrickInTemplate.js.map +1 -1
  26. package/dist/esm/internal/Renderer.js +5 -2
  27. package/dist/esm/internal/Renderer.js.map +1 -1
  28. package/dist/esm/internal/Router.js +9 -1
  29. package/dist/esm/internal/Router.js.map +1 -1
  30. package/dist/esm/internal/data/DataStore.js +23 -10
  31. package/dist/esm/internal/data/DataStore.js.map +1 -1
  32. package/dist/esm/internal/data/resolveDataStore.js +12 -5
  33. package/dist/esm/internal/data/resolveDataStore.js.map +1 -1
  34. package/dist/esm/internal/interfaces.js.map +1 -1
  35. package/dist/types/internal/CustomTemplates/replaceSlotWithSlottedBricks.d.ts +3 -0
  36. package/dist/types/internal/CustomTemplates/setupTemplateProxy.d.ts +3 -2
  37. package/dist/types/internal/data/DataStore.d.ts +5 -0
  38. package/dist/types/internal/interfaces.d.ts +1 -0
  39. package/package.json +2 -2
@@ -8,6 +8,7 @@ exports.DataStore = void 0;
8
8
  var _general = require("@next-core/utils/general");
9
9
  var _storyboard = require("@next-core/utils/storyboard");
10
10
  var _eventTarget = _interopRequireDefault(require("@ungap/event-target"));
11
+ var _lodash = require("lodash");
11
12
  var _bindListeners = require("../bindListeners.js");
12
13
  var _checkIf = require("../compute/checkIf.js");
13
14
  var _computeRealValue = require("../compute/computeRealValue.js");
@@ -30,6 +31,7 @@ class DataStore {
30
31
  batchUpdateContextsNames = [];
31
32
  rendererContext;
32
33
  routeMap = new WeakMap();
34
+ routeStackMap = new WeakMap();
33
35
 
34
36
  // 把 `rendererContext` 放在参数列表的最后,并作为可选,以减少测试文件的调整
35
37
  constructor(type, hostBrick, rendererContext, stateStoreId) {
@@ -203,6 +205,16 @@ class DataStore {
203
205
  define(dataConfs, runtimeContext, asyncHostPropertyEntries, routePath) {
204
206
  if (Array.isArray(dataConfs) && dataConfs.length > 0) {
205
207
  const pending = (0, _resolveDataStore.resolveDataStore)(dataConfs, dataConf => this.resolve(dataConf, runtimeContext, asyncHostPropertyEntries, routePath), this.type, (0, _isStrictMode.isStrictMode)(runtimeContext));
208
+ if (Array.isArray(routePath)) {
209
+ for (const route of routePath) {
210
+ const stack = this.routeStackMap.get(route);
211
+ if (stack) {
212
+ stack.add(pending);
213
+ } else {
214
+ this.routeStackMap.set(route, new Set([pending]));
215
+ }
216
+ }
217
+ }
206
218
  this.pendingStack.push(pending);
207
219
  }
208
220
  }
@@ -225,16 +237,6 @@ class DataStore {
225
237
  }
226
238
  }
227
239
  async waitForAll() {
228
- // Silent each pending contexts, since the error is handled by batched `pendingResult`
229
- for (const {
230
- pendingContexts
231
- } of this.pendingStack) {
232
- for (const p of pendingContexts.values()) {
233
- p.catch(() => {
234
- /* No-op */
235
- });
236
- }
237
- }
238
240
  for (const {
239
241
  pendingResult
240
242
  } of this.pendingStack) {
@@ -381,6 +383,11 @@ class DataStore {
381
383
  }
382
384
  return true;
383
385
  }
386
+
387
+ /**
388
+ * For sub-routes to be incrementally rendered,
389
+ * dispose their data and pending tasks.
390
+ */
384
391
  disposeDataInRoutes(routes) {
385
392
  for (const route of routes) {
386
393
  const names = this.routeMap.get(route);
@@ -388,6 +395,12 @@ class DataStore {
388
395
  for (const name of names) {
389
396
  this.data.delete(name);
390
397
  }
398
+ this.routeMap.delete(route);
399
+ }
400
+ const stack = this.routeStackMap.get(route);
401
+ if (stack !== undefined) {
402
+ (0, _lodash.pull)(this.pendingStack, ...stack);
403
+ this.routeStackMap.delete(route);
391
404
  }
392
405
  }
393
406
  }
@@ -1 +1 @@
1
- {"version":3,"file":"DataStore.js","names":["_general","require","_storyboard","_eventTarget","_interopRequireDefault","_bindListeners","_checkIf","_computeRealValue","_resolveData","_resolveDataStore","_handleHttpError","_computeRealProperties","_Runtime","_realTimeDataInspect","_isStrictMode","supportContextResolveTriggerBrickLifeCycle","DataStore","type","data","Map","changeEventType","pendingStack","hostBrick","stateStoreId","batchUpdate","batchUpdateContextsNames","rendererContext","routeMap","WeakMap","constructor","getAllValues","Object","fromEntries","entries","map","name","value","getValue","_this$data$get","get","notifyRealTimeDataChange","realTimeDataInspectRoot","tplStateStoreId","callRealTimeDataInspectHooks","changeType","detail","getAffectListByContext","affectNames","forEach","key","deps","isInDeps","some","item","includes","push","shift","Set","updateValues","values","method","argsFactory","length","Error","updateContexts","affectContexts","affectDepsContextNames","arg","updateContextItem","updateValue","filter","affectContextItem","triggerEvent","contexts","_context$eventTarget","context","eventTarget","dispatchEvent","CustomEvent","callback","callbackRuntimeContext","useResolve","promise","loaded","Promise","resolve","loading","shouldDismiss","error","_this$rendererContext","renderId","_internalApiGetRenderId","load","cache","then","val","finishLoad","err","handleHttpError","callbackFactory","eventCallbackFactory","isObject","assign","console","warn","define","dataConfs","runtimeContext","asyncHostPropertyEntries","routePath","Array","isArray","pending","resolveDataStore","dataConf","isStrictMode","onChange","dataName","listener","_this$data$get2","addEventListener","removeEventListener","waitFor","dataNames","pendingContexts","all","ctx","p","waitForAll","catch","pendingResult","mountAsyncData","route","_this$routeMap$get","async","has","asyncMounted","asyncCheckIf","expose","computePropertyValue","trackConditionalResolve","resolvePolicy","undefined","hasFallbackValue","hasOwnProperty","track","strictCollectMemberUsage","if","size","resolveConf","transform","options","_this$rendererContext2","resolveData","lazy","asyncComputeRealValue","newData","EventTarget","trigger","_this$rendererContext3","registerArbitraryLifeCycle","listenerFactory","dep","batchAddListener","checkIf","computeRealValue","e","set","names","add","disposeDataInRoutes","routes","delete","contextConf","event","exports"],"sources":["../../../../src/internal/data/DataStore.ts"],"sourcesContent":["import type {\n BatchUpdateContextItem,\n BrickEventHandlerCallback,\n ContextConf,\n ContextResolveTriggerBrickLifeCycle,\n RouteConf,\n} from \"@next-core/types\";\nimport { hasOwnProperty, isObject } from \"@next-core/utils/general\";\nimport { strictCollectMemberUsage } from \"@next-core/utils/storyboard\";\nimport EventTarget from \"@ungap/event-target\";\nimport { eventCallbackFactory, listenerFactory } from \"../bindListeners.js\";\nimport { asyncCheckIf, checkIf } from \"../compute/checkIf.js\";\nimport {\n asyncComputeRealValue,\n computeRealValue,\n} from \"../compute/computeRealValue.js\";\nimport { ResolveOptions, resolveData } from \"./resolveData.js\";\nimport { resolveDataStore } from \"./resolveDataStore.js\";\nimport type {\n AsyncPropertyEntry,\n RuntimeBrick,\n RuntimeContext,\n} from \"../interfaces.js\";\nimport { handleHttpError } from \"../../handleHttpError.js\";\nimport type { RendererContext } from \"../RendererContext.js\";\nimport { computePropertyValue } from \"../compute/computeRealProperties.js\";\nimport { _internalApiGetRenderId } from \"../Runtime.js\";\nimport {\n callRealTimeDataInspectHooks,\n realTimeDataInspectRoot,\n} from \"./realTimeDataInspect.js\";\nimport { isStrictMode } from \"../../isStrictMode.js\";\n\nconst supportContextResolveTriggerBrickLifeCycle = [\n \"onBeforePageLoad\",\n \"onPageLoad\",\n \"onBeforePageLeave\",\n \"onPageLeave\",\n \"onAnchorLoad\",\n \"onAnchorUnload\",\n] as ContextResolveTriggerBrickLifeCycle[];\n\nexport type DataStoreType = \"CTX\" | \"STATE\" | \"FORM_STATE\";\n\nexport interface DataStoreItem {\n name: string;\n value: unknown;\n eventTarget: EventTarget;\n useResolve?: boolean;\n loaded?: boolean;\n loading?: Promise<unknown>;\n load?: (options?: ResolveOptions) => Promise<unknown>;\n async?: boolean;\n asyncMounted?: boolean;\n deps: string[];\n}\n\nexport class DataStore<T extends DataStoreType = \"CTX\"> {\n private readonly type: T;\n private readonly data = new Map<string, DataStoreItem>();\n private readonly changeEventType: string;\n private readonly pendingStack: Array<ReturnType<typeof resolveDataStore>> =\n [];\n public readonly hostBrick?: RuntimeBrick;\n private readonly stateStoreId?: string;\n private batchUpdate = false;\n private batchUpdateContextsNames: string[] = [];\n private readonly rendererContext?: RendererContext;\n private routeMap = new WeakMap<RouteConf, Set<string>>();\n\n // 把 `rendererContext` 放在参数列表的最后,并作为可选,以减少测试文件的调整\n constructor(\n type: T,\n hostBrick?: RuntimeBrick,\n rendererContext?: RendererContext,\n stateStoreId?: string\n ) {\n this.type = type;\n this.changeEventType =\n this.type === \"FORM_STATE\"\n ? \"formstate.change\"\n : this.type === \"STATE\"\n ? \"state.change\"\n : \"context.change\";\n this.hostBrick = hostBrick;\n this.rendererContext = rendererContext;\n this.stateStoreId = stateStoreId;\n }\n\n getAllValues(): Record<string, unknown> {\n return Object.fromEntries(\n [...this.data.entries()].map(([name, { value }]) => [name, value])\n );\n }\n\n getValue(name: string): unknown {\n return this.data.get(name)?.value;\n }\n\n private notifyRealTimeDataChange(name: string, value: unknown) {\n if (realTimeDataInspectRoot) {\n const { tplStateStoreId } = realTimeDataInspectRoot;\n if (\n tplStateStoreId\n ? this.type === \"STATE\" && this.stateStoreId === tplStateStoreId\n : this.type === \"CTX\"\n ) {\n callRealTimeDataInspectHooks({\n changeType: \"update\",\n tplStateStoreId,\n detail: {\n name,\n value,\n },\n });\n }\n }\n }\n\n private getAffectListByContext(name: string): string[] {\n const affectNames = [name];\n this.data.forEach((value, key) => {\n if (value.deps) {\n const isInDeps = value.deps.some((item) => affectNames.includes(item));\n isInDeps &&\n affectNames.push(key) &&\n affectNames.push(...this.getAffectListByContext(key));\n }\n });\n affectNames.shift();\n return [...new Set(affectNames)];\n }\n\n updateValues(\n values: BatchUpdateContextItem[],\n method: \"assign\" | \"replace\",\n argsFactory: (arg: unknown[]) => BatchUpdateContextItem\n ): void {\n this.batchUpdate = true;\n this.batchUpdateContextsNames = values.map((item) => item.name);\n if (\n [...new Set(this.batchUpdateContextsNames)].length !==\n this.batchUpdateContextsNames.length\n ) {\n throw new Error(`Batch update not allow to update same item`);\n }\n\n const updateContexts: Record<string, DataStoreItem> = {};\n const affectContexts: Record<string, DataStoreItem> = {};\n const affectDepsContextNames: string[] = [];\n\n values.forEach((arg) => {\n const { name, value } = argsFactory([arg]);\n const updateContextItem = this.data.get(name);\n affectDepsContextNames.push(...this.getAffectListByContext(name));\n updateContextItem && (updateContexts[name] = updateContextItem);\n this.updateValue(name as string, value, method);\n });\n\n affectDepsContextNames\n .filter((item) => !updateContexts[item])\n .forEach((name) => {\n const affectContextItem = this.data.get(name);\n affectContextItem && (affectContexts[name] = affectContextItem);\n });\n\n const triggerEvent = (contexts: Record<string, DataStoreItem>): void => {\n for (const key in contexts) {\n const context = contexts[key];\n context.eventTarget?.dispatchEvent(\n new CustomEvent(this.changeEventType, {\n detail: context.value,\n })\n );\n }\n };\n\n triggerEvent(updateContexts);\n triggerEvent(affectContexts);\n\n this.batchUpdate = false;\n\n return;\n }\n\n updateValue(\n name: string,\n value: unknown,\n method: \"assign\" | \"replace\" | \"refresh\" | \"load\",\n callback?: BrickEventHandlerCallback,\n callbackRuntimeContext?: RuntimeContext\n ): void {\n const item = this.data.get(name);\n if (!item) {\n throw new Error(`${this.type} '${name}' is not defined`);\n }\n\n if (method === \"refresh\" || method === \"load\") {\n if (!item.useResolve) {\n throw new Error(\n `You can not ${method} \"${this.type}.${name}\" which is not using resolve`\n );\n }\n\n let promise: Promise<unknown> | undefined;\n if (method === \"load\") {\n // Try to reuse previous request when calling `load`.\n if (item.loaded) {\n promise = Promise.resolve(item.value);\n } else if (item.loading) {\n promise = item.loading;\n }\n }\n\n const shouldDismiss = (error: unknown) => {\n // If render twice immediately, flow API contracts maybe cleared before\n // the second rendering, while the page load handlers of the first\n // rendering can't be cancelled, which throws `FlowApiNotFoundError`.\n // So we ignore error reporting for this case.\n let renderId: string | undefined;\n return (\n (error as Error)?.name === \"FlowApiNotFoundError\" &&\n !!(renderId = this.rendererContext?.renderId) &&\n renderId !== _internalApiGetRenderId()\n );\n };\n\n if (!promise) {\n promise = item.loading = item.load!({\n cache: method === \"load\" ? \"default\" : \"reload\",\n ...(value as ResolveOptions),\n });\n // Do not use the chained promise, since the callbacks need the original promise.\n promise.then(\n (val) => {\n this.finishLoad(item, val);\n },\n (err) => {\n // Let users override error handling.\n if (item.useResolve && !shouldDismiss(err) && !callback?.error) {\n handleHttpError(err);\n }\n }\n );\n }\n\n if (callback) {\n const callbackFactory = eventCallbackFactory(\n callback,\n callbackRuntimeContext!\n );\n\n promise.then(\n (val) => {\n callbackFactory(\"success\")({ value: val });\n callbackFactory(\"finally\")();\n },\n (err) => {\n if (!shouldDismiss(err) && callback.error) {\n callbackFactory(\"error\")(err);\n }\n callbackFactory(\"finally\")();\n }\n );\n }\n\n return;\n }\n\n if (method === \"replace\") {\n item.value = value;\n } else {\n if (isObject(item.value)) {\n Object.assign(item.value, value);\n } else {\n // eslint-disable-next-line no-console\n console.warn(\n `Non-object current value of \"${this.type}.${name}\" for \"context.assign\", try \"context.replace\" instead.`\n );\n item.value = value;\n }\n }\n\n if (this.batchUpdate) return;\n\n item.eventTarget.dispatchEvent(\n new CustomEvent(this.changeEventType, {\n detail: item.value,\n })\n );\n }\n\n private finishLoad(item: DataStoreItem, value: unknown) {\n if (!item.useResolve) {\n // This happens when a tracked conditional resolve switches from\n // resolve to fallback after an dep update triggered refresh but\n // before it's been resolved.\n return;\n }\n item.loaded = true;\n item.value = value;\n item.eventTarget.dispatchEvent(\n new CustomEvent(this.changeEventType, {\n detail: value,\n })\n );\n }\n\n define(\n dataConfs: ContextConf[] | undefined,\n runtimeContext: RuntimeContext,\n asyncHostPropertyEntries?: AsyncPropertyEntry[],\n routePath?: RouteConf[]\n ): void {\n if (Array.isArray(dataConfs) && dataConfs.length > 0) {\n const pending = resolveDataStore(\n dataConfs,\n (dataConf: ContextConf) =>\n this.resolve(\n dataConf,\n runtimeContext,\n asyncHostPropertyEntries,\n routePath\n ),\n this.type,\n isStrictMode(runtimeContext)\n );\n this.pendingStack.push(pending);\n }\n }\n\n onChange(dataName: string, listener: EventListener): () => void {\n const eventTarget = this.data.get(dataName)?.eventTarget;\n eventTarget?.addEventListener(this.changeEventType, listener);\n return () => {\n eventTarget?.removeEventListener(this.changeEventType, listener);\n };\n }\n\n async waitFor(dataNames: string[] | Set<string>): Promise<void> {\n for (const { pendingContexts } of this.pendingStack) {\n await Promise.all(\n [...dataNames].map((ctx) => {\n const p = pendingContexts.get(ctx);\n return p;\n })\n );\n }\n }\n\n async waitForAll(): Promise<void> {\n // Silent each pending contexts, since the error is handled by batched `pendingResult`\n for (const { pendingContexts } of this.pendingStack) {\n for (const p of pendingContexts.values()) {\n p.catch(() => {\n /* No-op */\n });\n }\n }\n for (const { pendingResult } of this.pendingStack) {\n await pendingResult;\n }\n }\n\n /**\n * After mount, dispatch the change event when an async data is loaded.\n *\n * If param `route` is present, handle data defined in that route (or its descendants) only.\n */\n mountAsyncData(route?: RouteConf) {\n this.data.forEach((item) => {\n if (item.async && (!route || this.routeMap.get(route)?.has(item.name))) {\n // istanbul ignore next\n if (item.asyncMounted) {\n // eslint-disable-next-line no-console\n console.error(\n `Async data \"${item.name}\" already mounted. This is a bug of Brick Next, please report it.`\n );\n return;\n }\n item.asyncMounted = true;\n // An async data always has `loading`\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n item.loading!.then((value) => {\n this.finishLoad(item, value);\n });\n }\n });\n }\n\n private async resolve(\n dataConf: ContextConf,\n runtimeContext: RuntimeContext,\n asyncHostPropertyEntries?: AsyncPropertyEntry[],\n routePath?: RouteConf[]\n ): Promise<boolean> {\n if (!(await asyncCheckIf(dataConf, runtimeContext))) {\n return false;\n }\n let value: unknown;\n if (\n asyncHostPropertyEntries &&\n (this.type === \"STATE\" ? dataConf.expose : this.type === \"FORM_STATE\")\n ) {\n value = await computePropertyValue(\n asyncHostPropertyEntries,\n dataConf.name\n );\n }\n let load: DataStoreItem[\"load\"];\n let loading: Promise<unknown> | undefined;\n let useResolve: boolean | undefined;\n let trackConditionalResolve: boolean | undefined;\n let resolvePolicy: \"eager\" | \"lazy\" | \"async\" | undefined;\n if (value === undefined) {\n if (dataConf.resolve) {\n const hasFallbackValue = hasOwnProperty(dataConf, \"value\");\n // Track conditional resolve only if all matches:\n // - Track enabled\n // - Has fallback value\n // - Referencing other data in `resolve.if`\n trackConditionalResolve =\n dataConf.track &&\n hasFallbackValue &&\n hasOwnProperty(dataConf.resolve, \"if\") &&\n strictCollectMemberUsage(dataConf.resolve.if, this.type).size > 0;\n const resolveConf = {\n transform: \"value\",\n ...dataConf.resolve,\n };\n useResolve = await asyncCheckIf(dataConf.resolve, runtimeContext);\n if (useResolve || trackConditionalResolve) {\n load = async (options) =>\n (\n (await resolveData(resolveConf, runtimeContext, {\n ...options,\n renderId: this.rendererContext?.renderId,\n })) as {\n value: unknown;\n }\n ).value;\n }\n if (useResolve) {\n // `async` take precedence over `lazy`\n resolvePolicy = dataConf.resolve.async\n ? \"async\"\n : dataConf.resolve.lazy\n ? \"lazy\"\n : \"eager\";\n if (resolvePolicy === \"eager\") {\n value = await load!();\n } else if (resolvePolicy === \"async\") {\n loading = load!();\n }\n } else if (!hasFallbackValue) {\n return false;\n }\n }\n if (\n (!useResolve || resolvePolicy !== \"eager\") &&\n dataConf.value !== undefined\n ) {\n // If the context has no resolve, just use its `value`.\n // Or if the resolve is ignored or lazy, use its `value` as a fallback.\n value = await asyncComputeRealValue(dataConf.value, runtimeContext);\n }\n }\n\n if (this.data.has(dataConf.name)) {\n throw new Error(\n `${this.type} '${dataConf.name}' has already been declared`\n );\n }\n\n const newData: DataStoreItem = {\n name: dataConf.name,\n value,\n // This is required for tracking context, even if no `onChange` is specified.\n eventTarget: new EventTarget(),\n useResolve,\n load,\n loaded: resolvePolicy === \"eager\",\n loading,\n async: resolvePolicy === \"async\",\n deps: [],\n };\n\n if (resolvePolicy === \"lazy\") {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { trigger } = dataConf.resolve!;\n if (\n trigger &&\n supportContextResolveTriggerBrickLifeCycle.includes(trigger)\n ) {\n this.rendererContext?.registerArbitraryLifeCycle(trigger, () => {\n this.updateValue(dataConf.name, undefined, \"load\");\n });\n }\n }\n\n if (dataConf.onChange) {\n newData.eventTarget.addEventListener(\n this.changeEventType,\n listenerFactory(dataConf.onChange, runtimeContext)\n );\n }\n\n if (dataConf.track) {\n const deps = strictCollectMemberUsage(\n trackConditionalResolve\n ? [dataConf.resolve, dataConf.value]\n : load\n ? dataConf.resolve\n : dataConf.value,\n this.type\n );\n !load && (newData.deps = [...deps]);\n for (const dep of deps) {\n this.onChange(\n dep,\n this.batchAddListener(() => {\n newData.useResolve = trackConditionalResolve\n ? checkIf(dataConf.resolve!, runtimeContext)\n : !!load;\n if (newData.useResolve) {\n this.updateValue(dataConf.name, { cache: \"default\" }, \"refresh\");\n } else {\n this.updateValue(\n dataConf.name,\n computeRealValue(dataConf.value, runtimeContext),\n \"replace\"\n );\n }\n }, dataConf)\n );\n }\n }\n\n newData.eventTarget.addEventListener(this.changeEventType, (e) => {\n this.notifyRealTimeDataChange(dataConf.name, (e as CustomEvent).detail);\n });\n\n this.data.set(dataConf.name, newData);\n\n if (Array.isArray(routePath)) {\n for (const route of routePath) {\n const names = this.routeMap.get(route);\n if (names) {\n names.add(dataConf.name);\n } else {\n this.routeMap.set(route, new Set([dataConf.name]));\n }\n }\n }\n\n return true;\n }\n\n disposeDataInRoutes(routes: RouteConf[]) {\n for (const route of routes) {\n const names = this.routeMap.get(route);\n if (names !== undefined) {\n for (const name of names) {\n this.data.delete(name);\n }\n }\n }\n }\n\n private batchAddListener(\n listener: EventListener,\n contextConf: ContextConf\n ): EventListener {\n return (event: Event | CustomEvent): void => {\n if (\n this.batchUpdate &&\n this.batchUpdateContextsNames.includes(contextConf.name)\n ) {\n return;\n }\n listener(event);\n };\n }\n}\n"],"mappings":";;;;;;;AAOA,IAAAA,QAAA,GAAAC,OAAA;AACA,IAAAC,WAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,cAAA,GAAAJ,OAAA;AACA,IAAAK,QAAA,GAAAL,OAAA;AACA,IAAAM,iBAAA,GAAAN,OAAA;AAIA,IAAAO,YAAA,GAAAP,OAAA;AACA,IAAAQ,iBAAA,GAAAR,OAAA;AAMA,IAAAS,gBAAA,GAAAT,OAAA;AAEA,IAAAU,sBAAA,GAAAV,OAAA;AACA,IAAAW,QAAA,GAAAX,OAAA;AACA,IAAAY,oBAAA,GAAAZ,OAAA;AAIA,IAAAa,aAAA,GAAAb,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WAAW,IAChB,IAAI,CAACC,wBAAwB,CAAC6B,QAAQ,CAACuH,WAAW,CAAC1I,IAAI,CAAC,EACxD;QACA;MACF;MACAmF,QAAQ,CAACwD,KAAK,CAAC;IACjB,CAAC;EACH;AACF;AAACC,OAAA,CAAA/J,SAAA,GAAAA,SAAA","ignoreList":[]}
1
+ {"version":3,"file":"DataStore.js","names":["_general","require","_storyboard","_eventTarget","_interopRequireDefault","_lodash","_bindListeners","_checkIf","_computeRealValue","_resolveData","_resolveDataStore","_handleHttpError","_computeRealProperties","_Runtime","_realTimeDataInspect","_isStrictMode","supportContextResolveTriggerBrickLifeCycle","DataStore","type","data","Map","changeEventType","pendingStack","hostBrick","stateStoreId","batchUpdate","batchUpdateContextsNames","rendererContext","routeMap","WeakMap","routeStackMap","constructor","getAllValues","Object","fromEntries","entries","map","name","value","getValue","_this$data$get","get","notifyRealTimeDataChange","realTimeDataInspectRoot","tplStateStoreId","callRealTimeDataInspectHooks","changeType","detail","getAffectListByContext","affectNames","forEach","key","deps","isInDeps","some","item","includes","push","shift","Set","updateValues","values","method","argsFactory","length","Error","updateContexts","affectContexts","affectDepsContextNames","arg","updateContextItem","updateValue","filter","affectContextItem","triggerEvent","contexts","_context$eventTarget","context","eventTarget","dispatchEvent","CustomEvent","callback","callbackRuntimeContext","useResolve","promise","loaded","Promise","resolve","loading","shouldDismiss","error","_this$rendererContext","renderId","_internalApiGetRenderId","load","cache","then","val","finishLoad","err","handleHttpError","callbackFactory","eventCallbackFactory","isObject","assign","console","warn","define","dataConfs","runtimeContext","asyncHostPropertyEntries","routePath","Array","isArray","pending","resolveDataStore","dataConf","isStrictMode","route","stack","add","set","onChange","dataName","listener","_this$data$get2","addEventListener","removeEventListener","waitFor","dataNames","pendingContexts","all","ctx","p","waitForAll","pendingResult","mountAsyncData","_this$routeMap$get","async","has","asyncMounted","asyncCheckIf","expose","computePropertyValue","trackConditionalResolve","resolvePolicy","undefined","hasFallbackValue","hasOwnProperty","track","strictCollectMemberUsage","if","size","resolveConf","transform","options","_this$rendererContext2","resolveData","lazy","asyncComputeRealValue","newData","EventTarget","trigger","_this$rendererContext3","registerArbitraryLifeCycle","listenerFactory","dep","batchAddListener","checkIf","computeRealValue","e","names","disposeDataInRoutes","routes","delete","pull","contextConf","event","exports"],"sources":["../../../../src/internal/data/DataStore.ts"],"sourcesContent":["import type {\n BatchUpdateContextItem,\n BrickEventHandlerCallback,\n ContextConf,\n ContextResolveTriggerBrickLifeCycle,\n RouteConf,\n} from \"@next-core/types\";\nimport { hasOwnProperty, isObject } from \"@next-core/utils/general\";\nimport { strictCollectMemberUsage } from \"@next-core/utils/storyboard\";\nimport EventTarget from \"@ungap/event-target\";\nimport { pull } from \"lodash\";\nimport { eventCallbackFactory, listenerFactory } from \"../bindListeners.js\";\nimport { asyncCheckIf, checkIf } from \"../compute/checkIf.js\";\nimport {\n asyncComputeRealValue,\n computeRealValue,\n} from \"../compute/computeRealValue.js\";\nimport { ResolveOptions, resolveData } from \"./resolveData.js\";\nimport { resolveDataStore } from \"./resolveDataStore.js\";\nimport type {\n AsyncPropertyEntry,\n RuntimeBrick,\n RuntimeContext,\n} from \"../interfaces.js\";\nimport { handleHttpError } from \"../../handleHttpError.js\";\nimport type { RendererContext } from \"../RendererContext.js\";\nimport { computePropertyValue } from \"../compute/computeRealProperties.js\";\nimport { _internalApiGetRenderId } from \"../Runtime.js\";\nimport {\n callRealTimeDataInspectHooks,\n realTimeDataInspectRoot,\n} from \"./realTimeDataInspect.js\";\nimport { isStrictMode } from \"../../isStrictMode.js\";\n\nconst supportContextResolveTriggerBrickLifeCycle = [\n \"onBeforePageLoad\",\n \"onPageLoad\",\n \"onBeforePageLeave\",\n \"onPageLeave\",\n \"onAnchorLoad\",\n \"onAnchorUnload\",\n] as ContextResolveTriggerBrickLifeCycle[];\n\nexport type DataStoreType = \"CTX\" | \"STATE\" | \"FORM_STATE\";\n\nexport interface DataStoreItem {\n name: string;\n value: unknown;\n eventTarget: EventTarget;\n useResolve?: boolean;\n loaded?: boolean;\n loading?: Promise<unknown>;\n load?: (options?: ResolveOptions) => Promise<unknown>;\n async?: boolean;\n asyncMounted?: boolean;\n deps: string[];\n}\n\ntype PendingStackItem = ReturnType<typeof resolveDataStore>;\n\nexport class DataStore<T extends DataStoreType = \"CTX\"> {\n private readonly type: T;\n private readonly data = new Map<string, DataStoreItem>();\n private readonly changeEventType: string;\n private readonly pendingStack: Array<PendingStackItem> = [];\n public readonly hostBrick?: RuntimeBrick;\n private readonly stateStoreId?: string;\n private batchUpdate = false;\n private batchUpdateContextsNames: string[] = [];\n private readonly rendererContext?: RendererContext;\n private routeMap = new WeakMap<RouteConf, Set<string>>();\n private routeStackMap = new WeakMap<RouteConf, Set<PendingStackItem>>();\n\n // 把 `rendererContext` 放在参数列表的最后,并作为可选,以减少测试文件的调整\n constructor(\n type: T,\n hostBrick?: RuntimeBrick,\n rendererContext?: RendererContext,\n stateStoreId?: string\n ) {\n this.type = type;\n this.changeEventType =\n this.type === \"FORM_STATE\"\n ? \"formstate.change\"\n : this.type === \"STATE\"\n ? \"state.change\"\n : \"context.change\";\n this.hostBrick = hostBrick;\n this.rendererContext = rendererContext;\n this.stateStoreId = stateStoreId;\n }\n\n getAllValues(): Record<string, unknown> {\n return Object.fromEntries(\n [...this.data.entries()].map(([name, { value }]) => [name, value])\n );\n }\n\n getValue(name: string): unknown {\n return this.data.get(name)?.value;\n }\n\n private notifyRealTimeDataChange(name: string, value: unknown) {\n if (realTimeDataInspectRoot) {\n const { tplStateStoreId } = realTimeDataInspectRoot;\n if (\n tplStateStoreId\n ? this.type === \"STATE\" && this.stateStoreId === tplStateStoreId\n : this.type === \"CTX\"\n ) {\n callRealTimeDataInspectHooks({\n changeType: \"update\",\n tplStateStoreId,\n detail: {\n name,\n value,\n },\n });\n }\n }\n }\n\n private getAffectListByContext(name: string): string[] {\n const affectNames = [name];\n this.data.forEach((value, key) => {\n if (value.deps) {\n const isInDeps = value.deps.some((item) => affectNames.includes(item));\n isInDeps &&\n affectNames.push(key) &&\n affectNames.push(...this.getAffectListByContext(key));\n }\n });\n affectNames.shift();\n return [...new Set(affectNames)];\n }\n\n updateValues(\n values: BatchUpdateContextItem[],\n method: \"assign\" | \"replace\",\n argsFactory: (arg: unknown[]) => BatchUpdateContextItem\n ): void {\n this.batchUpdate = true;\n this.batchUpdateContextsNames = values.map((item) => item.name);\n if (\n [...new Set(this.batchUpdateContextsNames)].length !==\n this.batchUpdateContextsNames.length\n ) {\n throw new Error(`Batch update not allow to update same item`);\n }\n\n const updateContexts: Record<string, DataStoreItem> = {};\n const affectContexts: Record<string, DataStoreItem> = {};\n const affectDepsContextNames: string[] = [];\n\n values.forEach((arg) => {\n const { name, value } = argsFactory([arg]);\n const updateContextItem = this.data.get(name);\n affectDepsContextNames.push(...this.getAffectListByContext(name));\n updateContextItem && (updateContexts[name] = updateContextItem);\n this.updateValue(name as string, value, method);\n });\n\n affectDepsContextNames\n .filter((item) => !updateContexts[item])\n .forEach((name) => {\n const affectContextItem = this.data.get(name);\n affectContextItem && (affectContexts[name] = affectContextItem);\n });\n\n const triggerEvent = (contexts: Record<string, DataStoreItem>): void => {\n for (const key in contexts) {\n const context = contexts[key];\n context.eventTarget?.dispatchEvent(\n new CustomEvent(this.changeEventType, {\n detail: context.value,\n })\n );\n }\n };\n\n triggerEvent(updateContexts);\n triggerEvent(affectContexts);\n\n this.batchUpdate = false;\n\n return;\n }\n\n updateValue(\n name: string,\n value: unknown,\n method: \"assign\" | \"replace\" | \"refresh\" | \"load\",\n callback?: BrickEventHandlerCallback,\n callbackRuntimeContext?: RuntimeContext\n ): void {\n const item = this.data.get(name);\n if (!item) {\n throw new Error(`${this.type} '${name}' is not defined`);\n }\n\n if (method === \"refresh\" || method === \"load\") {\n if (!item.useResolve) {\n throw new Error(\n `You can not ${method} \"${this.type}.${name}\" which is not using resolve`\n );\n }\n\n let promise: Promise<unknown> | undefined;\n if (method === \"load\") {\n // Try to reuse previous request when calling `load`.\n if (item.loaded) {\n promise = Promise.resolve(item.value);\n } else if (item.loading) {\n promise = item.loading;\n }\n }\n\n const shouldDismiss = (error: unknown) => {\n // If render twice immediately, flow API contracts maybe cleared before\n // the second rendering, while the page load handlers of the first\n // rendering can't be cancelled, which throws `FlowApiNotFoundError`.\n // So we ignore error reporting for this case.\n let renderId: string | undefined;\n return (\n (error as Error)?.name === \"FlowApiNotFoundError\" &&\n !!(renderId = this.rendererContext?.renderId) &&\n renderId !== _internalApiGetRenderId()\n );\n };\n\n if (!promise) {\n promise = item.loading = item.load!({\n cache: method === \"load\" ? \"default\" : \"reload\",\n ...(value as ResolveOptions),\n });\n // Do not use the chained promise, since the callbacks need the original promise.\n promise.then(\n (val) => {\n this.finishLoad(item, val);\n },\n (err) => {\n // Let users override error handling.\n if (item.useResolve && !shouldDismiss(err) && !callback?.error) {\n handleHttpError(err);\n }\n }\n );\n }\n\n if (callback) {\n const callbackFactory = eventCallbackFactory(\n callback,\n callbackRuntimeContext!\n );\n\n promise.then(\n (val) => {\n callbackFactory(\"success\")({ value: val });\n callbackFactory(\"finally\")();\n },\n (err) => {\n if (!shouldDismiss(err) && callback.error) {\n callbackFactory(\"error\")(err);\n }\n callbackFactory(\"finally\")();\n }\n );\n }\n\n return;\n }\n\n if (method === \"replace\") {\n item.value = value;\n } else {\n if (isObject(item.value)) {\n Object.assign(item.value, value);\n } else {\n // eslint-disable-next-line no-console\n console.warn(\n `Non-object current value of \"${this.type}.${name}\" for \"context.assign\", try \"context.replace\" instead.`\n );\n item.value = value;\n }\n }\n\n if (this.batchUpdate) return;\n\n item.eventTarget.dispatchEvent(\n new CustomEvent(this.changeEventType, {\n detail: item.value,\n })\n );\n }\n\n private finishLoad(item: DataStoreItem, value: unknown) {\n if (!item.useResolve) {\n // This happens when a tracked conditional resolve switches from\n // resolve to fallback after an dep update triggered refresh but\n // before it's been resolved.\n return;\n }\n item.loaded = true;\n item.value = value;\n item.eventTarget.dispatchEvent(\n new CustomEvent(this.changeEventType, {\n detail: value,\n })\n );\n }\n\n define(\n dataConfs: ContextConf[] | undefined,\n runtimeContext: RuntimeContext,\n asyncHostPropertyEntries?: AsyncPropertyEntry[],\n routePath?: RouteConf[]\n ): void {\n if (Array.isArray(dataConfs) && dataConfs.length > 0) {\n const pending = resolveDataStore(\n dataConfs,\n (dataConf: ContextConf) =>\n this.resolve(\n dataConf,\n runtimeContext,\n asyncHostPropertyEntries,\n routePath\n ),\n this.type,\n isStrictMode(runtimeContext)\n );\n if (Array.isArray(routePath)) {\n for (const route of routePath) {\n const stack = this.routeStackMap.get(route);\n if (stack) {\n stack.add(pending);\n } else {\n this.routeStackMap.set(route, new Set([pending]));\n }\n }\n }\n this.pendingStack.push(pending);\n }\n }\n\n onChange(dataName: string, listener: EventListener): () => void {\n const eventTarget = this.data.get(dataName)?.eventTarget;\n eventTarget?.addEventListener(this.changeEventType, listener);\n return () => {\n eventTarget?.removeEventListener(this.changeEventType, listener);\n };\n }\n\n async waitFor(dataNames: string[] | Set<string>): Promise<void> {\n for (const { pendingContexts } of this.pendingStack) {\n await Promise.all(\n [...dataNames].map((ctx) => {\n const p = pendingContexts.get(ctx);\n return p;\n })\n );\n }\n }\n\n async waitForAll(): Promise<void> {\n for (const { pendingResult } of this.pendingStack) {\n await pendingResult;\n }\n }\n\n /**\n * After mount, dispatch the change event when an async data is loaded.\n *\n * If param `route` is present, handle data defined in that route (or its descendants) only.\n */\n mountAsyncData(route?: RouteConf) {\n this.data.forEach((item) => {\n if (item.async && (!route || this.routeMap.get(route)?.has(item.name))) {\n // istanbul ignore next\n if (item.asyncMounted) {\n // eslint-disable-next-line no-console\n console.error(\n `Async data \"${item.name}\" already mounted. This is a bug of Brick Next, please report it.`\n );\n return;\n }\n item.asyncMounted = true;\n // An async data always has `loading`\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n item.loading!.then((value) => {\n this.finishLoad(item, value);\n });\n }\n });\n }\n\n private async resolve(\n dataConf: ContextConf,\n runtimeContext: RuntimeContext,\n asyncHostPropertyEntries?: AsyncPropertyEntry[],\n routePath?: RouteConf[]\n ): Promise<boolean> {\n if (!(await asyncCheckIf(dataConf, runtimeContext))) {\n return false;\n }\n let value: unknown;\n if (\n asyncHostPropertyEntries &&\n (this.type === \"STATE\" ? dataConf.expose : this.type === \"FORM_STATE\")\n ) {\n value = await computePropertyValue(\n asyncHostPropertyEntries,\n dataConf.name\n );\n }\n let load: DataStoreItem[\"load\"];\n let loading: Promise<unknown> | undefined;\n let useResolve: boolean | undefined;\n let trackConditionalResolve: boolean | undefined;\n let resolvePolicy: \"eager\" | \"lazy\" | \"async\" | undefined;\n if (value === undefined) {\n if (dataConf.resolve) {\n const hasFallbackValue = hasOwnProperty(dataConf, \"value\");\n // Track conditional resolve only if all matches:\n // - Track enabled\n // - Has fallback value\n // - Referencing other data in `resolve.if`\n trackConditionalResolve =\n dataConf.track &&\n hasFallbackValue &&\n hasOwnProperty(dataConf.resolve, \"if\") &&\n strictCollectMemberUsage(dataConf.resolve.if, this.type).size > 0;\n const resolveConf = {\n transform: \"value\",\n ...dataConf.resolve,\n };\n useResolve = await asyncCheckIf(dataConf.resolve, runtimeContext);\n if (useResolve || trackConditionalResolve) {\n load = async (options) =>\n (\n (await resolveData(resolveConf, runtimeContext, {\n ...options,\n renderId: this.rendererContext?.renderId,\n })) as {\n value: unknown;\n }\n ).value;\n }\n if (useResolve) {\n // `async` take precedence over `lazy`\n resolvePolicy = dataConf.resolve.async\n ? \"async\"\n : dataConf.resolve.lazy\n ? \"lazy\"\n : \"eager\";\n if (resolvePolicy === \"eager\") {\n value = await load!();\n } else if (resolvePolicy === \"async\") {\n loading = load!();\n }\n } else if (!hasFallbackValue) {\n return false;\n }\n }\n if (\n (!useResolve || resolvePolicy !== \"eager\") &&\n dataConf.value !== undefined\n ) {\n // If the context has no resolve, just use its `value`.\n // Or if the resolve is ignored or lazy, use its `value` as a fallback.\n value = await asyncComputeRealValue(dataConf.value, runtimeContext);\n }\n }\n\n if (this.data.has(dataConf.name)) {\n throw new Error(\n `${this.type} '${dataConf.name}' has already been declared`\n );\n }\n\n const newData: DataStoreItem = {\n name: dataConf.name,\n value,\n // This is required for tracking context, even if no `onChange` is specified.\n eventTarget: new EventTarget(),\n useResolve,\n load,\n loaded: resolvePolicy === \"eager\",\n loading,\n async: resolvePolicy === \"async\",\n deps: [],\n };\n\n if (resolvePolicy === \"lazy\") {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { trigger } = dataConf.resolve!;\n if (\n trigger &&\n supportContextResolveTriggerBrickLifeCycle.includes(trigger)\n ) {\n this.rendererContext?.registerArbitraryLifeCycle(trigger, () => {\n this.updateValue(dataConf.name, undefined, \"load\");\n });\n }\n }\n\n if (dataConf.onChange) {\n newData.eventTarget.addEventListener(\n this.changeEventType,\n listenerFactory(dataConf.onChange, runtimeContext)\n );\n }\n\n if (dataConf.track) {\n const deps = strictCollectMemberUsage(\n trackConditionalResolve\n ? [dataConf.resolve, dataConf.value]\n : load\n ? dataConf.resolve\n : dataConf.value,\n this.type\n );\n !load && (newData.deps = [...deps]);\n for (const dep of deps) {\n this.onChange(\n dep,\n this.batchAddListener(() => {\n newData.useResolve = trackConditionalResolve\n ? checkIf(dataConf.resolve!, runtimeContext)\n : !!load;\n if (newData.useResolve) {\n this.updateValue(dataConf.name, { cache: \"default\" }, \"refresh\");\n } else {\n this.updateValue(\n dataConf.name,\n computeRealValue(dataConf.value, runtimeContext),\n \"replace\"\n );\n }\n }, dataConf)\n );\n }\n }\n\n newData.eventTarget.addEventListener(this.changeEventType, (e) => {\n this.notifyRealTimeDataChange(dataConf.name, (e as CustomEvent).detail);\n });\n\n this.data.set(dataConf.name, newData);\n\n if (Array.isArray(routePath)) {\n for (const route of routePath) {\n const names = this.routeMap.get(route);\n if (names) {\n names.add(dataConf.name);\n } else {\n this.routeMap.set(route, new Set([dataConf.name]));\n }\n }\n }\n\n return true;\n }\n\n /**\n * For sub-routes to be incrementally rendered,\n * dispose their data and pending tasks.\n */\n disposeDataInRoutes(routes: RouteConf[]) {\n for (const route of routes) {\n const names = this.routeMap.get(route);\n if (names !== undefined) {\n for (const name of names) {\n this.data.delete(name);\n }\n this.routeMap.delete(route);\n }\n const stack = this.routeStackMap.get(route);\n if (stack !== undefined) {\n pull(this.pendingStack, ...stack);\n this.routeStackMap.delete(route);\n }\n }\n }\n\n private batchAddListener(\n listener: EventListener,\n contextConf: ContextConf\n ): EventListener {\n return (event: Event | CustomEvent): void => {\n if (\n this.batchUpdate &&\n this.batchUpdateContextsNames.includes(contextConf.name)\n ) {\n return;\n }\n listener(event);\n };\n }\n}\n"],"mappings":";;;;;;;AAOA,IAAAA,QAAA,GAAAC,OAAA;AACA,IAAAC,WAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AACA,IAAAK,cAAA,GAAAL,OAAA;AACA,IAAAM,QAAA,GAAAN,OAAA;AACA,IAAAO,iBAAA,GAAAP,OAAA;AAIA,IAAAQ,YAAA,GAAAR,OAAA;AACA,IAAAS,iBAAA,GAAAT,OAAA;AAMA,IAAAU,gBAAA,GAAAV,OAAA;AAEA,IAAAW,sBAAA,GAAAX,OAAA;AACA,IAAAY,QAAA,GAAAZ,OAAA;AACA,IAAAa,oBAAA,GAAAb,OAAA;AAIA,IAAAc,aAAA,GAAAd,OAAA;AAEA,MAAMe,0CAA0C,GAAG,CACjD,kBAAkB,EAClB,YAAY,EACZ,mBAAmB,EACnB,aAAa,EACb,cAAc,EACd,gBAAgB,CACwB;AAmBnC,MAAMC,SAAS,CAAkC;EACrCC,IAAI;EACJC,IAAI,GAAG,IAAIC,GAAG,CAAwB,CAAC;EACvCC,eAAe;EACfC,YAAY,GAA4B,EAAE;EAC3CC,SAAS;EACRC,YAAY;EACrBC,WAAW,GAAG,KAAK;EACnBC,wBAAwB,GAAa,EAAE;EAC9BC,eAAe;EACxBC,QAAQ,GAAG,IAAIC,OAAO,CAAyB,CAAC;EAChDC,aAAa,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aAAa,CAACgJ,MAAM,CAACxD,KAAK,CAAC;MAClC;IACF;EACF;EAEQiD,gBAAgBA,CACtB3C,QAAuB,EACvBoD,WAAwB,EACT;IACf,OAAQC,KAA0B,IAAW;MAC3C,IACE,IAAI,CAACxJ,WAAW,IAChB,IAAI,CAACC,wBAAwB,CAAC8B,QAAQ,CAACwH,WAAW,CAAC3I,IAAI,CAAC,EACxD;QACA;MACF;MACAuF,QAAQ,CAACqD,KAAK,CAAC;IACjB,CAAC;EACH;AACF;AAACC,OAAA,CAAAjK,SAAA,GAAAA,SAAA","ignoreList":[]}
@@ -17,12 +17,17 @@ function resolveDataStore(contextConfs, resolveContext, keyword = "CTX", strict)
17
17
  const hasNonStaticUsage = Array.from(dependencyMap.values()).some(stats => stats.hasNonStaticUsage);
18
18
  const processed = new WeakSet();
19
19
  const deferredContexts = new Map();
20
- const pendingContexts = new Map([...new Set(contextConfs.map(contextConf => contextConf.name))].map(contextName => [contextName, new Promise((resolve, reject) => {
21
- deferredContexts.set(contextName, {
22
- resolve,
23
- reject
20
+ const pendingContexts = new Map([...new Set(contextConfs.map(contextConf => contextConf.name))].map(contextName => {
21
+ const promise = new Promise((resolve, reject) => {
22
+ deferredContexts.set(contextName, {
23
+ resolve,
24
+ reject
25
+ });
24
26
  });
25
- })]));
27
+ // The pending context will be caught by the renderer.
28
+ promise.catch(() => {});
29
+ return [contextName, promise];
30
+ }));
26
31
  const wrapResolve = async contextConf => {
27
32
  processed.add(contextConf);
28
33
  const resolved = await resolveContext(contextConf);
@@ -80,6 +85,8 @@ function resolveDataStore(contextConfs, resolveContext, keyword = "CTX", strict)
80
85
  }
81
86
  throw error;
82
87
  });
88
+ // The pending result will be caught by the renderer.
89
+ pendingResult.catch(() => {});
83
90
  return {
84
91
  pendingResult,
85
92
  pendingContexts
@@ -1 +1 @@
1
- {"version":3,"file":"resolveDataStore.js","names":["_storyboard","require","resolveDataStore","contextConfs","resolveContext","keyword","strict","dependencyMap","getDependencyMapOfContext","pendingDeps","Map","contextName","Array","from","keys","map","contextConf","name","set","get","hasNonStaticUsage","values","some","stats","processed","WeakSet","deferredContexts","pendingContexts","Set","Promise","resolve","reject","wrapResolve","add","resolved","delete","left","Error","scheduleNext","scheduleAsSerial","readyContexts","entries","filter","predicateNextResolveFactory","entry","has","all","pendingResult","then","size","detectCircularContexts","deferred","catch","error","index","usedProperties","dep","depsMap","data","if","value","collectMemberUsage","legacyTplStats","prop","duplicatedMap","next","processedAtLeastOne","ReferenceError","join"],"sources":["../../../../src/internal/data/resolveDataStore.ts"],"sourcesContent":["import { ContextConf } from \"@next-core/types\";\nimport { collectMemberUsage, MemberUsage } from \"@next-core/utils/storyboard\";\n\nexport interface DeferredContext {\n resolve(): void;\n reject(e: unknown): void;\n}\n\nexport function resolveDataStore(\n contextConfs: ContextConf[],\n resolveContext: (contextConf: ContextConf) => Promise<boolean>,\n keyword = \"CTX\",\n strict?: boolean\n): {\n pendingResult: Promise<void>;\n pendingContexts: Map<string, Promise<void>>;\n} {\n const dependencyMap = getDependencyMapOfContext(\n contextConfs,\n keyword,\n strict\n );\n // There maybe multiple context confs for a specific name, since there are conditional contexts.\n // This is a map of how many pending context confs for each context name.\n const pendingDeps = new Map<string, number>();\n for (const contextName of Array.from(dependencyMap.keys()).map(\n (contextConf) => contextConf.name\n )) {\n pendingDeps.set(contextName, (pendingDeps.get(contextName) ?? 0) + 1);\n }\n const hasNonStaticUsage = Array.from(dependencyMap.values()).some(\n (stats) => stats.hasNonStaticUsage\n );\n const processed = new WeakSet<ContextConf>();\n\n const deferredContexts = new Map<string, DeferredContext>();\n const pendingContexts = new Map(\n [...new Set(contextConfs.map((contextConf) => contextConf.name))].map(\n (contextName) => [\n contextName,\n new Promise<void>((resolve, reject) => {\n deferredContexts.set(contextName, { resolve, reject });\n }),\n ]\n )\n );\n\n const wrapResolve = async (contextConf: ContextConf): Promise<void> => {\n processed.add(contextConf);\n const resolved = await resolveContext(contextConf);\n dependencyMap.delete(contextConf);\n const left = pendingDeps.get(contextConf.name) ?? 0;\n if (resolved) {\n // Assert: contextConf.name exists in deferredContexts\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n deferredContexts.get(contextConf.name)!.resolve();\n pendingDeps.delete(contextConf.name);\n if (left === 0) {\n throw new Error(`Duplicated context defined: ${contextConf.name}`);\n }\n } else {\n // Assert: left >= 1\n if (left === 1) {\n // Assert: contextConf.name exists in deferredContexts\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n deferredContexts.get(contextConf.name)!.resolve();\n pendingDeps.delete(contextConf.name);\n } else {\n pendingDeps.set(contextConf.name, left - 1);\n }\n }\n await scheduleNext();\n };\n\n let scheduleAsSerial = hasNonStaticUsage;\n\n async function scheduleNext(): Promise<void> {\n const readyContexts = Array.from(dependencyMap.entries())\n .filter(predicateNextResolveFactory(pendingDeps, scheduleAsSerial))\n .map((entry) => entry[0])\n .filter((contextConf) => !processed.has(contextConf));\n await Promise.all(readyContexts.map(wrapResolve));\n }\n\n const pendingResult = scheduleNext()\n .then(async () => {\n // If there are still contexts left, it implies one of these situations:\n // - Circular contexts.\n // Such as: a depends on b, while b depends on a.\n // - Related contexts are all ignored.\n // Such as: a depends on b,\n // while both them are ignore by a falsy result of `if`.\n if (dependencyMap.size > 0) {\n // This will throw if circular contexts detected.\n detectCircularContexts(dependencyMap, keyword);\n scheduleAsSerial = true;\n await scheduleNext();\n }\n // There maybe ignored contexts which are still not fulfilled.\n // We treat them as RESOLVED.\n for (const deferred of deferredContexts.values()) {\n deferred.resolve();\n }\n })\n .catch((error) => {\n // There maybe contexts left not fulfilled, when an error occurred.\n // We treat them as REJECTED.\n for (const deferred of deferredContexts.values()) {\n deferred.reject(error);\n }\n throw error;\n });\n return { pendingResult, pendingContexts };\n}\n\nfunction predicateNextResolveFactory(\n pendingDeps: Map<string, number>,\n scheduleAsSerial: boolean\n): (entry: [ContextConf, MemberUsage], index: number) => boolean {\n return (entry, index) =>\n // When contexts contain computed CTX accesses, it implies a dynamic dependency map.\n // So make them process sequentially, keep the same behavior as before.\n scheduleAsSerial\n ? index === 0\n : // A context is ready when it has no pending dependencies.\n ![...entry[1].usedProperties].some((dep) => pendingDeps.has(dep));\n}\n\nexport function getDependencyMapOfContext(\n contextConfs: ContextConf[],\n keyword = \"CTX\",\n strict?: boolean\n): Map<ContextConf, MemberUsage> {\n const depsMap = new Map<ContextConf, MemberUsage>();\n for (const contextConf of contextConfs) {\n const data = [contextConf.if, contextConf.value, contextConf.resolve];\n const stats = collectMemberUsage(data, keyword);\n if (!strict && keyword === \"STATE\") {\n const legacyTplStats = collectMemberUsage(data, \"TPL\");\n // Merge stats with legacyTplStats\n for (const prop of legacyTplStats.usedProperties) {\n stats.usedProperties.add(prop);\n }\n if (legacyTplStats.hasNonStaticUsage) {\n stats.hasNonStaticUsage = true;\n }\n }\n depsMap.set(contextConf, stats);\n }\n return depsMap;\n}\n\nfunction detectCircularContexts(\n dependencyMap: Map<ContextConf, MemberUsage>,\n keyword: string\n): void {\n const duplicatedMap = new Map(dependencyMap);\n const pendingDeps = new Set<string>(\n Array.from(duplicatedMap.keys()).map((contextConf) => contextConf.name)\n );\n const next = (): void => {\n let processedAtLeastOne = false;\n for (const [contextConf, stats] of duplicatedMap.entries()) {\n if (![...stats.usedProperties].some((dep) => pendingDeps.has(dep))) {\n duplicatedMap.delete(contextConf);\n pendingDeps.delete(contextConf.name);\n processedAtLeastOne = true;\n }\n }\n if (processedAtLeastOne) {\n next();\n }\n };\n next();\n\n if (duplicatedMap.size > 0) {\n throw new ReferenceError(\n `Circular ${keyword} detected: ${Array.from(duplicatedMap.keys())\n .map((contextConf) => contextConf.name)\n .join(\", \")}`\n );\n }\n}\n"],"mappings":";;;;;;;AACA,IAAAA,WAAA,GAAAC,OAAA;AAOO,SAASC,gBAAgBA,CAC9BC,YAA2B,EAC3BC,cAA8D,EAC9DC,OAAO,GAAG,KAAK,EACfC,MAAgB,EAIhB;EACA,MAAMC,aAAa,GAAGC,yBAAyB,CAC7CL,YAAY,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,GAAG,IAAI;MAC5B;IACF;IACA,IAAIA,mBAAmB,EAAE;MACvBD,IAAI,CAAC,CAAC;IACR;EACF,CAAC;EACDA,IAAI,CAAC,CAAC;EAEN,IAAID,aAAa,CAACf,IAAI,GAAG,CAAC,EAAE;IAC1B,MAAM,IAAIkB,cAAc,CACtB,YAAY9D,OAAO,cAAcO,KAAK,CAACC,IAAI,CAACmD,aAAa,CAAClD,IAAI,CAAC,CAAC,CAAC,CAC9DC,GAAG,CAAEC,WAAW,IAAKA,WAAW,CAACC,IAAI,CAAC,CACtCmD,IAAI,CAAC,IAAI,CAAC,EACf,CAAC;EACH;AACF","ignoreList":[]}
1
+ {"version":3,"file":"resolveDataStore.js","names":["_storyboard","require","resolveDataStore","contextConfs","resolveContext","keyword","strict","dependencyMap","getDependencyMapOfContext","pendingDeps","Map","contextName","Array","from","keys","map","contextConf","name","set","get","hasNonStaticUsage","values","some","stats","processed","WeakSet","deferredContexts","pendingContexts","Set","promise","Promise","resolve","reject","catch","wrapResolve","add","resolved","delete","left","Error","scheduleNext","scheduleAsSerial","readyContexts","entries","filter","predicateNextResolveFactory","entry","has","all","pendingResult","then","size","detectCircularContexts","deferred","error","index","usedProperties","dep","depsMap","data","if","value","collectMemberUsage","legacyTplStats","prop","duplicatedMap","next","processedAtLeastOne","ReferenceError","join"],"sources":["../../../../src/internal/data/resolveDataStore.ts"],"sourcesContent":["import { ContextConf } from \"@next-core/types\";\nimport { collectMemberUsage, MemberUsage } from \"@next-core/utils/storyboard\";\n\nexport interface DeferredContext {\n resolve(): void;\n reject(e: unknown): void;\n}\n\nexport function resolveDataStore(\n contextConfs: ContextConf[],\n resolveContext: (contextConf: ContextConf) => Promise<boolean>,\n keyword = \"CTX\",\n strict?: boolean\n): {\n pendingResult: Promise<void>;\n pendingContexts: Map<string, Promise<void>>;\n} {\n const dependencyMap = getDependencyMapOfContext(\n contextConfs,\n keyword,\n strict\n );\n // There maybe multiple context confs for a specific name, since there are conditional contexts.\n // This is a map of how many pending context confs for each context name.\n const pendingDeps = new Map<string, number>();\n for (const contextName of Array.from(dependencyMap.keys()).map(\n (contextConf) => contextConf.name\n )) {\n pendingDeps.set(contextName, (pendingDeps.get(contextName) ?? 0) + 1);\n }\n const hasNonStaticUsage = Array.from(dependencyMap.values()).some(\n (stats) => stats.hasNonStaticUsage\n );\n const processed = new WeakSet<ContextConf>();\n\n const deferredContexts = new Map<string, DeferredContext>();\n const pendingContexts = new Map(\n [...new Set(contextConfs.map((contextConf) => contextConf.name))].map(\n (contextName) => {\n const promise = new Promise<void>((resolve, reject) => {\n deferredContexts.set(contextName, { resolve, reject });\n });\n // The pending context will be caught by the renderer.\n promise.catch(() => {});\n return [contextName, promise];\n }\n )\n );\n\n const wrapResolve = async (contextConf: ContextConf): Promise<void> => {\n processed.add(contextConf);\n const resolved = await resolveContext(contextConf);\n dependencyMap.delete(contextConf);\n const left = pendingDeps.get(contextConf.name) ?? 0;\n if (resolved) {\n // Assert: contextConf.name exists in deferredContexts\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n deferredContexts.get(contextConf.name)!.resolve();\n pendingDeps.delete(contextConf.name);\n if (left === 0) {\n throw new Error(`Duplicated context defined: ${contextConf.name}`);\n }\n } else {\n // Assert: left >= 1\n if (left === 1) {\n // Assert: contextConf.name exists in deferredContexts\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n deferredContexts.get(contextConf.name)!.resolve();\n pendingDeps.delete(contextConf.name);\n } else {\n pendingDeps.set(contextConf.name, left - 1);\n }\n }\n await scheduleNext();\n };\n\n let scheduleAsSerial = hasNonStaticUsage;\n\n async function scheduleNext(): Promise<void> {\n const readyContexts = Array.from(dependencyMap.entries())\n .filter(predicateNextResolveFactory(pendingDeps, scheduleAsSerial))\n .map((entry) => entry[0])\n .filter((contextConf) => !processed.has(contextConf));\n await Promise.all(readyContexts.map(wrapResolve));\n }\n\n const pendingResult = scheduleNext()\n .then(async () => {\n // If there are still contexts left, it implies one of these situations:\n // - Circular contexts.\n // Such as: a depends on b, while b depends on a.\n // - Related contexts are all ignored.\n // Such as: a depends on b,\n // while both them are ignore by a falsy result of `if`.\n if (dependencyMap.size > 0) {\n // This will throw if circular contexts detected.\n detectCircularContexts(dependencyMap, keyword);\n scheduleAsSerial = true;\n await scheduleNext();\n }\n // There maybe ignored contexts which are still not fulfilled.\n // We treat them as RESOLVED.\n for (const deferred of deferredContexts.values()) {\n deferred.resolve();\n }\n })\n .catch((error) => {\n // There maybe contexts left not fulfilled, when an error occurred.\n // We treat them as REJECTED.\n for (const deferred of deferredContexts.values()) {\n deferred.reject(error);\n }\n throw error;\n });\n // The pending result will be caught by the renderer.\n pendingResult.catch(() => {});\n return { pendingResult, pendingContexts };\n}\n\nfunction predicateNextResolveFactory(\n pendingDeps: Map<string, number>,\n scheduleAsSerial: boolean\n): (entry: [ContextConf, MemberUsage], index: number) => boolean {\n return (entry, index) =>\n // When contexts contain computed CTX accesses, it implies a dynamic dependency map.\n // So make them process sequentially, keep the same behavior as before.\n scheduleAsSerial\n ? index === 0\n : // A context is ready when it has no pending dependencies.\n ![...entry[1].usedProperties].some((dep) => pendingDeps.has(dep));\n}\n\nexport function getDependencyMapOfContext(\n contextConfs: ContextConf[],\n keyword = \"CTX\",\n strict?: boolean\n): Map<ContextConf, MemberUsage> {\n const depsMap = new Map<ContextConf, MemberUsage>();\n for (const contextConf of contextConfs) {\n const data = [contextConf.if, contextConf.value, contextConf.resolve];\n const stats = collectMemberUsage(data, keyword);\n if (!strict && keyword === \"STATE\") {\n const legacyTplStats = collectMemberUsage(data, \"TPL\");\n // Merge stats with legacyTplStats\n for (const prop of legacyTplStats.usedProperties) {\n stats.usedProperties.add(prop);\n }\n if (legacyTplStats.hasNonStaticUsage) {\n stats.hasNonStaticUsage = true;\n }\n }\n depsMap.set(contextConf, stats);\n }\n return depsMap;\n}\n\nfunction detectCircularContexts(\n dependencyMap: Map<ContextConf, MemberUsage>,\n keyword: string\n): void {\n const duplicatedMap = new Map(dependencyMap);\n const pendingDeps = new Set<string>(\n Array.from(duplicatedMap.keys()).map((contextConf) => contextConf.name)\n );\n const next = (): void => {\n let processedAtLeastOne = false;\n for (const [contextConf, stats] of duplicatedMap.entries()) {\n if (![...stats.usedProperties].some((dep) => pendingDeps.has(dep))) {\n duplicatedMap.delete(contextConf);\n pendingDeps.delete(contextConf.name);\n processedAtLeastOne = true;\n }\n }\n if (processedAtLeastOne) {\n next();\n }\n };\n next();\n\n if (duplicatedMap.size > 0) {\n throw new ReferenceError(\n `Circular ${keyword} detected: ${Array.from(duplicatedMap.keys())\n .map((contextConf) => contextConf.name)\n .join(\", \")}`\n );\n }\n}\n"],"mappings":";;;;;;;AACA,IAAAA,WAAA,GAAAC,OAAA;AAOO,SAASC,gBAAgBA,CAC9BC,YAA2B,EAC3BC,cAA8D,EAC9DC,OAAO,GAAG,KAAK,EACfC,MAAgB,EAIhB;EACA,MAAMC,aAAa,GAAGC,yBAAyB,CAC7CL,YAAY,EACZE,OAAO,EACPC,MACF,CAAC;EACD;EACA;EACA,MAAMG,WAAW,GAAG,IAAIC,GAAG,CAAiB,CAAC;EAC7C,KAAK,MAAMC,WAAW,IAAIC,KAAK,CAACC,IAAI,CAACN,aAAa,CAACO,IAAI,CAAC,CAAC,CAAC,CAACC,GAAG,CAC3DC,WAAW,IAAKA,WAAW,CAACC,IAC/B,CAAC,EAAE;IACDR,WAAW,CAACS,GAAG,CAACP,WAAW,EAAE,CAACF,WAAW,CAACU,GAAG,CAACR,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;EACvE;EACA,MAAMS,iBAAiB,GAAGR,KAAK,CAACC,IAAI,CAACN,aAAa,CAACc,MAAM,CAAC,CAAC,CAAC,CAACC,IAAI,CAC9DC,KAAK,IAAKA,KAAK,CAACH,iBACnB,CAAC;EACD,MAAMI,SAAS,GAAG,IAAIC,OAAO,CAAc,CAAC;EAE5C,MAAMC,gBAAgB,GAAG,IAAIhB,GAAG,CAA0B,CAAC;EAC3D,MAAMiB,e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[],"sources":["../../../src/internal/interfaces.ts"],"sourcesContent":["import type { LegacyCompatibleRuntimeContext } from \"@next-core/inject\";\nimport type {\n BrickEventHandler,\n BrickEventsMap,\n CustomTemplate,\n RouteConf,\n RuntimeSnippet,\n CustomTemplateProxy,\n CustomTemplateProxyBasicProperty,\n CustomTemplateProxySlot,\n SlotsConfOfBricks,\n Storyboard,\n StaticMenuConf,\n UseProviderResolveConf,\n MicroApp,\n} from \"@next-core/types\";\nimport type { DataStore } from \"./data/DataStore.js\";\nimport { RenderTag } from \"./enums.js\";\nimport { RuntimeBrickConfWithTplSymbols } from \"./CustomTemplates/constants.js\";\nimport { RuntimeBrickConfOfFormSymbols } from \"./FormRenderer/constants.js\";\n\nexport interface RuntimeContext extends LegacyCompatibleRuntimeContext {\n ctxStore: DataStore<\"CTX\">;\n tplStateStoreMap: Map<string, DataStore<\"STATE\">>;\n pendingPermissionsPreCheck: (Promise<unknown> | undefined)[];\n tplStateStoreId?: string;\n // `useBrick` has a local tpl state store scope\n tplStateStoreScope?: DataStore<\"STATE\">[];\n forEachItem?: unknown;\n forEachIndex?: number;\n forEachSize?: number;\n appendI18nNamespace?: string;\n\n formStateStoreMap: Map<string, DataStore<\"FORM_STATE\">>;\n formStateStoreId?: string;\n formStateStoreScope?: DataStore<\"FORM_STATE\">[];\n}\n\nexport type AsyncPropertyEntry = [\n name: string,\n value: Promise<unknown>,\n ignoreUndefined?: boolean,\n];\n\nexport interface ElementHolder {\n element?: HTMLElement | null;\n}\n\nexport interface RenderRoot extends BaseRenderNode {\n tag: RenderTag.ROOT;\n container?: HTMLElement | DocumentFragment;\n createPortal:\n | HTMLElement\n | DocumentFragment\n | (() => HTMLElement | DocumentFragment);\n}\n\nexport interface RenderBrick extends BaseRenderNode, RuntimeBrick {\n tag: RenderTag.BRICK;\n return: RenderReturnNode;\n hasTrackingControls?: boolean;\n}\n\nexport interface RenderPlaceholder extends BaseRenderNode {\n tag: RenderTag.PLACEHOLDER;\n return: RenderReturnNode;\n}\n\nexport interface BaseRenderNode {\n tag: RenderTag;\n child?: RenderChildNode;\n sibling?: RenderChildNode;\n return?: RenderReturnNode | null;\n childElements?: HTMLElement[];\n}\n\nexport type RenderNode = RenderRoot | RenderBrick | RenderPlaceholder;\n\nexport type RenderChildNode = RenderBrick | RenderPlaceholder;\nexport type RenderReturnNode = RenderRoot | RenderBrick;\n\nexport interface RuntimeBrick {\n type: string;\n properties?: Record<string, unknown>;\n events?: BrickEventsMap;\n slotId?: string;\n element?: RuntimeBrickElement | null;\n iid?: string;\n runtimeContext: RuntimeContext;\n tplHostMetadata?: TemplateHostMetadata;\n portal?: boolean;\n ref?: string;\n disposes?: (() => void)[];\n}\n\nexport type MetaInfoOfEventListener = [\n string,\n // For compatibility of devtools, leave the second argument there.\n null | undefined,\n BrickEventHandler,\n];\n\nexport type RememberedEventListener = [string, EventListener];\n\nexport interface RuntimeBrickElement extends HTMLElement {\n $$typeof?: \"brick\" | \"provider\" | \"custom-template\" | \"native\" | \"invalid\";\n /** Meta info of listeners, for devtools only */\n $$eventListeners?: MetaInfoOfEventListener[];\n /** Remembered listeners for unbinding */\n $$listeners?: RememberedEventListener[];\n /** Remembered proxy listeners for unbinding */\n $$proxyListeners?: RememberedEventListener[];\n /** Find element by ref in a custom template */\n $$getElementByRef?: (ref: string) => HTMLElement | null | undefined;\n $$tplStateStore?: DataStore<\"STATE\">;\n}\n\nexport interface TemplateHostMetadata {\n internalBricksByRef: Map<string, RuntimeBrick>;\n tplStateStoreId: string;\n proxy?: CustomTemplateProxy;\n}\n\nexport type TemplateHostBrick = RuntimeBrick & {\n tplHostMetadata: TemplateHostMetadata;\n};\n\nexport interface TemplateHostContext {\n reversedProxies: ReversedProxies;\n asyncHostPropertyEntries: AsyncPropertyEntry[];\n externalSlots?: SlotsConfOfBricks;\n tplStateStoreId: string;\n hostBrick: TemplateHostBrick;\n}\n\ninterface ReversedProxies {\n properties: Map<string, ReversedPropertyProxy[]>;\n slots: Map<string, ReversedSlotProxy[]>;\n}\n\ninterface ReversedPropertyProxy {\n from: string;\n to: CustomTemplateProxyBasicProperty;\n}\n\ninterface ReversedSlotProxy {\n from: string;\n to: CustomTemplateProxySlot;\n}\n\nexport type RuntimeBrickConfWithSymbols = RuntimeBrickConfWithTplSymbols &\n RuntimeBrickConfOfFormSymbols;\n\nexport interface DataValueOption {\n tplStateStoreId?: string;\n routeId?: string;\n}\n\nexport type PreviewStoryboardPatch =\n | CustomTemplate\n | RouteConf\n | RuntimeSnippet;\n\nexport interface PreviewOption {\n appId: string;\n formId?: string;\n updateStoryboardType?: \"route\" | \"template\" | \"snippet\";\n collectUsedContracts?(storyboard: Storyboard): string[] | Promise<string[]>;\n}\n\nexport interface MenuRequestNode {\n child?: MenuRequestNode;\n sibling?: MenuRequestNode;\n return?: MenuRequestNode;\n request?: Promise<StaticMenuConf>;\n}\n\nexport interface DebugDataValue {\n resolve?: UseProviderResolveConf;\n value?: unknown;\n}\n\nexport interface RuntimeDataVale\n extends Pick<LegacyCompatibleRuntimeContext, \"match\" | \"sys\" | \"query\"> {\n location: {\n href: string;\n origin: string;\n hostname: string;\n host: string;\n };\n app?: MicroApp;\n}\n\nexport interface RuntimeDataValueOption {\n routeId?: string;\n}\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"interfaces.js","names":[],"sources":["../../../src/internal/interfaces.ts"],"sourcesContent":["import type { LegacyCompatibleRuntimeContext } from \"@next-core/inject\";\nimport type {\n BrickEventHandler,\n BrickEventsMap,\n CustomTemplate,\n RouteConf,\n RuntimeSnippet,\n CustomTemplateProxy,\n CustomTemplateProxyBasicProperty,\n CustomTemplateProxySlot,\n SlotsConfOfBricks,\n Storyboard,\n StaticMenuConf,\n UseProviderResolveConf,\n MicroApp,\n} from \"@next-core/types\";\nimport type { DataStore } from \"./data/DataStore.js\";\nimport { RenderTag } from \"./enums.js\";\nimport { RuntimeBrickConfWithTplSymbols } from \"./CustomTemplates/constants.js\";\nimport { RuntimeBrickConfOfFormSymbols } from \"./FormRenderer/constants.js\";\n\nexport interface RuntimeContext extends LegacyCompatibleRuntimeContext {\n ctxStore: DataStore<\"CTX\">;\n tplStateStoreMap: Map<string, DataStore<\"STATE\">>;\n pendingPermissionsPreCheck: (Promise<unknown> | undefined)[];\n tplStateStoreId?: string;\n // `useBrick` has a local tpl state store scope\n tplStateStoreScope?: DataStore<\"STATE\">[];\n forEachItem?: unknown;\n forEachIndex?: number;\n forEachSize?: number;\n appendI18nNamespace?: string;\n\n formStateStoreMap: Map<string, DataStore<\"FORM_STATE\">>;\n formStateStoreId?: string;\n formStateStoreScope?: DataStore<\"FORM_STATE\">[];\n}\n\nexport type AsyncPropertyEntry = [\n name: string,\n value: Promise<unknown>,\n ignoreUndefined?: boolean,\n];\n\nexport interface ElementHolder {\n element?: HTMLElement | null;\n}\n\nexport interface RenderRoot extends BaseRenderNode {\n tag: RenderTag.ROOT;\n container?: HTMLElement | DocumentFragment;\n createPortal:\n | HTMLElement\n | DocumentFragment\n | (() => HTMLElement | DocumentFragment);\n}\n\nexport interface RenderBrick extends BaseRenderNode, RuntimeBrick {\n tag: RenderTag.BRICK;\n return: RenderReturnNode;\n hasTrackingControls?: boolean;\n}\n\nexport interface RenderPlaceholder extends BaseRenderNode {\n tag: RenderTag.PLACEHOLDER;\n return: RenderReturnNode;\n}\n\nexport interface BaseRenderNode {\n tag: RenderTag;\n child?: RenderChildNode;\n sibling?: RenderChildNode;\n return?: RenderReturnNode | null;\n childElements?: HTMLElement[];\n}\n\nexport type RenderNode = RenderRoot | RenderBrick | RenderPlaceholder;\n\nexport type RenderChildNode = RenderBrick | RenderPlaceholder;\nexport type RenderReturnNode = RenderRoot | RenderBrick;\n\nexport interface RuntimeBrick {\n type: string;\n properties?: Record<string, unknown>;\n events?: BrickEventsMap;\n slotId?: string;\n element?: RuntimeBrickElement | null;\n iid?: string;\n runtimeContext: RuntimeContext;\n tplHostMetadata?: TemplateHostMetadata;\n portal?: boolean;\n ref?: string;\n disposes?: (() => void)[];\n}\n\nexport type MetaInfoOfEventListener = [\n string,\n // For compatibility of devtools, leave the second argument there.\n null | undefined,\n BrickEventHandler,\n];\n\nexport type RememberedEventListener = [string, EventListener];\n\nexport interface RuntimeBrickElement extends HTMLElement {\n $$typeof?: \"brick\" | \"provider\" | \"custom-template\" | \"native\" | \"invalid\";\n /** Meta info of listeners, for devtools only */\n $$eventListeners?: MetaInfoOfEventListener[];\n /** Remembered listeners for unbinding */\n $$listeners?: RememberedEventListener[];\n /** Remembered proxy listeners for unbinding */\n $$proxyListeners?: RememberedEventListener[];\n /** Find element by ref in a custom template */\n $$getElementByRef?: (ref: string) => HTMLElement | null | undefined;\n $$tplStateStore?: DataStore<\"STATE\">;\n}\n\nexport interface TemplateHostMetadata {\n internalBricksByRef: Map<string, RuntimeBrick>;\n tplStateStoreId: string;\n proxy?: CustomTemplateProxy;\n}\n\nexport type TemplateHostBrick = RuntimeBrick & {\n tplHostMetadata: TemplateHostMetadata;\n};\n\nexport interface TemplateHostContext {\n reversedProxies: ReversedProxies;\n asyncHostPropertyEntries: AsyncPropertyEntry[];\n externalSlots?: SlotsConfOfBricks;\n tplStateStoreId: string;\n hostBrick: TemplateHostBrick;\n usedSlots: Set<string>;\n}\n\ninterface ReversedProxies {\n properties: Map<string, ReversedPropertyProxy[]>;\n slots: Map<string, ReversedSlotProxy[]>;\n}\n\ninterface ReversedPropertyProxy {\n from: string;\n to: CustomTemplateProxyBasicProperty;\n}\n\ninterface ReversedSlotProxy {\n from: string;\n to: CustomTemplateProxySlot;\n}\n\nexport type RuntimeBrickConfWithSymbols = RuntimeBrickConfWithTplSymbols &\n RuntimeBrickConfOfFormSymbols;\n\nexport interface DataValueOption {\n tplStateStoreId?: string;\n routeId?: string;\n}\n\nexport type PreviewStoryboardPatch =\n | CustomTemplate\n | RouteConf\n | RuntimeSnippet;\n\nexport interface PreviewOption {\n appId: string;\n formId?: string;\n updateStoryboardType?: \"route\" | \"template\" | \"snippet\";\n collectUsedContracts?(storyboard: Storyboard): string[] | Promise<string[]>;\n}\n\nexport interface MenuRequestNode {\n child?: MenuRequestNode;\n sibling?: MenuRequestNode;\n return?: MenuRequestNode;\n request?: Promise<StaticMenuConf>;\n}\n\nexport interface DebugDataValue {\n resolve?: UseProviderResolveConf;\n value?: unknown;\n}\n\nexport interface RuntimeDataVale\n extends Pick<LegacyCompatibleRuntimeContext, \"match\" | \"sys\" | \"query\"> {\n location: {\n href: string;\n origin: string;\n hostname: string;\n host: string;\n };\n app?: MicroApp;\n}\n\nexport interface RuntimeDataValueOption {\n routeId?: string;\n}\n"],"mappings":"","ignoreList":[]}
@@ -5,6 +5,7 @@ import { setupTemplateProxy } from "./setupTemplateProxy.js";
5
5
  import { setupUseBrickInTemplate } from "./setupUseBrickInTemplate.js";
6
6
  import { childrenToSlots } from "../Renderer.js";
7
7
  import { hooks } from "../Runtime.js";
8
+ import { replaceSlotWithSlottedBricks } from "./replaceSlotWithSlottedBricks.js";
8
9
  export function expandCustomTemplate(tplTagName, brickConf, hostBrick, asyncHostPropertyEntries, rendererContext) {
9
10
  var _hooks$flowApi;
10
11
  const tplStateStoreId = uniqueId("tpl-state-");
@@ -83,21 +84,26 @@ export function expandCustomTemplate(tplTagName, brickConf, hostBrick, asyncHost
83
84
  asyncHostPropertyEntries,
84
85
  externalSlots: childrenToSlots(externalChildren, originalExternalSlots),
85
86
  tplStateStoreId,
86
- hostBrick: hostBrick
87
+ hostBrick: hostBrick,
88
+ usedSlots: new Set()
87
89
  };
88
90
  newBrickConf.slots = {
89
91
  "": {
90
92
  type: "bricks",
91
- bricks: bricks.map(item => expandBrickInTemplate(item, hostContext))
93
+ bricks: bricks.flatMap(item => expandBrickInTemplate(item, hostContext))
92
94
  }
93
95
  };
94
96
  return newBrickConf;
95
97
  }
96
- function expandBrickInTemplate(brickConfInTemplate, hostContext) {
98
+ function expandBrickInTemplate(brickConfInTemplate, hostContext, markSlotted) {
97
99
  // Ignore `if: null` to make `looseCheckIf` working.
98
100
  if (brickConfInTemplate.if === null) {
99
101
  delete brickConfInTemplate.if;
100
102
  }
103
+ if (brickConfInTemplate.brick === "slot") {
104
+ markSlotted === null || markSlotted === void 0 || markSlotted();
105
+ return replaceSlotWithSlottedBricks(brickConfInTemplate, hostContext, expandBrickInTemplate);
106
+ }
101
107
  const {
102
108
  properties,
103
109
  slots: slotsInTemplate,
@@ -105,18 +111,22 @@ function expandBrickInTemplate(brickConfInTemplate, hostContext) {
105
111
  ...restBrickConfInTemplate
106
112
  } = brickConfInTemplate;
107
113
  const transpiledSlots = childrenToSlots(childrenInTemplate, slotsInTemplate);
114
+ let slotted = false;
115
+ const markChild = () => {
116
+ slotted = true;
117
+ };
108
118
  const slots = Object.fromEntries(Object.entries(transpiledSlots ?? {}).map(_ref => {
109
119
  let [slotName, slotConf] = _ref;
110
120
  return [slotName, {
111
121
  type: "bricks",
112
- bricks: (slotConf.bricks ?? []).map(item => expandBrickInTemplate(item, hostContext))
122
+ bricks: (slotConf.bricks ?? []).flatMap(item => expandBrickInTemplate(item, hostContext, markChild))
113
123
  }];
114
124
  }));
115
125
  return {
116
126
  ...restBrickConfInTemplate,
117
127
  properties: setupUseBrickInTemplate(properties, hostContext),
118
128
  slots,
119
- ...setupTemplateProxy(hostContext, restBrickConfInTemplate.ref, slots)
129
+ ...setupTemplateProxy(hostContext, restBrickConfInTemplate.ref, slots, slotted)
120
130
  };
121
131
  }
122
132
  //# sourceMappingURL=expandCustomTemplate.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"expandCustomTemplate.js","names":["uniqueId","customTemplates","DataStore","setupTemplateProxy","setupUseBrickInTemplate","childrenToSlots","hooks","expandCustomTemplate","tplTagName","brickConf","hostBrick","asyncHostPropertyEntries","rendererContext","_hooks$flowApi","tplStateStoreId","runtimeContext","forEachItem","forEachIndex","forEachSize","formStateStoreId","tplStateStore","tplStateStoreMap","set","tplStateStoreScope","push","bricks","proxy","state","contracts","get","flowApi","collectWidgetContract","define","slots","originalExternalSlots","children","externalChildren","restBrickConf","newBrickConf","brick","tplHostMetadata","internalBricksByRef","Map","reversedProxies","properties","from","to","Object","entries","proxies","ref","hostContext","externalSlots","type","map","item","expandBrickInTemplate","brickConfInTemplate","if","slotsInTemplate","childrenInTemplate","restBrickConfInTemplate","transpiledSlots","fromEntries","_ref","slotName","slotConf"],"sources":["../../../../src/internal/CustomTemplates/expandCustomTemplate.ts"],"sourcesContent":["import type {\n BrickConf,\n BrickConfInTemplate,\n SlotsConfInTemplate,\n SlotsConfOfBricks,\n UseSingleBrickConf,\n} from \"@next-core/types\";\nimport { uniqueId } from \"lodash\";\nimport { customTemplates } from \"../../CustomTemplates.js\";\nimport { DataStore } from \"../data/DataStore.js\";\nimport { RuntimeBrickConfWithTplSymbols } from \"./constants.js\";\nimport { setupTemplateProxy } from \"./setupTemplateProxy.js\";\nimport type {\n AsyncPropertyEntry,\n RuntimeBrick,\n TemplateHostBrick,\n TemplateHostContext,\n} from \"../interfaces.js\";\nimport { setupUseBrickInTemplate } from \"./setupUseBrickInTemplate.js\";\nimport { childrenToSlots } from \"../Renderer.js\";\nimport { hooks } from \"../Runtime.js\";\nimport type { RendererContext } from \"../RendererContext.js\";\n\nexport function expandCustomTemplate<T extends BrickConf | UseSingleBrickConf>(\n tplTagName: string,\n brickConf: T,\n hostBrick: RuntimeBrick,\n asyncHostPropertyEntries: AsyncPropertyEntry[],\n rendererContext: RendererContext\n): T {\n const tplStateStoreId = uniqueId(\"tpl-state-\");\n const runtimeContext = {\n ...hostBrick.runtimeContext,\n tplStateStoreId,\n };\n\n // There is a boundary for `forEach*` and `FORM_STATE` between template internals and externals.\n delete runtimeContext.forEachItem;\n delete runtimeContext.forEachIndex;\n delete runtimeContext.forEachSize;\n delete runtimeContext.formStateStoreId;\n\n const tplStateStore = new DataStore(\n \"STATE\",\n hostBrick,\n rendererContext,\n tplStateStoreId\n );\n runtimeContext.tplStateStoreMap.set(tplStateStoreId, tplStateStore);\n if (runtimeContext.tplStateStoreScope) {\n runtimeContext.tplStateStoreScope.push(tplStateStore);\n }\n\n const { bricks, proxy, state, contracts } = customTemplates.get(tplTagName)!;\n hooks?.flowApi?.collectWidgetContract(contracts);\n tplStateStore.define(state, runtimeContext, asyncHostPropertyEntries);\n\n const {\n slots: originalExternalSlots,\n children: externalChildren,\n ...restBrickConf\n } = brickConf;\n\n const newBrickConf = {\n ...restBrickConf,\n brick: tplTagName,\n } as T;\n\n hostBrick.tplHostMetadata = {\n internalBricksByRef: new Map(),\n tplStateStoreId,\n proxy,\n };\n\n // Reversed proxies are used for expand storyboard before rendering page.\n const reversedProxies: TemplateHostContext[\"reversedProxies\"] = {\n properties: new Map(),\n slots: new Map(),\n // mergeBases: new Map(),\n };\n\n if (proxy?.properties) {\n for (const [from, to] of Object.entries(proxy.properties)) {\n let proxies = reversedProxies.properties.get(to.ref);\n if (!proxies) {\n proxies = [];\n reversedProxies.properties.set(to.ref, proxies);\n }\n proxies.push({\n from,\n to,\n });\n }\n }\n\n if (proxy?.slots) {\n for (const [from, to] of Object.entries(proxy.slots)) {\n let proxies = reversedProxies.slots.get(to.ref);\n if (!proxies) {\n proxies = [];\n reversedProxies.slots.set(to.ref, proxies);\n }\n proxies.push({\n from,\n to,\n });\n }\n }\n\n const hostContext: TemplateHostContext = {\n reversedProxies,\n asyncHostPropertyEntries,\n externalSlots: childrenToSlots(externalChildren, originalExternalSlots) as\n | SlotsConfOfBricks\n | undefined,\n tplStateStoreId,\n hostBrick: hostBrick as TemplateHostBrick,\n };\n\n newBrickConf.slots = {\n \"\": {\n type: \"bricks\",\n bricks: bricks.map((item) => expandBrickInTemplate(item, hostContext)),\n },\n };\n\n return newBrickConf;\n}\n\nfunction expandBrickInTemplate(\n brickConfInTemplate: BrickConfInTemplate,\n hostContext: TemplateHostContext\n): RuntimeBrickConfWithTplSymbols {\n // Ignore `if: null` to make `looseCheckIf` working.\n if (brickConfInTemplate.if === null) {\n delete brickConfInTemplate.if;\n }\n const {\n properties,\n slots: slotsInTemplate,\n children: childrenInTemplate,\n ...restBrickConfInTemplate\n } = brickConfInTemplate;\n\n const transpiledSlots = childrenToSlots(\n childrenInTemplate,\n slotsInTemplate\n ) as SlotsConfInTemplate | undefined;\n\n const slots: SlotsConfOfBricks = Object.fromEntries(\n Object.entries(transpiledSlots ?? {}).map(([slotName, slotConf]) => [\n slotName,\n {\n type: \"bricks\",\n bricks: (slotConf.bricks ?? []).map((item) =>\n expandBrickInTemplate(item, hostContext)\n ),\n },\n ])\n );\n\n return {\n ...restBrickConfInTemplate,\n properties: setupUseBrickInTemplate(properties, hostContext),\n slots,\n ...setupTemplateProxy(hostContext, restBrickConfInTemplate.ref, slots),\n };\n}\n"],"mappings":"AAOA,SAASA,QAAQ,QAAQ,QAAQ;AACjC,SAASC,eAAe,QAAQ,0BAA0B;AAC1D,SAASC,SAAS,QAAQ,sBAAsB;AAEhD,SAASC,kBAAkB,QAAQ,yBAAyB;AAO5D,SAASC,uBAAuB,QAAQ,8BAA8B;AACtE,SAASC,eAAe,QAAQ,gBAAgB;AAChD,SAASC,KAAK,QAAQ,eAAe;AAGrC,OAAO,SAASC,oBAAoBA,CAClCC,UAAkB,EAClBC,SAAY,EACZC,SAAuB,EACvBC,wBAA8C,EAC9CC,eAAgC,EAC7B;EAAA,IAAAC,cAAA;EACH,MAAMC,eAAe,GAAGd,QAAQ,CAAC,YAAY,CAAC;EAC9C,MAAMe,cAAc,GAAG;IACrB,GAAGL,SAAS,CAACK,cAAc;IAC3BD;EACF,CAAC;;EAED;EACA,OAAOC,cAAc,CAACC,WAAW;EACjC,OAAOD,cAAc,CAACE,YAAY;EAClC,OAAOF,cAAc,CAACG,WAAW;EACjC,OAAOH,cAAc,CAACI,gBAAgB;EAEtC,MAAMC,aAAa,GAAG,IAAIlB,SAAS,CACjC,OAAO,EACPQ,SAAS,EACTE,eAAe,EACfE,eACF,CAAC;EACDC,cAAc,CAACM,gBAAgB,CAACC,GAAG,CAACR,eAAe,EAAEM,aAAa,CAAC;EACnE,IAAIL,cAAc,CAACQ,kBAAkB,EAA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;EAEvB,MAAMK,eAAe,GAAGzD,eAAe,CACrCuD,kBAAkB,EAClBD,eACF,CAAoC;EAEpC,MAAM1B,KAAwB,GAAGc,MAAM,CAACgB,WAAW,CACjDhB,MAAM,CAACC,OAAO,CAACc,eAAe,IAAI,CAAC,CAAC,CAAC,CAACR,GAAG,CAACU,IAAA;IAAA,IAAC,CAACC,QAAQ,EAAEC,QAAQ,CAAC,GAAAF,IAAA;IAAA,OAAK,CAClEC,QAAQ,EACR;MACEZ,IAAI,EAAE,QAAQ;MACd5B,MAAM,EAAE,CAACyC,QAAQ,CAACzC,MAAM,IAAI,EAAE,EAAE6B,GAAG,CAAEC,IAAI,IACvCC,qBAAqB,CAACD,IAAI,EAAEJ,WAAW,CACzC;IACF,CAAC,CACF;EAAA,EACH,CAAC;EAED,OAAO;IACL,GAAGU,uBAAuB;IAC1BjB,UAAU,EAAExC,uBAAuB,CAACwC,UAAU,EAAEO,WAAW,CAAC;IAC5DlB,KAAK;IACL,GAAG9B,kBAAkB,CAACgD,WAAW,EAAEU,uBAAuB,CAACX,GAAG,EAAEjB,KAAK;EACvE,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"expandCustomTemplate.js","names":["uniqueId","customTemplates","DataStore","setupTemplateProxy","setupUseBrickInTemplate","childrenToSlots","hooks","replaceSlotWithSlottedBricks","expandCustomTemplate","tplTagName","brickConf","hostBrick","asyncHostPropertyEntries","rendererContext","_hooks$flowApi","tplStateStoreId","runtimeContext","forEachItem","forEachIndex","forEachSize","formStateStoreId","tplStateStore","tplStateStoreMap","set","tplStateStoreScope","push","bricks","proxy","state","contracts","get","flowApi","collectWidgetContract","define","slots","originalExternalSlots","children","externalChildren","restBrickConf","newBrickConf","brick","tplHostMetadata","internalBricksByRef","Map","reversedProxies","properties","from","to","Object","entries","proxies","ref","hostContext","externalSlots","usedSlots","Set","type","flatMap","item","expandBrickInTemplate","brickConfInTemplate","markSlotted","if","slotsInTemplate","childrenInTemplate","restBrickConfInTemplate","transpiledSlots","slotted","markChild","fromEntries","map","_ref","slotName","slotConf"],"sources":["../../../../src/internal/CustomTemplates/expandCustomTemplate.ts"],"sourcesContent":["import type {\n BrickConf,\n BrickConfInTemplate,\n SlotConfOfBricks,\n SlotsConfInTemplate,\n SlotsConfOfBricks,\n UseSingleBrickConf,\n} from \"@next-core/types\";\nimport { uniqueId } from \"lodash\";\nimport { customTemplates } from \"../../CustomTemplates.js\";\nimport { DataStore } from \"../data/DataStore.js\";\nimport { setupTemplateProxy } from \"./setupTemplateProxy.js\";\nimport type {\n AsyncPropertyEntry,\n RuntimeBrick,\n TemplateHostBrick,\n TemplateHostContext,\n} from \"../interfaces.js\";\nimport { setupUseBrickInTemplate } from \"./setupUseBrickInTemplate.js\";\nimport { childrenToSlots } from \"../Renderer.js\";\nimport { hooks } from \"../Runtime.js\";\nimport type { RendererContext } from \"../RendererContext.js\";\nimport { replaceSlotWithSlottedBricks } from \"./replaceSlotWithSlottedBricks.js\";\n\nexport function expandCustomTemplate<T extends BrickConf | UseSingleBrickConf>(\n tplTagName: string,\n brickConf: T,\n hostBrick: RuntimeBrick,\n asyncHostPropertyEntries: AsyncPropertyEntry[],\n rendererContext: RendererContext\n): T {\n const tplStateStoreId = uniqueId(\"tpl-state-\");\n const runtimeContext = {\n ...hostBrick.runtimeContext,\n tplStateStoreId,\n };\n\n // There is a boundary for `forEach*` and `FORM_STATE` between template internals and externals.\n delete runtimeContext.forEachItem;\n delete runtimeContext.forEachIndex;\n delete runtimeContext.forEachSize;\n delete runtimeContext.formStateStoreId;\n\n const tplStateStore = new DataStore(\n \"STATE\",\n hostBrick,\n rendererContext,\n tplStateStoreId\n );\n runtimeContext.tplStateStoreMap.set(tplStateStoreId, tplStateStore);\n if (runtimeContext.tplStateStoreScope) {\n runtimeContext.tplStateStoreScope.push(tplStateStore);\n }\n\n const { bricks, proxy, state, contracts } = customTemplates.get(tplTagName)!;\n hooks?.flowApi?.collectWidgetContract(contracts);\n tplStateStore.define(state, runtimeContext, asyncHostPropertyEntries);\n\n const {\n slots: originalExternalSlots,\n children: externalChildren,\n ...restBrickConf\n } = brickConf;\n\n const newBrickConf = {\n ...restBrickConf,\n brick: tplTagName,\n } as T;\n\n hostBrick.tplHostMetadata = {\n internalBricksByRef: new Map(),\n tplStateStoreId,\n proxy,\n };\n\n // Reversed proxies are used for expand storyboard before rendering page.\n const reversedProxies: TemplateHostContext[\"reversedProxies\"] = {\n properties: new Map(),\n slots: new Map(),\n // mergeBases: new Map(),\n };\n\n if (proxy?.properties) {\n for (const [from, to] of Object.entries(proxy.properties)) {\n let proxies = reversedProxies.properties.get(to.ref);\n if (!proxies) {\n proxies = [];\n reversedProxies.properties.set(to.ref, proxies);\n }\n proxies.push({\n from,\n to,\n });\n }\n }\n\n if (proxy?.slots) {\n for (const [from, to] of Object.entries(proxy.slots)) {\n let proxies = reversedProxies.slots.get(to.ref);\n if (!proxies) {\n proxies = [];\n reversedProxies.slots.set(to.ref, proxies);\n }\n proxies.push({\n from,\n to,\n });\n }\n }\n\n const hostContext: TemplateHostContext = {\n reversedProxies,\n asyncHostPropertyEntries,\n externalSlots: childrenToSlots(externalChildren, originalExternalSlots) as\n | SlotsConfOfBricks\n | undefined,\n tplStateStoreId,\n hostBrick: hostBrick as TemplateHostBrick,\n usedSlots: new Set(),\n };\n\n newBrickConf.slots = {\n \"\": {\n type: \"bricks\",\n bricks: bricks.flatMap((item) =>\n expandBrickInTemplate(item, hostContext)\n ),\n },\n };\n\n return newBrickConf;\n}\n\nfunction expandBrickInTemplate(\n brickConfInTemplate: BrickConf,\n hostContext: TemplateHostContext,\n markSlotted?: () => void\n): BrickConf | BrickConf[] {\n // Ignore `if: null` to make `looseCheckIf` working.\n if (brickConfInTemplate.if === null) {\n delete brickConfInTemplate.if;\n }\n\n if (brickConfInTemplate.brick === \"slot\") {\n markSlotted?.();\n return replaceSlotWithSlottedBricks(\n brickConfInTemplate,\n hostContext,\n expandBrickInTemplate\n );\n }\n\n const {\n properties,\n slots: slotsInTemplate,\n children: childrenInTemplate,\n ...restBrickConfInTemplate\n } = brickConfInTemplate as BrickConfInTemplate;\n\n const transpiledSlots = childrenToSlots(\n childrenInTemplate,\n slotsInTemplate\n ) as SlotsConfInTemplate | undefined;\n\n let slotted = false;\n const markChild = () => {\n slotted = true;\n };\n const slots = Object.fromEntries<SlotConfOfBricks>(\n Object.entries(transpiledSlots ?? {}).map(([slotName, slotConf]) => [\n slotName,\n {\n type: \"bricks\",\n bricks: (slotConf.bricks ?? []).flatMap((item) =>\n expandBrickInTemplate(item, hostContext, markChild)\n ),\n },\n ])\n );\n\n return {\n ...restBrickConfInTemplate,\n properties: setupUseBrickInTemplate(properties, hostContext),\n slots,\n ...setupTemplateProxy(\n hostContext,\n restBrickConfInTemplate.ref,\n slots,\n slotted\n ),\n };\n}\n"],"mappings":"AAQA,SAASA,QAAQ,QAAQ,QAAQ;AACjC,SAASC,eAAe,QAAQ,0BAA0B;AAC1D,SAASC,SAAS,QAAQ,sBAAsB;AAChD,SAASC,kBAAkB,QAAQ,yBAAyB;AAO5D,SAASC,uBAAuB,QAAQ,8BAA8B;AACtE,SAASC,eAAe,QAAQ,gBAAgB;AAChD,SAASC,KAAK,QAAQ,eAAe;AAErC,SAASC,4BAA4B,QAAQ,mCAAmC;AAEhF,OAAO,SAASC,oBAAoBA,CAClCC,UAAkB,EAClBC,SAAY,EACZC,SAAuB,EACvBC,wBAA8C,EAC9CC,eAAgC,EAC7B;EAAA,IAAAC,cAAA;EACH,MAAMC,eAAe,GAAGf,QAAQ,CAAC,YAAY,CAAC;EAC9C,MAAMgB,cAAc,GAAG;IACrB,GAAGL,SAAS,CAACK,cAAc;IAC3BD;EACF,CAAC;;EAED;EACA,OAAOC,cAAc,CAACC,WAAW;EACjC,OAAOD,cAAc,CAACE,YAAY;EAClC,OAAOF,cAAc,CAACG,WAAW;EACjC,OAAOH,cAAc,CAACI,gBAAgB;EAEtC,MAAMC,aAAa,GAAG,IAAInB,SAAS,CACjC,OAAO,EACPS,S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 -0,0 +1,36 @@
1
+ import { hasOwnProperty } from "@next-core/utils/general";
2
+ import { isEvaluable } from "@next-core/cook";
3
+ import { setupTemplateExternalBricksWithForEach } from "./setupTemplateProxy.js";
4
+ import { childrenToSlots } from "../Renderer.js";
5
+ export function replaceSlotWithSlottedBricks(brickConf, hostContext, expand) {
6
+ var _brickConf$properties, _defaultSlots$;
7
+ // Currently, no support for `if` in a slot.
8
+ if (brickConf.if != null && !brickConf.if || typeof brickConf.if === "string") {
9
+ throw new Error(`Can not use "if" in a slot currently, check your template "${hostContext.hostBrick.type}"`);
10
+ }
11
+ const slot = String(((_brickConf$properties = brickConf.properties) === null || _brickConf$properties === void 0 ? void 0 : _brickConf$properties.name) ?? "");
12
+
13
+ // Currently, no support for expression as slot name.
14
+ if (isEvaluable(slot)) {
15
+ throw new Error(`Can not use an expression as slot name "${slot}" currently, check your template "${hostContext.hostBrick.type}"`);
16
+ }
17
+
18
+ // Do not repeat the same slot name in a template.
19
+ if (hostContext.usedSlots.has(slot)) {
20
+ throw new Error(`Can not have multiple slots with the same name "${slot}", check your template "${hostContext.hostBrick.type}"`);
21
+ }
22
+ hostContext.usedSlots.add(slot);
23
+ if (hostContext.externalSlots && hasOwnProperty(hostContext.externalSlots, slot)) {
24
+ const insertBricks = hostContext.externalSlots[slot].bricks ?? [];
25
+ if (insertBricks.length > 0) {
26
+ const hostCtx = hostContext.hostBrick.runtimeContext;
27
+ // External bricks of a template, should not access the template internal forEach `ITEM`.
28
+ // For some existing templates who is *USING* this bug, we keep the old behavior.
29
+ const hostHasForEach = hasOwnProperty(hostCtx, "forEachItem");
30
+ return hostHasForEach ? setupTemplateExternalBricksWithForEach(insertBricks, hostCtx.forEachItem, hostCtx.forEachIndex, hostCtx.forEachSize) : insertBricks;
31
+ }
32
+ }
33
+ const defaultSlots = childrenToSlots(brickConf.children, brickConf.slots);
34
+ return ((defaultSlots === null || defaultSlots === void 0 || (_defaultSlots$ = defaultSlots[""]) === null || _defaultSlots$ === void 0 ? void 0 : _defaultSlots$.bricks) ?? []).flatMap(item => expand(item, hostContext));
35
+ }
36
+ //# sourceMappingURL=replaceSlotWithSlottedBricks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replaceSlotWithSlottedBricks.js","names":["hasOwnProperty","isEvaluable","setupTemplateExternalBricksWithForEach","childrenToSlots","replaceSlotWithSlottedBricks","brickConf","hostContext","expand","_brickConf$properties","_defaultSlots$","if","Error","hostBrick","type","slot","String","properties","name","usedSlots","has","add","externalSlots","insertBricks","bricks","length","hostCtx","runtimeContext","hostHasForEach","forEachItem","forEachIndex","forEachSize","defaultSlots","children","slots","flatMap","item"],"sources":["../../../../src/internal/CustomTemplates/replaceSlotWithSlottedBricks.ts"],"sourcesContent":["import type {\n BrickConf,\n SlotsConfInTemplate,\n UseSingleBrickConf,\n} from \"@next-core/types\";\nimport { hasOwnProperty } from \"@next-core/utils/general\";\nimport { isEvaluable } from \"@next-core/cook\";\nimport type { TemplateHostContext } from \"../interfaces.js\";\nimport { setupTemplateExternalBricksWithForEach } from \"./setupTemplateProxy.js\";\nimport { childrenToSlots } from \"../Renderer.js\";\n\nexport function replaceSlotWithSlottedBricks<\n T extends BrickConf | UseSingleBrickConf,\n>(\n brickConf: T,\n hostContext: TemplateHostContext,\n expand: (item: T, hostContext: TemplateHostContext) => T | T[]\n): T[] {\n // Currently, no support for `if` in a slot.\n if (\n (brickConf.if != null && !brickConf.if) ||\n typeof brickConf.if === \"string\"\n ) {\n throw new Error(\n `Can not use \"if\" in a slot currently, check your template \"${hostContext.hostBrick.type}\"`\n );\n }\n\n const slot = String(brickConf.properties?.name ?? \"\");\n\n // Currently, no support for expression as slot name.\n if (isEvaluable(slot)) {\n throw new Error(\n `Can not use an expression as slot name \"${slot}\" currently, check your template \"${hostContext.hostBrick.type}\"`\n );\n }\n\n // Do not repeat the same slot name in a template.\n if (hostContext.usedSlots.has(slot)) {\n throw new Error(\n `Can not have multiple slots with the same name \"${slot}\", check your template \"${hostContext.hostBrick.type}\"`\n );\n }\n hostContext.usedSlots.add(slot);\n\n if (\n hostContext.externalSlots &&\n hasOwnProperty(hostContext.externalSlots, slot)\n ) {\n const insertBricks = hostContext.externalSlots[slot].bricks ?? [];\n if (insertBricks.length > 0) {\n const hostCtx = hostContext.hostBrick.runtimeContext;\n // External bricks of a template, should not access the template internal forEach `ITEM`.\n // For some existing templates who is *USING* this bug, we keep the old behavior.\n const hostHasForEach = hasOwnProperty(hostCtx, \"forEachItem\");\n return (\n hostHasForEach\n ? setupTemplateExternalBricksWithForEach(\n insertBricks,\n hostCtx.forEachItem,\n hostCtx.forEachIndex!,\n hostCtx.forEachSize!\n )\n : insertBricks\n ) as T[];\n }\n }\n\n const defaultSlots = childrenToSlots(brickConf.children, brickConf.slots) as\n | SlotsConfInTemplate\n | undefined;\n return (defaultSlots?.[\"\"]?.bricks ?? []).flatMap((item) =>\n expand(item as T, hostContext)\n );\n}\n"],"mappings":"AAKA,SAASA,cAAc,QAAQ,0BAA0B;AACzD,SAASC,WAAW,QAAQ,iBAAiB;AAE7C,SAASC,sCAAsC,QAAQ,yBAAyB;AAChF,SAASC,eAAe,QAAQ,gBAAgB;AAEhD,OAAO,SAASC,4BAA4BA,CAG1CC,SAAY,EACZC,WAAgC,EAChCC,MAA8D,EACzD;EAAA,IAAAC,qBAAA,EAAAC,cAAA;EACL;EACA,IACGJ,SAAS,CAACK,EAAE,IAAI,IAAI,IAAI,CAACL,SAAS,CAACK,EAAE,IACtC,OAAOL,SAAS,CAACK,EAAE,KAAK,QAAQ,EAChC;IACA,MAAM,IAAIC,KAAK,CACb,8DAA8DL,WAAW,CAACM,SAAS,CAACC,IAAI,GAC1F,CAAC;EACH;EAEA,MAAMC,IAAI,GAAGC,MAAM,CAAC,EAAAP,qBAAA,GAAAH,SAAS,CAACW,UAAU,cAAAR,qBAAA,uBAApBA,qBAAA,CAAsBS,IAAI,KAAI,EAAE,CAAC;;EAErD;EACA,IAAIhB,WAAW,CAACa,IAAI,CAAC,EAA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";
3
3
  import { symbolForAsyncComputedPropsFromHost, symbolForTPlExternalForEachIndex, symbolForTPlExternalForEachItem, symbolForTPlExternalForEachSize, symbolForTplStateStoreId } from "./constants.js";
4
4
  import { computePropertyValue } from "../compute/computeRealProperties.js";
5
5
  import { childrenToSlots } from "../Renderer.js";
6
- export function setupTemplateProxy(hostContext, ref, slots) {
6
+ export function setupTemplateProxy(hostContext, ref, slots, slotted) {
7
7
  const {
8
8
  reversedProxies,
9
9
  asyncHostPropertyEntries,
@@ -30,6 +30,9 @@ export function setupTemplateProxy(hostContext, ref, slots) {
30
30
  asyncComputedProps = getComputedProps(asyncHostPropertyEntries);
31
31
  }
32
32
  const slotProxies = reversedProxies.slots.get(ref);
33
+ if (slotProxies && slotted) {
34
+ throw new Error(`Can not have proxied slot ref when the parent has a slot element child, check your template "${hostBrick.type}" and ref "${ref}"`);
35
+ }
33
36
  if (slotProxies && externalSlots) {
34
37
  // Use an approach like template-literal's quasis:
35
38
  // `quasi0${0}quais1${1}quasi2...`
@@ -83,7 +86,7 @@ export function setupTemplateProxy(hostContext, ref, slots) {
83
86
  }
84
87
 
85
88
  // External bricks of a template, have the same forEachItem context as their host.
86
- function setupTemplateExternalBricksWithForEach(bricks, forEachItem, forEachIndex, forEachSize) {
89
+ export function setupTemplateExternalBricksWithForEach(bricks, forEachItem, forEachIndex, forEachSize) {
87
90
  return bricks.map(_ref2 => {
88
91
  let {
89
92
  children,