document-model 6.2.3-dev.9 → 6.2.3-staging.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.
package/README.md CHANGED
@@ -118,12 +118,6 @@ undo(count: number);
118
118
  redo(count: number);
119
119
  ```
120
120
 
121
- - `PRUNE`: Joins multiple operations into a single `LOAD_STATE` operation. Useful to keep operations history smaller. Operations to prune are selected by index, similar to the [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) method in Arrays.
122
-
123
- ```javascript
124
- prune(start?: number, end?: number);
125
- ```
126
-
127
121
  ## Budget Statement Model
128
122
 
129
123
  A Budget statement follows the following data structure:
package/dist/index.d.ts CHANGED
@@ -1,16 +1,15 @@
1
1
  import { Action, AssertIsDocumentOfType, AssertIsStateOfType, CreateState, DocumentAction, DocumentModelAction, DocumentModelDocument, DocumentModelDocumentModelModule, DocumentModelModule, DocumentModelPHState, DocumentOperations, IsDocumentOfType, IsStateOfType, Operation, PHBaseState, PHDocument, PHDocumentHeader } from "@powerhousedao/shared/document-model";
2
2
  export * from "@powerhousedao/shared/document-model";
3
-
4
3
  //#region src/controller.d.ts
5
4
  type ScreamingSnakeToCamel<S extends string> = S extends `${infer Head}_${infer Tail}` ? `${Lowercase<Head>}${Capitalize<ScreamingSnakeToCamel<Tail>>}` : Lowercase<S>;
6
- type DocumentChangeEvent<TState extends PHBaseState = PHBaseState> = {
5
+ export type DocumentChangeEvent<TState extends PHBaseState = PHBaseState> = {
7
6
  document: PHDocument<TState>;
8
7
  };
9
- type DocumentChangeListener<TState extends PHBaseState = PHBaseState> = (event: DocumentChangeEvent<TState>) => void;
10
- type ActionMap<TAction extends Action, TReturn = void> = { [K in (TAction | DocumentAction)["type"] as ScreamingSnakeToCamel<K>]: (input: Extract<TAction | DocumentAction, {
8
+ export type DocumentChangeListener<TState extends PHBaseState = PHBaseState> = (event: DocumentChangeEvent<TState>) => void;
9
+ export type ActionMap<TAction extends Action, TReturn = void> = { [K in (TAction | DocumentAction)["type"] as ScreamingSnakeToCamel<K>]: (input: Extract<TAction | DocumentAction, {
11
10
  type: K;
12
- }>["input"]) => TReturn & ActionMap<TAction, TReturn> };
13
- declare class PHDocumentController<TState extends PHBaseState> implements PHDocument<TState> {
11
+ }>["input"]) => TReturn & ActionMap<TAction, TReturn>; };
12
+ export declare class PHDocumentController<TState extends PHBaseState> implements PHDocument<TState> {
14
13
  readonly module: DocumentModelModule<TState>;
15
14
  protected _document: PHDocument<TState>;
16
15
  private listeners;
@@ -25,11 +24,11 @@ declare class PHDocumentController<TState extends PHBaseState> implements PHDocu
25
24
  private notifyListeners;
26
25
  static forDocumentModel<TState extends PHBaseState, TAction extends Action>(module: DocumentModelModule<TState>): new (initialDocument?: PHDocument<TState>) => PHDocumentController<TState> & ActionMap<TAction, PHDocumentController<TState>>;
27
26
  }
28
- declare const DocumentModelController: new (initialDocument?: PHDocument<DocumentModelPHState> | undefined) => PHDocumentController<DocumentModelPHState> & ActionMap<DocumentModelAction, PHDocumentController<DocumentModelPHState>>;
27
+ export declare const DocumentModelController: new (initialDocument?: PHDocument<DocumentModelPHState> | undefined) => PHDocumentController<DocumentModelPHState> & ActionMap<DocumentModelAction, PHDocumentController<DocumentModelPHState>>;
29
28
  //#endregion
30
29
  //#region src/logger-types.d.ts
31
- type LoggerErrorHandler = (...data: any[]) => void;
32
- type ILogger = {
30
+ export type LoggerErrorHandler = (...data: any[]) => void;
31
+ export type ILogger = {
33
32
  level: "verbose" | "debug" | "info" | "warn" | "error";
34
33
  verbose: (message: string, ...replacements: any[]) => void;
35
34
  debug: (message: string, ...replacements: any[]) => void;
@@ -48,7 +47,7 @@ declare const LOG_LEVELS: {
48
47
  readonly warn: 3;
49
48
  readonly error: 4;
50
49
  };
51
- declare class ConsoleLogger implements ILogger {
50
+ export declare class ConsoleLogger implements ILogger {
52
51
  #private;
53
52
  errorHandler: LoggerErrorHandler;
54
53
  constructor(tags?: string[], handler?: LoggerErrorHandler);
@@ -61,21 +60,21 @@ declare class ConsoleLogger implements ILogger {
61
60
  warn: (message: string, ...replacements: any[]) => void;
62
61
  error: (message: string, ...replacements: any[]) => void;
63
62
  }
64
- declare const logger: ILogger;
65
- declare const setLogLevel: (level: ILogger["level"]) => void;
66
- declare const setErrorHandler: (handler: LoggerErrorHandler) => void;
67
- declare const childLogger: (tags: string[]) => ILogger;
63
+ export declare const logger: ILogger;
64
+ export declare const setLogLevel: (level: ILogger["level"]) => void;
65
+ export declare const setErrorHandler: (handler: LoggerErrorHandler) => void;
66
+ export declare const childLogger: (tags: string[]) => ILogger;
68
67
  //#endregion
69
68
  //#region src/module.d.ts
70
- declare const documentModelDocumentModelModule: DocumentModelDocumentModelModule;
69
+ export declare const documentModelDocumentModelModule: DocumentModelDocumentModelModule;
71
70
  //#endregion
72
71
  //#region src/state.d.ts
73
- declare const isStateOfType: IsStateOfType<DocumentModelPHState>;
74
- declare const assertIsStateOfType: AssertIsStateOfType<DocumentModelPHState>;
75
- declare const isDocumentOfType: IsDocumentOfType<DocumentModelPHState>;
76
- declare const assertIsDocumentOfType: AssertIsDocumentOfType<DocumentModelPHState>;
77
- declare const documentModelCreateState: CreateState<DocumentModelPHState>;
78
- declare function documentModelCreateDocument(state?: Partial<DocumentModelPHState>): DocumentModelDocument;
72
+ export declare const isStateOfType: IsStateOfType<DocumentModelPHState>;
73
+ export declare const assertIsStateOfType: AssertIsStateOfType<DocumentModelPHState>;
74
+ export declare const isDocumentOfType: IsDocumentOfType<DocumentModelPHState>;
75
+ export declare const assertIsDocumentOfType: AssertIsDocumentOfType<DocumentModelPHState>;
76
+ export declare const documentModelCreateState: CreateState<DocumentModelPHState>;
77
+ export declare function documentModelCreateDocument(state?: Partial<DocumentModelPHState>): DocumentModelDocument;
79
78
  //#endregion
80
- export { ActionMap, ConsoleLogger, DocumentChangeEvent, DocumentChangeListener, DocumentModelController, ILogger, LoggerErrorHandler, PHDocumentController, assertIsDocumentOfType, assertIsStateOfType, childLogger, documentModelCreateDocument, documentModelCreateState, documentModelDocumentModelModule, isDocumentOfType, isStateOfType, logger, setErrorHandler, setLogLevel };
79
+ export {};
81
80
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/controller.ts","../src/logger-types.ts","../src/logger.ts","../src/module.ts","../src/state.ts"],"mappings":";;;;KAcK,qBAAA,qBACH,CAAA,4CACO,SAAA,CAAU,IAAA,IAAQ,UAAA,CAAW,qBAAA,CAAsB,IAAA,OACtD,SAAA,CAAU,CAAA;AAAA,KAEJ,mBAAA,gBAAmC,WAAA,GAAc,WAAA;EAC3D,QAAA,EAAU,UAAA,CAAW,MAAA;AAAA;AAAA,KAGX,sBAAA,gBAAsC,WAAA,GAAc,WAAA,KAC9D,KAAA,EAAO,mBAAA,CAAoB,MAAA;AAAA,KAGjB,SAAA,iBAA0B,MAAA,6BAC7B,OAAA,GAAU,cAAA,aAA2B,qBAAA,CAAsB,CAAA,KAChE,KAAA,EAAO,OAAA,CAAQ,OAAA,GAAU,cAAA;EAAkB,IAAA,EAAM,CAAA;AAAA,gBAC9C,OAAA,GAAU,SAAA,CAAU,OAAA,EAAS,OAAA;AAAA,cAGvB,oBAAA,gBACI,WAAA,aACJ,UAAA,CAAW,MAAA;EAAA,SACb,MAAA,EAAQ,mBAAA,CAAoB,MAAA;EAAA,UAC3B,SAAA,EAAW,UAAA,CAAW,MAAA;EAAA,QACxB,SAAA;cAGN,MAAA,EAAQ,mBAAA,CAAoB,MAAA,GAC5B,eAAA,GAAkB,UAAA,CAAW,MAAA;EAAA,IAkB3B,QAAA,CAAA,GAAY,UAAA,CAAW,MAAA;EAAA,IAIvB,MAAA,CAAA,GAAU,gBAAA;EAAA,IAGV,KAAA,CAAA,GAAS,MAAA;EAAA,IAGT,YAAA,CAAA,GAAgB,MAAA;EAAA,IAGhB,UAAA,CAAA,GAAc,kBAAA;EAAA,IAGd,SAAA,CAAA,GAAa,SAAA;EAIjB,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,qBAAqB;;qBAIjC,8BAAuB,kBAAA,WAAA,sCAAA,qBAAA,wBAAA,UAAA,qBAAA,qBAAA;;;YC7GxB,yBAAyB;YAEzB;EACV;EAEA,UAAU,oBAAoB;EAC9B,QAAQ,oBAAoB;EAC5B,OAAO,oBAAoB;EAC3B,OAAO,oBAAoB;EAC3B,QAAQ,oBAAoB;EAE5B,cAAc;EAEd,QAAQ,mBAAmB;;;;cCsEvB;WACJ;WACA;WACA;WACA;WACA;;qBAGW,yBAAyB;;EAKpC,cAAc;EAEd,YAAY,iBAAiB,UAAU;MAOnC,sBAAsB;MAMtB,MAAM,oBAAoB;EAI9B,MAAM,iBAAiB;EAevB,UAAO,oBAAmB;EAa1B,QAAK,oBAAmB;EAaxB,OAAI,oBAAmB;EAavB,OAAI,oBAAmB;EAavB,QAAK,oBAAmB;;qBAeb,QAAQ;qBAGR,cAAW,OAAW;qBAItB,kBAAe,SAAa;qBAK5B,cAAW,mBAAqB;;;qBCjLhC,kCAAkC;;;qBCVlC,eAAe,cAAc;qBAI7B,qBAAqB,oBAAoB;qBAMzC,kBAAkB,iBAAiB;qBAMnC,wBAAwB,uBACnC;qBAIW,0BAA0B,YAAY;wBAanC,4BACd,QAAQ,QAAQ,wBACf"}
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#tags","#tagString","#level","#includeStack"],"sources":["../src/state.ts","../src/module.ts","../src/controller.ts","../src/logger.ts"],"sourcesContent":["import type {\n AssertIsDocumentOfType,\n AssertIsStateOfType,\n CreateState,\n DocumentModelDocument,\n DocumentModelGlobalState,\n DocumentModelPHState,\n IsDocumentOfType,\n IsStateOfType,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n assertIsDocumentModelDocument,\n assertIsDocumentModelState,\n baseCreateDocument,\n defaultBaseState,\n documentModelDocumentType,\n documentModelInitialGlobalState,\n documentModelInitialLocalState,\n isDocumentModelDocument,\n isDocumentModelState,\n} from \"@powerhousedao/shared/document-model\";\n\nexport const isStateOfType: IsStateOfType<DocumentModelPHState> = (state) => {\n return isDocumentModelState(state);\n};\n\nexport const assertIsStateOfType: AssertIsStateOfType<DocumentModelPHState> = (\n state,\n) => {\n assertIsDocumentModelState(state);\n};\n\nexport const isDocumentOfType: IsDocumentOfType<DocumentModelPHState> = (\n document,\n) => {\n return isDocumentModelDocument(document);\n};\n\nexport const assertIsDocumentOfType: AssertIsDocumentOfType<\n DocumentModelPHState\n> = (document) => {\n assertIsDocumentModelDocument(document);\n};\nexport const documentModelCreateState: CreateState<DocumentModelPHState> = (\n state,\n) => {\n return {\n ...defaultBaseState(),\n global: {\n ...documentModelInitialGlobalState,\n ...((state?.global ?? {}) as DocumentModelGlobalState),\n },\n local: { ...documentModelInitialLocalState, ...(state?.local ?? {}) },\n };\n};\n\nexport function documentModelCreateDocument(\n state?: Partial<DocumentModelPHState>,\n): DocumentModelDocument {\n return baseCreateDocument(\n documentModelCreateState,\n state,\n documentModelDocumentType,\n );\n}\n","import type { DocumentModelDocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport {\n actions,\n createState,\n defaultBaseState,\n documentModelFileExtension,\n documentModelGlobalState,\n documentModelLoadFromInput,\n documentModelReducer,\n documentModelSaveToFileHandle,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n assertIsDocumentOfType,\n assertIsStateOfType,\n documentModelCreateDocument,\n documentModelCreateState,\n isDocumentOfType,\n isStateOfType,\n} from \"./state.js\";\n\nconst utils = {\n fileExtension: documentModelFileExtension,\n createState: documentModelCreateState,\n createDocument: documentModelCreateDocument,\n loadFromInput: documentModelLoadFromInput,\n saveToFileHandle: documentModelSaveToFileHandle,\n isStateOfType,\n assertIsStateOfType,\n isDocumentOfType,\n assertIsDocumentOfType,\n};\n\nexport const documentModelDocumentModelModule: DocumentModelDocumentModelModule =\n {\n reducer: documentModelReducer,\n documentModel: createState(defaultBaseState(), documentModelGlobalState),\n actions,\n utils,\n };\n","import {\n type Action,\n type DocumentAction,\n type DocumentModelAction,\n type DocumentModelModule,\n type DocumentModelPHState,\n type DocumentOperations,\n type Operation,\n type PHBaseState,\n type PHDocument,\n type PHDocumentHeader,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule } from \"./module.js\";\n\ntype ScreamingSnakeToCamel<S extends string> =\n S extends `${infer Head}_${infer Tail}`\n ? `${Lowercase<Head>}${Capitalize<ScreamingSnakeToCamel<Tail>>}`\n : Lowercase<S>;\n\nexport type DocumentChangeEvent<TState extends PHBaseState = PHBaseState> = {\n document: PHDocument<TState>;\n};\n\nexport type DocumentChangeListener<TState extends PHBaseState = PHBaseState> = (\n event: DocumentChangeEvent<TState>,\n) => void;\n\nexport type ActionMap<TAction extends Action, TReturn = void> = {\n [K in (TAction | DocumentAction)[\"type\"] as ScreamingSnakeToCamel<K>]: (\n input: Extract<TAction | DocumentAction, { type: K }>[\"input\"],\n ) => TReturn & ActionMap<TAction, TReturn>;\n};\n\nexport class PHDocumentController<\n TState extends PHBaseState,\n> implements PHDocument<TState> {\n readonly module: DocumentModelModule<TState>;\n protected _document: PHDocument<TState>;\n private listeners: DocumentChangeListener<TState>[] = [];\n\n constructor(\n module: DocumentModelModule<TState>,\n initialDocument?: PHDocument<TState>,\n ) {\n this.module = module;\n this._document = initialDocument ?? module.utils.createDocument();\n\n // dynamically add action methods to the controller\n for (const actionType in this.module.actions) {\n Object.defineProperty(this, actionType, {\n value: (input: unknown) => {\n const action = this.module.actions[actionType](input);\n this._document = this.module.reducer(this._document, action);\n this.notifyListeners();\n return this;\n },\n });\n }\n }\n\n get document(): PHDocument<TState> {\n return this._document;\n }\n\n get header(): PHDocumentHeader {\n return this.document.header;\n }\n get state(): TState {\n return this.document.state;\n }\n get initialState(): TState {\n return this.document.initialState;\n }\n get operations(): DocumentOperations {\n return this.document.operations;\n }\n get clipboard(): Operation[] {\n return this.document.clipboard;\n }\n\n onChange(listener: DocumentChangeListener<TState>): () => void {\n this.listeners.push(listener);\n return () => {\n this.listeners = this.listeners.filter((l) => l !== listener);\n };\n }\n\n private notifyListeners(): void {\n if (this.listeners.length === 0) return;\n const event: DocumentChangeEvent<TState> = { document: this._document };\n for (const listener of this.listeners) {\n listener(event);\n }\n }\n\n static forDocumentModel<TState extends PHBaseState, TAction extends Action>(\n module: DocumentModelModule<TState>,\n ) {\n return class extends PHDocumentController<TState> {\n constructor(initialDocument?: PHDocument<TState>) {\n super(module, initialDocument);\n }\n } as unknown as new (\n initialDocument?: PHDocument<TState>,\n ) => PHDocumentController<TState> &\n ActionMap<TAction, PHDocumentController<TState>>;\n }\n}\n\nexport const DocumentModelController = PHDocumentController.forDocumentModel<\n DocumentModelPHState,\n DocumentModelAction\n>(documentModelDocumentModelModule);\n","import type { ILogger, LoggerErrorHandler } from \"./logger-types.js\";\n\nconst tokenSub = /@([a-zA-Z0-9_]+)/g;\nconst dtf = new Intl.DateTimeFormat(undefined, {\n hour12: false,\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n fractionalSecondDigits: 2,\n});\n\nconst stringify = (value: unknown, includeStack: boolean): string => {\n if (value === null || value === undefined) return \"null\";\n if (typeof value === \"string\") return value;\n if (value instanceof Error) {\n const base = `${value.name}: ${value.message}`;\n return includeStack && value.stack ? `${base}\\n${value.stack}` : base;\n }\n if (typeof value === \"object\") {\n try {\n return JSON.stringify(value);\n } catch {\n // Circular or otherwise non-serializable object; fall back to the\n // base tag (e.g. \"[object Object]\") without tripping no-base-to-string.\n return Object.prototype.toString.call(value);\n }\n }\n if (typeof value === \"function\") {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n const name = (value as Function).name;\n return name ? `${name}()` : \"anonymous()\";\n }\n // Remaining primitives (number, boolean, bigint, symbol) stringify cleanly.\n return String(value as number | boolean | bigint | symbol);\n};\n\nconst formatMessage = (\n tagString: string,\n message: string,\n replacements: any[],\n includeStack: boolean,\n): [string, Record<string, any>] => {\n const meta: Record<string, any> = {};\n const uniqueTokens: string[] = [];\n\n let results;\n while ((results = tokenSub.exec(message)) !== null) {\n const tokenName = results[1];\n const index = uniqueTokens.indexOf(tokenName);\n if (index === -1) {\n uniqueTokens.push(tokenName);\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const replacement = replacements[uniqueTokens.length - 1];\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n meta[tokenName] = replacement;\n }\n }\n\n // replace\n for (const [key, value] of Object.entries(meta)) {\n message = message.replaceAll(`@${key}`, stringify(value, includeStack));\n }\n\n // Any replacements past the unique-token count would otherwise be\n // silently dropped — append them so positional Errors still surface.\n const extras = replacements.slice(uniqueTokens.length);\n if (extras.length > 0) {\n message = `${message} ${extras.map((v) => stringify(v, includeStack)).join(\" \")}`;\n }\n\n if (tagString.length > 0) {\n message = `${tagString} ${message}`;\n }\n\n // timestamp\n const now = new Date();\n const timestamp = dtf.format(now);\n meta[\"timestamp\"] = timestamp;\n\n return [message, meta];\n};\n\nconst LOG_LEVELS = {\n verbose: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n} as const;\n\nexport class ConsoleLogger implements ILogger {\n #tags: string[];\n #tagString: string;\n #level: number = LOG_LEVELS.info;\n\n errorHandler: LoggerErrorHandler;\n\n constructor(tags?: string[], handler?: LoggerErrorHandler) {\n this.#tags = tags || [];\n this.#tagString = this.#tags.map((tag) => `[${tag}]`).join(\"\");\n\n this.errorHandler = handler ?? (() => {});\n }\n\n get level(): keyof typeof LOG_LEVELS {\n return Object.keys(LOG_LEVELS).find(\n (key) => LOG_LEVELS[key as keyof typeof LOG_LEVELS] === this.#level,\n ) as keyof typeof LOG_LEVELS;\n }\n\n set level(value: keyof typeof LOG_LEVELS) {\n this.#level = LOG_LEVELS[value];\n }\n\n child(tags: string[]): ILogger {\n const logger = new ConsoleLogger(\n [...this.#tags, ...tags],\n this.errorHandler,\n );\n logger.level = this.level;\n return logger;\n }\n\n // Errors get full stacks only at debug/verbose; at info/warn/error we\n // emit `name: message` to keep production logs readable.\n get #includeStack(): boolean {\n return this.#level <= LOG_LEVELS.debug;\n }\n\n verbose = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.verbose) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.debug(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n debug = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.debug) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.debug(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n info = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.info) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.info(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n warn = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.warn) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.warn(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n error = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.error) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.error(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n}\n\n// Singleton instance\nexport const logger: ILogger = new ConsoleLogger();\n\n// Global configuration\nexport const setLogLevel = (level: ILogger[\"level\"]) => {\n logger.level = level;\n};\n\nexport const setErrorHandler = (handler: LoggerErrorHandler) => {\n logger.errorHandler = handler;\n};\n\n// Backwards-compatible factory function\nexport const childLogger = (tags: string[]): ILogger => {\n return logger.child(tags);\n};\n"],"mappings":";;;AAsBA,MAAa,iBAAsD,UAAU;AAC3E,QAAO,qBAAqB,MAAM;;AAGpC,MAAa,uBACX,UACG;AACH,4BAA2B,M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e,WAAW,SAAS;GACrC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,MAAA,WACA,SACA,cACA,MAAA,aACD;AAED,WAAQ,MAAM,IAAI,KAAK,aAAa,IAAI,mBAAmB;;;CAI/D,SAAS,SAAiB,GAAG,iBAA8B;AACzD,MAAI,MAAA,SAAe,WAAW,OAAO;GACnC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,MAAA,WACA,SACA,cACA,MAAA,aACD;AAED,WAAQ,MAAM,IAAI,KAAK,aAAa,IAAI,mBAAmB;;;CAI/D,QAAQ,SAAiB,GAAG,iBAA8B;AACxD,MAAI,MAAA,SAAe,WAAW,MAAM;GAClC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,MAAA,WACA,SACA,cACA,MAAA,aACD;AAED,WAAQ,KAAK,IAAI,KAAK,aAAa,IAAI,mBAAmB;;;CAI9D,QAAQ,SAAiB,GAAG,iBAA8B;AACxD,MAAI,MAAA,SAAe,WAAW,MAAM;GAClC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,MAAA,WACA,SACA,cACA,MAAA,aACD;AAED,WAAQ,KAAK,IAAI,KAAK,aAAa,IAAI,mBAAmB;;;CAI9D,SAAS,SAAiB,GAAG,iBAA8B;AACzD,MAAI,MAAA,SAAe,WAAW,OAAO;GACnC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,MAAA,WACA,SACA,cACA,MAAA,aACD;AAED,WAAQ,MAAM,IAAI,KAAK,aAAa,IAAI,mBAAmB;;;;AAMjE,MAAa,SAAkB,IAAI,eAAe;AAGlD,MAAa,eAAe,UAA4B;AACtD,QAAO,QAAQ;;AAGjB,MAAa,mBAAmB,YAAgC;AAC9D,QAAO,eAAe;;AAIxB,MAAa,eAAe,SAA4B;AACtD,QAAO,OAAO,MAAM,KAAK"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/state.ts","../src/module.ts","../src/controller.ts","../src/logger.ts"],"sourcesContent":["import type {\n AssertIsDocumentOfType,\n AssertIsStateOfType,\n CreateState,\n DocumentModelDocument,\n DocumentModelGlobalState,\n DocumentModelPHState,\n IsDocumentOfType,\n IsStateOfType,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n assertIsDocumentModelDocument,\n assertIsDocumentModelState,\n baseCreateDocument,\n defaultBaseState,\n documentModelDocumentType,\n documentModelInitialGlobalState,\n documentModelInitialLocalState,\n isDocumentModelDocument,\n isDocumentModelState,\n} from \"@powerhousedao/shared/document-model\";\n\nexport const isStateOfType: IsStateOfType<DocumentModelPHState> = (state) => {\n return isDocumentModelState(state);\n};\n\nexport const assertIsStateOfType: AssertIsStateOfType<DocumentModelPHState> = (\n state,\n) => {\n assertIsDocumentModelState(state);\n};\n\nexport const isDocumentOfType: IsDocumentOfType<DocumentModelPHState> = (\n document,\n) => {\n return isDocumentModelDocument(document);\n};\n\nexport const assertIsDocumentOfType: AssertIsDocumentOfType<\n DocumentModelPHState\n> = (document) => {\n assertIsDocumentModelDocument(document);\n};\nexport const documentModelCreateState: CreateState<DocumentModelPHState> = (\n state,\n) => {\n return {\n ...defaultBaseState(),\n global: {\n ...documentModelInitialGlobalState,\n ...((state?.global ?? {}) as DocumentModelGlobalState),\n },\n local: { ...documentModelInitialLocalState, ...(state?.local ?? {}) },\n };\n};\n\nexport function documentModelCreateDocument(\n state?: Partial<DocumentModelPHState>,\n): DocumentModelDocument {\n return baseCreateDocument(\n documentModelCreateState,\n state,\n documentModelDocumentType,\n );\n}\n","import type { DocumentModelDocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport {\n actions,\n createState,\n defaultBaseState,\n documentModelFileExtension,\n documentModelGlobalState,\n documentModelLoadFromInput,\n documentModelReducer,\n documentModelSaveToFileHandle,\n} from \"@powerhousedao/shared/document-model\";\nimport {\n assertIsDocumentOfType,\n assertIsStateOfType,\n documentModelCreateDocument,\n documentModelCreateState,\n isDocumentOfType,\n isStateOfType,\n} from \"./state.js\";\n\nconst utils = {\n fileExtension: documentModelFileExtension,\n createState: documentModelCreateState,\n createDocument: documentModelCreateDocument,\n loadFromInput: documentModelLoadFromInput,\n saveToFileHandle: documentModelSaveToFileHandle,\n isStateOfType,\n assertIsStateOfType,\n isDocumentOfType,\n assertIsDocumentOfType,\n};\n\nexport const documentModelDocumentModelModule: DocumentModelDocumentModelModule =\n {\n reducer: documentModelReducer,\n documentModel: createState(defaultBaseState(), documentModelGlobalState),\n actions,\n utils,\n };\n","import {\n type Action,\n type DocumentAction,\n type DocumentModelAction,\n type DocumentModelModule,\n type DocumentModelPHState,\n type DocumentOperations,\n type Operation,\n type PHBaseState,\n type PHDocument,\n type PHDocumentHeader,\n} from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule } from \"./module.js\";\n\ntype ScreamingSnakeToCamel<S extends string> =\n S extends `${infer Head}_${infer Tail}`\n ? `${Lowercase<Head>}${Capitalize<ScreamingSnakeToCamel<Tail>>}`\n : Lowercase<S>;\n\nexport type DocumentChangeEvent<TState extends PHBaseState = PHBaseState> = {\n document: PHDocument<TState>;\n};\n\nexport type DocumentChangeListener<TState extends PHBaseState = PHBaseState> = (\n event: DocumentChangeEvent<TState>,\n) => void;\n\nexport type ActionMap<TAction extends Action, TReturn = void> = {\n [K in (TAction | DocumentAction)[\"type\"] as ScreamingSnakeToCamel<K>]: (\n input: Extract<TAction | DocumentAction, { type: K }>[\"input\"],\n ) => TReturn & ActionMap<TAction, TReturn>;\n};\n\nexport class PHDocumentController<\n TState extends PHBaseState,\n> implements PHDocument<TState> {\n readonly module: DocumentModelModule<TState>;\n protected _document: PHDocument<TState>;\n private listeners: DocumentChangeListener<TState>[] = [];\n\n constructor(\n module: DocumentModelModule<TState>,\n initialDocument?: PHDocument<TState>,\n ) {\n this.module = module;\n this._document = initialDocument ?? module.utils.createDocument();\n\n // dynamically add action methods to the controller\n for (const actionType in this.module.actions) {\n Object.defineProperty(this, actionType, {\n value: (input: unknown) => {\n const action = this.module.actions[actionType](input);\n this._document = this.module.reducer(this._document, action);\n this.notifyListeners();\n return this;\n },\n });\n }\n }\n\n get document(): PHDocument<TState> {\n return this._document;\n }\n\n get header(): PHDocumentHeader {\n return this.document.header;\n }\n get state(): TState {\n return this.document.state;\n }\n get initialState(): TState {\n return this.document.initialState;\n }\n get operations(): DocumentOperations {\n return this.document.operations;\n }\n get clipboard(): Operation[] {\n return this.document.clipboard;\n }\n\n onChange(listener: DocumentChangeListener<TState>): () => void {\n this.listeners.push(listener);\n return () => {\n this.listeners = this.listeners.filter((l) => l !== listener);\n };\n }\n\n private notifyListeners(): void {\n if (this.listeners.length === 0) return;\n const event: DocumentChangeEvent<TState> = { document: this._document };\n for (const listener of this.listeners) {\n listener(event);\n }\n }\n\n static forDocumentModel<TState extends PHBaseState, TAction extends Action>(\n module: DocumentModelModule<TState>,\n ) {\n return class extends PHDocumentController<TState> {\n constructor(initialDocument?: PHDocument<TState>) {\n super(module, initialDocument);\n }\n } as unknown as new (\n initialDocument?: PHDocument<TState>,\n ) => PHDocumentController<TState> &\n ActionMap<TAction, PHDocumentController<TState>>;\n }\n}\n\nexport const DocumentModelController = PHDocumentController.forDocumentModel<\n DocumentModelPHState,\n DocumentModelAction\n>(documentModelDocumentModelModule);\n","import type { ILogger, LoggerErrorHandler } from \"./logger-types.js\";\n\nconst tokenSub = /@([a-zA-Z0-9_]+)/g;\nconst dtf = new Intl.DateTimeFormat(undefined, {\n hour12: false,\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n fractionalSecondDigits: 2,\n});\n\nconst stringify = (value: unknown, includeStack: boolean): string => {\n if (value === null || value === undefined) return \"null\";\n if (typeof value === \"string\") return value;\n if (value instanceof Error) {\n const base = `${value.name}: ${value.message}`;\n return includeStack && value.stack ? `${base}\\n${value.stack}` : base;\n }\n if (typeof value === \"object\") {\n try {\n return JSON.stringify(value);\n } catch {\n // Circular or otherwise non-serializable object; fall back to the\n // base tag (e.g. \"[object Object]\") without tripping no-base-to-string.\n return Object.prototype.toString.call(value);\n }\n }\n if (typeof value === \"function\") {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n const name = (value as Function).name;\n return name ? `${name}()` : \"anonymous()\";\n }\n // Remaining primitives (number, boolean, bigint, symbol) stringify cleanly.\n return String(value as number | boolean | bigint | symbol);\n};\n\nconst formatMessage = (\n tagString: string,\n message: string,\n replacements: any[],\n includeStack: boolean,\n): [string, Record<string, any>] => {\n const meta: Record<string, any> = {};\n const uniqueTokens: string[] = [];\n\n let results;\n while ((results = tokenSub.exec(message)) !== null) {\n const tokenName = results[1];\n const index = uniqueTokens.indexOf(tokenName);\n if (index === -1) {\n uniqueTokens.push(tokenName);\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const replacement = replacements[uniqueTokens.length - 1];\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n meta[tokenName] = replacement;\n }\n }\n\n // replace\n for (const [key, value] of Object.entries(meta)) {\n message = message.replaceAll(`@${key}`, stringify(value, includeStack));\n }\n\n // Any replacements past the unique-token count would otherwise be\n // silently dropped — append them so positional Errors still surface.\n const extras = replacements.slice(uniqueTokens.length);\n if (extras.length > 0) {\n message = `${message} ${extras.map((v) => stringify(v, includeStack)).join(\" \")}`;\n }\n\n if (tagString.length > 0) {\n message = `${tagString} ${message}`;\n }\n\n // timestamp\n const now = new Date();\n const timestamp = dtf.format(now);\n meta[\"timestamp\"] = timestamp;\n\n return [message, meta];\n};\n\nconst LOG_LEVELS = {\n verbose: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n} as const;\n\nexport class ConsoleLogger implements ILogger {\n #tags: string[];\n #tagString: string;\n #level: number = LOG_LEVELS.info;\n\n errorHandler: LoggerErrorHandler;\n\n constructor(tags?: string[], handler?: LoggerErrorHandler) {\n this.#tags = tags || [];\n this.#tagString = this.#tags.map((tag) => `[${tag}]`).join(\"\");\n\n this.errorHandler = handler ?? (() => {});\n }\n\n get level(): keyof typeof LOG_LEVELS {\n return Object.keys(LOG_LEVELS).find(\n (key) => LOG_LEVELS[key as keyof typeof LOG_LEVELS] === this.#level,\n ) as keyof typeof LOG_LEVELS;\n }\n\n set level(value: keyof typeof LOG_LEVELS) {\n this.#level = LOG_LEVELS[value];\n }\n\n child(tags: string[]): ILogger {\n const logger = new ConsoleLogger(\n [...this.#tags, ...tags],\n this.errorHandler,\n );\n logger.level = this.level;\n return logger;\n }\n\n // Errors get full stacks only at debug/verbose; at info/warn/error we\n // emit `name: message` to keep production logs readable.\n get #includeStack(): boolean {\n return this.#level <= LOG_LEVELS.debug;\n }\n\n verbose = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.verbose) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.debug(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n debug = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.debug) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.debug(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n info = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.info) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.info(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n warn = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.warn) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.warn(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n\n error = (message: string, ...replacements: any[]): void => {\n if (this.#level <= LOG_LEVELS.error) {\n const [formattedMessage, meta] = formatMessage(\n this.#tagString,\n message,\n replacements,\n this.#includeStack,\n );\n\n console.error(`[${meta[\"timestamp\"]}] ${formattedMessage}`);\n }\n };\n}\n\n// Singleton instance\nexport const logger: ILogger = new ConsoleLogger();\n\n// Global configuration\nexport const setLogLevel = (level: ILogger[\"level\"]) => {\n logger.level = level;\n};\n\nexport const setErrorHandler = (handler: LoggerErrorHandler) => {\n logger.errorHandler = handler;\n};\n\n// Backwards-compatible factory function\nexport const childLogger = (tags: string[]): ILogger => {\n return logger.child(tags);\n};\n"],"mappings":";;;AAsBA,MAAa,iBAAsD,UAAU;CAC3E,OAAO,qBAAqB,KAAK;AACnC;AAEA,MAAa,uBACX,UACG;CACH,2BAA2B,KAAK;AAClC;AAEA,MAAa,oBACX,aACG;CACH,OAAO,wBAAwB,QAAQ;AACzC;AAEA,MAAa,0BAER,aAAa;CAChB,8BAA8B,QAAQ;AACxC;AACA,MAAa,4BACX,UACG;CACH,OAAO;EACL,GAAG,iBAAiB;EACpB,QAAQ;GACN,GAAG;GACH,GAAK,OAAO,UAAU,CAAC;EACzB;EACA,OAAO;GAAE,GAAG;GAAgC,GAAI,OAAO,SAAS,CAAC;EAAG;CACtE;AACF;AAEA,SAAgB,4BACd,OACuB;CACvB,OAAO,mBACL,0BACA,OACA,yBACF;AACF;;;AC5CA,MAAM,QAAQ;CACZ,eAAe;CACf,aAAa;CACb,gBAAgB;CAChB,eAAe;CACf,kBAAkB;CAClB;CACA;CACA;CACA;AACF;AAEA,MAAa,mCACX;CACE,SAAS;CACT,eAAe,YAAY,iBAAiB,GAAG,wBAAwB;CACvE;CACA;AACF;;;ACLF,IAAa,uBAAb,MAAa,qBAEmB;CAC9B;CACA;CACA,YAAsD,CAAC;CAEvD,YACE,QACA,iBACA;EACA,KAAK,SAAS;EACd,KAAK,YAAY,mBAAmB,OAAO,MAAM,eAAe;EAGhE,KAAK,MAAM,cAAc,KAAK,OAAO,SACnC,OAAO,eAAe,MAAM,YAAY,EACtC,QAAQ,UAAmB;GACzB,MAAM,SAAS,KAAK,OAAO,QAAQ,WAAW,CAAC,KAAK;GACpD,KAAK,YAAY,KAAK,OAAO,QAAQ,KAAK,WAAW,MAAM;GAC3D,KAAK,gBAAgB;GACrB,OAAO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AAS,SAAiB,GAAG,iBAA8B;EACzD,IAAI,KAAK,UAAU,WAAW,OAAO;GACnC,MAAM,CAAC,kBAAkB,QAAQ,cAC/B,KAAK,YACL,SACA,cACA,KAAK,aACP;GAEA,QAAQ,MAAM,IAAI,KAAK,aAAa,IAAI,kBAAkB;EAC5D;CACF;AACF;AAGA,MAAa,SAAkB,IAAI,cAAc;AAGjD,MAAa,eAAe,UAA4B;CACtD,OAAO,QAAQ;AACjB;AAEA,MAAa,mBAAmB,YAAgC;CAC9D,OAAO,eAAe;AACxB;AAGA,MAAa,eAAe,SAA4B;CACtD,OAAO,OAAO,MAAM,IAAI;AAC1B"}
package/dist/mock.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  import { generateMock } from "@powerhousedao/shared/document-model/mock";
2
- export { generateMock };
2
+ export { generateMock };
3
+ export {};
package/dist/node.d.mts CHANGED
@@ -1,15 +1,14 @@
1
1
  import { MinimalBackupData, PHBaseState, PHDocument, Reducer, ReplayDocumentOptions, VersionedReplayConfig } from "@powerhousedao/shared/document-model";
2
2
  import { BinaryLike } from "node:crypto";
3
-
4
3
  //#region node.d.mts
5
- declare function writeFileNode(path: string, name: string, data: Uint8Array): Promise<string>;
6
- declare function readFileNode(path: string): NonSharedBuffer;
7
- declare function fetchFileNode(url: string): Promise<{
4
+ export declare function writeFileNode(path: string, name: string, data: Uint8Array): Promise<string>;
5
+ export declare function readFileNode(path: string): NonSharedBuffer;
6
+ export declare function fetchFileNode(url: string): Promise<{
8
7
  buffer: Buffer;
9
8
  mimeType?: string;
10
9
  }>;
11
- declare const getFileNode: (file: string) => Promise<NonSharedBuffer>;
12
- declare const hashNode: (data: BinaryLike, algorithm?: string, encoding?: "base64" | "hex", _params?: Record<string, unknown>) => string;
10
+ export declare const getFileNode: (file: string) => Promise<NonSharedBuffer>;
11
+ export declare const hashNode: (data: BinaryLike, algorithm?: string, encoding?: "base64" | "hex", _params?: Record<string, unknown>) => string;
13
12
  /**
14
13
  * Loads a document from a ZIP file.
15
14
  *
@@ -25,7 +24,7 @@ declare const hashNode: (data: BinaryLike, algorithm?: string, encoding?: "base6
25
24
  * @returns A promise that resolves to the document state after applying all the operations.
26
25
  * @throws An error if the initial state or the operations history is not found in the ZIP file.
27
26
  */
28
- declare function baseLoadFromFile<TState extends PHBaseState = PHBaseState>(path: string, reducer: Reducer<TState>, options?: ReplayDocumentOptions): Promise<PHDocument<TState>>;
27
+ export declare function baseLoadFromFile<TState extends PHBaseState = PHBaseState>(path: string, reducer: Reducer<TState>, options?: ReplayDocumentOptions): Promise<PHDocument<TState>>;
29
28
  /**
30
29
  * Loads a version-aware document from a ZIP file.
31
30
  *
@@ -35,13 +34,13 @@ declare function baseLoadFromFile<TState extends PHBaseState = PHBaseState>(path
35
34
  * @param options - Optional replay options.
36
35
  * @returns A promise that resolves to the document state after versioned replay.
37
36
  */
38
- declare function baseLoadFromFileVersioned<TState extends PHBaseState = PHBaseState>(path: string, config: VersionedReplayConfig, options?: ReplayDocumentOptions): Promise<PHDocument<TState>>;
37
+ export declare function baseLoadFromFileVersioned<TState extends PHBaseState = PHBaseState>(path: string, config: VersionedReplayConfig, options?: ReplayDocumentOptions): Promise<PHDocument<TState>>;
39
38
  /**
40
39
  * Saves a minimal document backup to a .phd file.
41
40
  * Used when the full document is not available (e.g., in onOperations handler).
42
41
  * Creates a file with minimal header and empty operations.
43
42
  */
44
- declare function baseMinimalSaveToFile(data: MinimalBackupData, path: string, extension: string): Promise<string>;
43
+ export declare function baseMinimalSaveToFile(data: MinimalBackupData, path: string, extension: string): Promise<string>;
45
44
  /**
46
45
  * Saves a document to a ZIP file.
47
46
  *
@@ -54,7 +53,7 @@ declare function baseMinimalSaveToFile(data: MinimalBackupData, path: string, ex
54
53
  * @param extension - The extension to use for the file.
55
54
  * @returns A promise that resolves to the path of the saved file.
56
55
  */
57
- declare function baseSaveToFile(document: PHDocument, path: string, extension: string, name?: string): Promise<string>;
56
+ export declare function baseSaveToFile(document: PHDocument, path: string, extension: string, name?: string): Promise<string>;
58
57
  //#endregion
59
- export { baseLoadFromFile, baseLoadFromFileVersioned, baseMinimalSaveToFile, baseSaveToFile, fetchFileNode, getFileNode, hashNode, readFileNode, writeFileNode };
58
+ export {};
60
59
  //# sourceMappingURL=node.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.mts","names":[],"sources":["../node.mts"],"mappings":";;;;iBAkBgB,aAAA,CACd,IAAA,UACA,IAAA,UACA,IAAA,EAAM,UAAA,GACL,OAAA;AAAA,iBAuBa,YAAA,CAAa,IAAA,WAAY,eAAA;AAAA,iBAIzB,aAAA,CACd,GAAA,WACC,OAAA;EAAU,MAAA,EAAQ,MAAA;EAAQ,QAAA;AAAA;AAAA,cAoBhB,WAAA,GAAe,IAAA,aAAY,OAAA,CAAA,eAAA;AAAA,cAI3B,QAAA,GACX,IAAA,EAAM,UAAA,EACN,SAAA,WACA,QAAA,qBACA,OAAA,GAAU,MAAA;;;;;;AAlCZ;;;;;AAIA;;;;;iBA8DsB,gBAAA,gBACL,WAAA,GAAc,WAAA,CAAA,CAE7B,IAAA,UACA,OAAA,EAAS,OAAA,CAAQ,MAAA,GACjB,OAAA,GAAU,qBAAA,GACT,OAAA,CAAQ,UAAA,CAAW,MAAA;;;;;;AA9CtB;;;;iBA4DsB,yBAAA,gBACL,WAAA,GAAc,WAAA,CAAA,CAE7B,IAAA,UACA,MAAA,EAAQ,qBAAA,EACR,OAAA,GAAU,qBAAA,GACT,OAAA,CAAQ,UAAA,CAAW,MAAA;;;;;AA9DtB;iBAwEsB,qBAAA,CACpB,IAAA,EAAM,iBAAA,EACN,IAAA,UACA,SAAA,WAAiB,OAAA;;;;;;;;;;;AAvCnB;;iBAiEsB,cAAA,CACpB,QAAA,EAAU,UAAA,EACV,IAAA,UACA,SAAA,UACA,IAAA,YAAa,OAAA"}
1
+ {"version":3,"file":"node.d.mts","names":[],"sources":["../node.mts"],"mappings":";;;wBAkBgB,cACd,cACA,cACA,MAAM,aACL;wBAuBa,aAAa,eAAY;wBAIzB,cACd,cACC;EAAU,QAAQ;EAAQ;;qBAoBhB,cAAW,iBAAgB,QAAA;qBAI3B,WAAQ,MACb,YAAU,oBAAA,6BAEU,UAChB;;;;;;;;;;;;;;;;wBAgCU,iBACpB,eAAe,cAAc,aAE7B,cACA,SAAS,QAAQ,SACjB,UAAU,wBACT,QAAQ,WAAW;;;;;;;;;;wBAcA,0BACpB,eAAe,cAAc,aAE7B,cACA,QAAQ,uBACR,UAAU,wBACT,QAAQ,WAAW;;;;;;wBAUA,sBACpB,MAAM,mBACN,cACA,oBAAiB;;;;;;;;;;;;;wBA0BG,eACpB,UAAU,YACV,cACA,mBACA,gBAAa"}
package/dist/node.mjs CHANGED
@@ -69,7 +69,8 @@ const hashNode = (data, algorithm = "sha1", encoding = "base64", _params) => {
69
69
  * @throws An error if the initial state or the operations history is not found in the ZIP file.
70
70
  */
71
71
  async function baseLoadFromFile(path, reducer, options) {
72
- return baseLoadFromInput(readFileNode(path), reducer, options);
72
+ const file = readFileNode(path);
73
+ return baseLoadFromInput(file, reducer, options);
73
74
  }
74
75
  /**
75
76
  * Loads a version-aware document from a ZIP file.
@@ -81,7 +82,8 @@ async function baseLoadFromFile(path, reducer, options) {
81
82
  * @returns A promise that resolves to the document state after versioned replay.
82
83
  */
83
84
  async function baseLoadFromFileVersioned(path, config, options) {
84
- return baseLoadFromInputVersioned(readFileNode(path), config, options);
85
+ const file = readFileNode(path);
86
+ return baseLoadFromInputVersioned(file, config, options);
85
87
  }
86
88
  /**
87
89
  * Saves a minimal document backup to a .phd file.
package/dist/node.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.mjs","names":[],"sources":["../node.mts"],"sourcesContent":["import {\n baseLoadFromInput,\n baseLoadFromInputVersioned,\n createMinimalZip,\n createZip,\n type MinimalBackupData,\n type PHBaseState,\n type PHDocument,\n type Reducer,\n type ReplayDocumentOptions,\n type VersionedReplayConfig,\n} from \"@powerhousedao/shared/document-model\";\nimport type { BinaryLike } from \"node:crypto\";\nimport { createHash } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport https from \"node:https\";\nimport { join } from \"node:path\";\n\nexport function writeFileNode(\n path: string,\n name: string,\n data: Uint8Array,\n): Promise<string> {\n const filePath = join(path, name);\n fs.mkdirSync(path, { recursive: true });\n\n return new Promise((resolve, reject) => {\n try {\n fs.writeFile(filePath, data, {}, (err) => {\n if (err) {\n reject(err);\n } else {\n resolve(filePath);\n }\n });\n } catch (error: unknown) {\n if (error instanceof Error) {\n reject(error);\n } else {\n reject(new Error(String(error)));\n }\n }\n });\n}\n\nexport function readFileNode(path: string) {\n return fs.readFileSync(path);\n}\n\nexport function fetchFileNode(\n url: string,\n): Promise<{ buffer: Buffer; mimeType?: string }> {\n return new Promise((resolve, reject) => {\n https\n .get(url, (resp) => {\n const data: Uint8Array[] = [];\n const mimeType = resp.headers[\"content-type\"];\n resp.on(\"data\", (chunk: Uint8Array) => {\n data.push(chunk);\n });\n\n resp.on(\"end\", () => {\n resolve({ buffer: Buffer.concat(data), mimeType });\n });\n })\n .on(\"error\", (err) => {\n reject(err);\n });\n });\n}\n\nexport const getFileNode = (file: string) => {\n return Promise.resolve(readFileNode(file));\n};\n\nexport const hashNode = (\n data: BinaryLike,\n algorithm = \"sha1\",\n encoding: \"base64\" | \"hex\" = \"base64\",\n _params?: Record<string, unknown>,\n) => {\n if (![\"sha1\", \"sha256\", \"sha512\"].includes(algorithm)) {\n throw new Error(\n `Hashing algorithm not supported: \"${algorithm}\". Available: sha1, sha256, sha512`,\n );\n }\n\n if (![\"base64\", \"hex\"].includes(encoding)) {\n throw new Error(\n `Hash encoding not supported: \"${encoding}\". Available: base64, hex`,\n );\n }\n\n return createHash(algorithm).update(data).digest(encoding);\n};\n\n/**\n * Loads a document from a ZIP file.\n *\n * @remarks\n * This function reads a ZIP file and returns the document state after\n * applying all the operations. The reducer is used to apply the operations.\n *\n * @typeParam S - The type of the state object.\n * @typeParam A - The type of the actions that can be applied to the state object.\n *\n * @param path - The path to the ZIP file.\n * @param reducer - The reducer to apply the operations to the state object.\n * @returns A promise that resolves to the document state after applying all the operations.\n * @throws An error if the initial state or the operations history is not found in the ZIP file.\n */\nexport async function baseLoadFromFile<\n TState extends PHBaseState = PHBaseState,\n>(\n path: string,\n reducer: Reducer<TState>,\n options?: ReplayDocumentOptions,\n): Promise<PHDocument<TState>> {\n const file = readFileNode(path);\n return baseLoadFromInput(file, reducer, options);\n}\n\n/**\n * Loads a version-aware document from a ZIP file.\n *\n * @typeParam TState - The type of the state object.\n * @param path - The path to the ZIP file.\n * @param config - Versioned replay config with per-version reducers and optional upgrade manifest.\n * @param options - Optional replay options.\n * @returns A promise that resolves to the document state after versioned replay.\n */\nexport async function baseLoadFromFileVersioned<\n TState extends PHBaseState = PHBaseState,\n>(\n path: string,\n config: VersionedReplayConfig,\n options?: ReplayDocumentOptions,\n): Promise<PHDocument<TState>> {\n const file = readFileNode(path);\n return baseLoadFromInputVersioned<TState>(file, config, options);\n}\n\n/**\n * Saves a minimal document backup to a .phd file.\n * Used when the full document is not available (e.g., in onOperations handler).\n * Creates a file with minimal header and empty operations.\n */\nexport async function baseMinimalSaveToFile(\n data: MinimalBackupData,\n path: string,\n extension: string,\n) {\n const file = await createMinimalZip(data);\n const fileExtension = extension ? `.${extension}.phd` : \".phd\";\n\n return writeFileNode(\n path,\n data.name.endsWith(fileExtension)\n ? data.name\n : `${data.name}${fileExtension}`,\n file,\n );\n}\n\n/**\n * Saves a document to a ZIP file.\n *\n * @remarks\n * This function creates a ZIP file containing the document's state and\n * operations. The file is saved to the specified path.\n *\n * @param document - The document to save to the file.\n * @param path - The path to save the file to.\n * @param extension - The extension to use for the file.\n * @returns A promise that resolves to the path of the saved file.\n */\nexport async function baseSaveToFile(\n document: PHDocument,\n path: string,\n extension: string,\n name?: string,\n) {\n const file = await createZip(document);\n const fileName = name ?? document.header.name;\n const fileExtension = extension ? `.${extension}.phd` : \".phd\";\n\n return writeFileNode(\n path,\n fileName.endsWith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KAAK,CAAC,OAAO,SAAS;;;;;;;;;;;;;;;;;AAkB5D,eAAsB,iBAGpB,MACA,SACA,SAC6B;AAE7B,QAAO,kBADM,aAAa,KAAK,EACA,SAAS,QAAQ;;;;;;;;;;;AAYlD,eAAsB,0BAGpB,MACA,QACA,SAC6B;AAE7B,QAAO,2BADM,aAAa,KAAK,EACiB,QAAQ,QAAQ;;;;;;;AAQlE,eAAsB,sBACpB,MACA,MACA,WACA;CACA,MAAM,OAAO,MAAM,iBAAiB,KAAK;CACzC,MAAM,gBAAgB,YAAY,IAAI,UAAU,QAAQ;AAExD,QAAO,cACL,MACA,KAAK,KAAK,SAAS,cAAc,GAC7B,KAAK,OACL,GAAG,KAAK,OAAO,iBACnB,KACD;;;;;;;;;;;;;;AAeH,eAAsB,eACpB,UACA,MACA,WACA,MACA;CACA,MAAM,OAAO,MAAM,UAAU,SAAS;CACtC,MAAM,WAAW,QAAQ,SAAS,OAAO;CACzC,MAAM,gBAAgB,YAAY,IAAI,UAAU,QAAQ;AAExD,QAAO,cACL,MACA,SAAS,SAAS,cAAc,GAAG,WAAW,GAAG,WAAW,iBAC5D,KACD"}
1
+ {"version":3,"file":"node.mjs","names":[],"sources":["../node.mts"],"sourcesContent":["import {\n baseLoadFromInput,\n baseLoadFromInputVersioned,\n createMinimalZip,\n createZip,\n type MinimalBackupData,\n type PHBaseState,\n type PHDocument,\n type Reducer,\n type ReplayDocumentOptions,\n type VersionedReplayConfig,\n} from \"@powerhousedao/shared/document-model\";\nimport type { BinaryLike } from \"node:crypto\";\nimport { createHash } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport https from \"node:https\";\nimport { join } from \"node:path\";\n\nexport function writeFileNode(\n path: string,\n name: string,\n data: Uint8Array,\n): Promise<string> {\n const filePath = join(path, name);\n fs.mkdirSync(path, { recursive: true });\n\n return new Promise((resolve, reject) => {\n try {\n fs.writeFile(filePath, data, {}, (err) => {\n if (err) {\n reject(err);\n } else {\n resolve(filePath);\n }\n });\n } catch (error: unknown) {\n if (error instanceof Error) {\n reject(error);\n } else {\n reject(new Error(String(error)));\n }\n }\n });\n}\n\nexport function readFileNode(path: string) {\n return fs.readFileSync(path);\n}\n\nexport function fetchFileNode(\n url: string,\n): Promise<{ buffer: Buffer; mimeType?: string }> {\n return new Promise((resolve, reject) => {\n https\n .get(url, (resp) => {\n const data: Uint8Array[] = [];\n const mimeType = resp.headers[\"content-type\"];\n resp.on(\"data\", (chunk: Uint8Array) => {\n data.push(chunk);\n });\n\n resp.on(\"end\", () => {\n resolve({ buffer: Buffer.concat(data), mimeType });\n });\n })\n .on(\"error\", (err) => {\n reject(err);\n });\n });\n}\n\nexport const getFileNode = (file: string) => {\n return Promise.resolve(readFileNode(file));\n};\n\nexport const hashNode = (\n data: BinaryLike,\n algorithm = \"sha1\",\n encoding: \"base64\" | \"hex\" = \"base64\",\n _params?: Record<string, unknown>,\n) => {\n if (![\"sha1\", \"sha256\", \"sha512\"].includes(algorithm)) {\n throw new Error(\n `Hashing algorithm not supported: \"${algorithm}\". Available: sha1, sha256, sha512`,\n );\n }\n\n if (![\"base64\", \"hex\"].includes(encoding)) {\n throw new Error(\n `Hash encoding not supported: \"${encoding}\". Available: base64, hex`,\n );\n }\n\n return createHash(algorithm).update(data).digest(encoding);\n};\n\n/**\n * Loads a document from a ZIP file.\n *\n * @remarks\n * This function reads a ZIP file and returns the document state after\n * applying all the operations. The reducer is used to apply the operations.\n *\n * @typeParam S - The type of the state object.\n * @typeParam A - The type of the actions that can be applied to the state object.\n *\n * @param path - The path to the ZIP file.\n * @param reducer - The reducer to apply the operations to the state object.\n * @returns A promise that resolves to the document state after applying all the operations.\n * @throws An error if the initial state or the operations history is not found in the ZIP file.\n */\nexport async function baseLoadFromFile<\n TState extends PHBaseState = PHBaseState,\n>(\n path: string,\n reducer: Reducer<TState>,\n options?: ReplayDocumentOptions,\n): Promise<PHDocument<TState>> {\n const file = readFileNode(path);\n return baseLoadFromInput(file, reducer, options);\n}\n\n/**\n * Loads a version-aware document from a ZIP file.\n *\n * @typeParam TState - The type of the state object.\n * @param path - The path to the ZIP file.\n * @param config - Versioned replay config with per-version reducers and optional upgrade manifest.\n * @param options - Optional replay options.\n * @returns A promise that resolves to the document state after versioned replay.\n */\nexport async function baseLoadFromFileVersioned<\n TState extends PHBaseState = PHBaseState,\n>(\n path: string,\n config: VersionedReplayConfig,\n options?: ReplayDocumentOptions,\n): Promise<PHDocument<TState>> {\n const file = readFileNode(path);\n return baseLoadFromInputVersioned<TState>(file, config, options);\n}\n\n/**\n * Saves a minimal document backup to a .phd file.\n * Used when the full document is not available (e.g., in onOperations handler).\n * Creates a file with minimal header and empty operations.\n */\nexport async function baseMinimalSaveToFile(\n data: MinimalBackupData,\n path: string,\n extension: string,\n) {\n const file = await createMinimalZip(data);\n const fileExtension = extension ? `.${extension}.phd` : \".phd\";\n\n return writeFileNode(\n path,\n data.name.endsWith(fileExtension)\n ? data.name\n : `${data.name}${fileExtension}`,\n file,\n );\n}\n\n/**\n * Saves a document to a ZIP file.\n *\n * @remarks\n * This function creates a ZIP file containing the document's state and\n * operations. The file is saved to the specified path.\n *\n * @param document - The document to save to the file.\n * @param path - The path to save the file to.\n * @param extension - The extension to use for the file.\n * @returns A promise that resolves to the path of the saved file.\n */\nexport async function baseSaveToFile(\n document: PHDocument,\n path: string,\n extension: string,\n name?: string,\n) {\n const file = await createZip(document);\n const fileName = name ?? document.header.name;\n const fileExtension = extension ? `.${extension}.phd` : \".phd\";\n\n return writeFileNode(\n path,\n fileName.endsWith(fileExtension) ? fileName : `${fileName}${fileExtension}`,\n file,\n );\n}\n"],"mappings":";;;;;;AAkBA,SAAgB,cACd,MACA,MACA,MACiB;CACjB,MAAM,WAAW,KAAK,MAAM,IAAI;CAChC,GAAG,UAAU,MAAM,EAAE,WAAW,KAAK,CAAC;CAEtC,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,IAAI;GACF,GAAG,UAAU,UAAU,MAAM,CAAC,IAAI,QAAQ;IACxC,IAAI,KAC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GpB,MACA,QACA,SAC6B;CAC7B,MAAM,OAAO,aAAa,IAAI;CAC9B,OAAO,2BAAmC,MAAM,QAAQ,OAAO;AACjE;;;;;;AAOA,eAAsB,sBACpB,MACA,MACA,WACA;CACA,MAAM,OAAO,MAAM,iBAAiB,IAAI;CACxC,MAAM,gBAAgB,YAAY,IAAI,UAAU,QAAQ;CAExD,OAAO,cACL,MACA,KAAK,KAAK,SAAS,aAAa,IAC5B,KAAK,OACL,GAAG,KAAK,OAAO,iBACnB,IACF;AACF;;;;;;;;;;;;;AAcA,eAAsB,eACpB,UACA,MACA,WACA,MACA;CACA,MAAM,OAAO,MAAM,UAAU,QAAQ;CACrC,MAAM,WAAW,QAAQ,SAAS,OAAO;CACzC,MAAM,gBAAgB,YAAY,IAAI,UAAU,QAAQ;CAExD,OAAO,cACL,MACA,SAAS,SAAS,aAAa,IAAI,WAAW,GAAG,WAAW,iBAC5D,IACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document-model",
3
- "version": "6.2.3-dev.9",
3
+ "version": "6.2.3-staging.0",
4
4
  "license": "AGPL-3.0-only",
5
5
  "private": false,
6
6
  "files": [
@@ -45,15 +45,14 @@
45
45
  "@types/mime": "^4.0.0",
46
46
  "@types/node": "25.2.3",
47
47
  "change-case": "5.4.4",
48
- "jest": "^30.0.5",
49
48
  "mutative": "^1.0.5",
50
- "tsdown": "0.21.1",
51
- "tsx": "4.21.0",
49
+ "tsdown": "0.23.0",
50
+ "tsx": "4.23.13",
52
51
  "vitest": "4.1.1",
53
52
  "zod": "4.3.6"
54
53
  },
55
54
  "dependencies": {
56
- "@powerhousedao/shared": "6.2.3-dev.9"
55
+ "@powerhousedao/shared": "6.2.3-staging.0"
57
56
  },
58
57
  "description": "Powerhouse document model — foundational data structure for local-first, event-sourced documents with typed operations, reducers, and GraphQL schema validation.",
59
58
  "keywords": [
@@ -70,7 +69,7 @@
70
69
  "homepage": "https://academy.vetra.io/academy/Reference/DocumentModels",
71
70
  "scripts": {
72
71
  "tsc": "tsc",
73
- "lint": "eslint",
72
+ "lint": "cd ../.. && oxlint packages/document-model",
74
73
  "test": "vitest --run",
75
74
  "test:watch": "vitest watch",
76
75
  "build": "tsx ./build.ts"