prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack | .parseLine(extra.stack.split('\n')[0])
} |
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " file,\n line: er.loc.line,\n column: er.loc.column + 1,\n }\n } else {\n // parse out the 'at' bit from the first line.\n extra.at = stack.parseLine(splitst[1])\n }\n extra.stack = stack.clean(splitst)\n }",
"score": 0.8100846409797668
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const res = { ...object }\n if (hasOwn(res, 'stack') && !hasOwn(res, 'at')) {\n res.at = stack.parseLine(res.stack.split('\\n')[0])\n }\n const file = res.at && res.at.file && resolve(res.at.file)\n if (\n !options.stackIncludesTap &&\n file &&\n file.includes(tapDir)\n ) {",
"score": 0.7940845489501953
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " Object.defineProperty(er, 'message', {\n value: '',\n configurable: true\n })\n } catch {}\n }\n const st = er.stack && er.stack.substr(\n er._babel ? (message + er.codeFrame).length : 0)\n if (st) {\n const splitst = st.split('\\n')",
"score": 0.7919418215751648
},
{
"filename": "src/base.ts",
"retrieved_chunk": " } else if (!er.stack) {\n console.error(er)\n } else {\n if (message) {\n er.message = message\n }\n delete extra.stack\n delete extra.at\n console.error('%s: %s', er.name || 'Error', message)\n console.error(",
"score": 0.7815345525741577
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (!er || typeof er !== 'object') {\n extra.error = er\n return extra\n }\n // pull out error details\n const message = er.message ? er.message\n : er.stack ? er.stack.split('\\n')[0]\n : ''\n if (er.message) {\n try {",
"score": 0.7806823253631592
}
] | typescript | .parseLine(extra.stack.split('\n')[0])
} |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton. | innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
} |
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
.then(async (response) => {
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "\t\tconst { contentEl } = this\n\t\tconst titleEl = contentEl.createDiv(\"title\")\n\t\ttitleEl.addClass(\"modal__title\")\n\t\ttitleEl.setText(this.title)\n\t\tconst textEl = contentEl.createDiv(\"text\")\n\t\ttextEl.addClass(\"modal__text\")\n\t\ttextEl.setText(this.displayedText)\n\t\t// Copy text when clicked\n\t\ttextEl.addEventListener(\"click\", () => {\n\t\t\tnavigator.clipboard.writeText(this.displayedText)",
"score": 0.7460681200027466
},
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "\t\t\tnew Notice(\"Copied to clipboard\")\n\t\t})\n\t\ttextEl.addEventListener(\"contextmenu\", () => {\n\t\t\tnavigator.clipboard.writeText(this.displayedText)\n\t\t\tnew Notice(\"Copied to clipboard\")\n\t\t})\n\t}\n\tonClose() {\n\t\tconst { contentEl } = this\n\t\tcontentEl.empty()",
"score": 0.7344515323638916
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t}\n\t\t\t},\n\t\t})\n\t\t// Also add redact to the right-click context menu\n\t\tthis.registerEvent(\n\t\t\tthis.app.workspace.on(\"editor-menu\", (menu: Menu, editor, view) => {\n\t\t\t\tmenu.addItem((item) => {\n\t\t\t\t\titem.setTitle(\"Redact\")\n\t\t\t\t\titem.setIcon(\"aimentor\")\n\t\t\t\t\titem.onClick(() => {",
"score": 0.7216019034385681
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\t\tthis.plugin.settings.token = change\n\t\t\t\t\t\tthis.plugin.saveSettings()\n\t\t\t\t\t})\n\t\t\t})\n\t\t\t.addButton((button: ButtonComponent) => {\n\t\t\t\tbutton.setButtonText(\"Generate token\")\n\t\t\t\tbutton.onClick((evt: MouseEvent) => {\n\t\t\t\t\twindow.open(\"https://platform.openai.com/account/api-keys\")\n\t\t\t\t})\n\t\t\t})",
"score": 0.709675669670105
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t},\n\t\t})\n\t\t// Also add ELI5 to the right-click context menu\n\t\t// todo: clean to avoid code duplication\n\t\tthis.registerEvent(\n\t\t\tthis.app.workspace.on(\"editor-menu\", (menu: Menu, editor, view) => {\n\t\t\t\tmenu.addItem((item) => {\n\t\t\t\t\titem.setTitle(\"Explain Like I'm 5\")\n\t\t\t\t\titem.setIcon(\"aimentor\")\n\t\t\t\t\titem.onClick(() => {",
"score": 0.7031975388526917
}
] | typescript | innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
} |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML | = CopyIcon
actionButton.onclick = () => { |
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
.then(async (response) => {
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "\t\tconst { contentEl } = this\n\t\tconst titleEl = contentEl.createDiv(\"title\")\n\t\ttitleEl.addClass(\"modal__title\")\n\t\ttitleEl.setText(this.title)\n\t\tconst textEl = contentEl.createDiv(\"text\")\n\t\ttextEl.addClass(\"modal__text\")\n\t\ttextEl.setText(this.displayedText)\n\t\t// Copy text when clicked\n\t\ttextEl.addEventListener(\"click\", () => {\n\t\t\tnavigator.clipboard.writeText(this.displayedText)",
"score": 0.7606234550476074
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t}\n\t\t\t},\n\t\t})\n\t\t// Also add redact to the right-click context menu\n\t\tthis.registerEvent(\n\t\t\tthis.app.workspace.on(\"editor-menu\", (menu: Menu, editor, view) => {\n\t\t\t\tmenu.addItem((item) => {\n\t\t\t\t\titem.setTitle(\"Redact\")\n\t\t\t\t\titem.setIcon(\"aimentor\")\n\t\t\t\t\titem.onClick(() => {",
"score": 0.7238219976425171
},
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "\t\t\tnew Notice(\"Copied to clipboard\")\n\t\t})\n\t\ttextEl.addEventListener(\"contextmenu\", () => {\n\t\t\tnavigator.clipboard.writeText(this.displayedText)\n\t\t\tnew Notice(\"Copied to clipboard\")\n\t\t})\n\t}\n\tonClose() {\n\t\tconst { contentEl } = this\n\t\tcontentEl.empty()",
"score": 0.7215980291366577
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t},\n\t\t})\n\t\t// Also add ELI5 to the right-click context menu\n\t\t// todo: clean to avoid code duplication\n\t\tthis.registerEvent(\n\t\t\tthis.app.workspace.on(\"editor-menu\", (menu: Menu, editor, view) => {\n\t\t\t\tmenu.addItem((item) => {\n\t\t\t\t\titem.setTitle(\"Explain Like I'm 5\")\n\t\t\t\t\titem.setIcon(\"aimentor\")\n\t\t\t\t\titem.onClick(() => {",
"score": 0.7012200951576233
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\tthis.settings.token,\n\t\t\t\t\tthis.settings.preferredMentorId,\n\t\t\t\t\tthis.settings.model,\n\t\t\t\t\tthis.settings.language\n\t\t\t\t)\n\t\t)\n\t\t// This creates an icon in the left ribbon.\n\t\taddIcon(\"aimentor\", MentorIcon)\n\t\tconst ribbonIconEl = this.addRibbonIcon(\n\t\t\t\"aimentor\",",
"score": 0.6836165189743042
}
] | typescript | = CopyIcon
actionButton.onclick = () => { |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
| .then(async (response) => { |
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t// Get the explanation\n\t\t\t\t\talfred\n\t\t\t\t\t\t.execute(selection, commands.explain)\n\t\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\t\tif (response) {\n\t\t\t\t\t\t\t\t// Show the explanation\n\t\t\t\t\t\t\t\tloadingModal.close()\n\t\t\t\t\t\t\t\tnew MentorModal(\n\t\t\t\t\t\t\t\t\tthis.app,\n\t\t\t\t\t\t\t\t\ttitle,",
"score": 0.801460325717926
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t\t\talfred\n\t\t\t\t\t\t\t\t.execute(selection, commands.explain)\n\t\t\t\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\t\t\t\tif (response) {\n\t\t\t\t\t\t\t\t\t\t// Show the explanation\n\t\t\t\t\t\t\t\t\t\tloadingModal.close()\n\t\t\t\t\t\t\t\t\t\tnew MentorModal(\n\t\t\t\t\t\t\t\t\t\t\tthis.app,\n\t\t\t\t\t\t\t\t\t\t\ttitle,\n\t\t\t\t\t\t\t\t\t\t\tresponse[0] // Only one possible response",
"score": 0.7838570475578308
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 0.7833040356636047
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\tDEFAULT_SETTINGS,\n\t\t\tawait this.loadData()\n\t\t)\n\t}\n\tasync saveSettings() {\n\t\tawait this.saveData(this.settings)\n\t}\n\tasync getCompletion() {\n\t\tconsole.log(\"OK\")\n\t}",
"score": 0.7755448222160339
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\tcontent: newMentor.systemPrompt[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t}\n\treset() {\n\t\tthis.history = [\n\t\t\t{\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: this.mentor.systemPrompt[this.preferredLanguage],\n\t\t\t},",
"score": 0.7649847269058228
}
] | typescript | .then(async (response) => { |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl. | text = mentor[1].name[this.preferredLanguage]
} |
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
.then(async (response) => {
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 0.7417775392532349
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t.setDesc(\"The mentor you'd like to talk to in priority.\")\n\t\t\t.addDropdown((dropdown) => {\n\t\t\t\tmentorIds.forEach((id) => {\n\t\t\t\t\tdropdown.addOption(id, mentorList[id].name.en)\n\t\t\t\t})\n\t\t\t\tdropdown.setValue(\n\t\t\t\t\tthis.plugin.settings.preferredMentorId || \"default\"\n\t\t\t\t)\n\t\t\t\tdropdown.onChange((value) => {\n\t\t\t\t\tthis.plugin.settings.preferredMentorId = value",
"score": 0.7291545867919922
},
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "\t\tconst { contentEl } = this\n\t\tconst titleEl = contentEl.createDiv(\"title\")\n\t\ttitleEl.addClass(\"modal__title\")\n\t\ttitleEl.setText(this.title)\n\t\tconst textEl = contentEl.createDiv(\"text\")\n\t\ttextEl.addClass(\"modal__text\")\n\t\ttextEl.setText(this.displayedText)\n\t\t// Copy text when clicked\n\t\ttextEl.addEventListener(\"click\", () => {\n\t\t\tnavigator.clipboard.writeText(this.displayedText)",
"score": 0.7259204983711243
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Preferred Model\")\n\t\t\t.setDesc(\"The model you want to use.\")\n\t\t\t.addDropdown((dropdown) => {\n\t\t\t\tdropdown.addOption(\"gpt-3.5-turbo\", \"GPT-3.5 Turbo\")\n\t\t\t\tdropdown.addOption(\"gpt-3.5-turbo-16k\", \"GPT-3.5 Turbo 16k\")\n\t\t\t\tdropdown.addOption(\"gpt-4\", \"GPT-4\")\n\t\t\t\tdropdown.addOption(\"text-davinci-003\", \"Davinci 003\")\n\t\t\t\tdropdown.setValue(this.plugin.settings.model || \"gpt-3.5-turbo\")\n\t\t\t\tdropdown.onChange((value) => {",
"score": 0.6806285381317139
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\tdropdown.addOption(\"en\", \"English\")\n\t\t\t\tdropdown.addOption(\"fr\", \"Français\")\n\t\t\t\tdropdown.setValue(this.plugin.settings.language || \"en\")\n\t\t\t\tdropdown.onChange((value) => {\n\t\t\t\t\tthis.plugin.settings.language = value as supportedLanguage\n\t\t\t\t\tthis.plugin.saveSettings()\n\t\t\t\t})\n\t\t\t})\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Preferred Mentor\")",
"score": 0.6616383790969849
}
] | typescript | text = mentor[1].name[this.preferredLanguage]
} |
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
async execute(text: string, command: Command): Promise<string[]> {
const params = command.settings
const mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
const requestedMentor = mentorList[command.mentor]
const | prompts = command.pattern.map((prompt) => { |
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command.prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) {
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
| src/ai/model.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 0.8068987131118774
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\tpreferredLanguage = \"en\"\n\tmodel: ModelType\n\tfirstOpen = true\n\t// isTyping = false\n\tdisplayedMessages: Message[] = []\n\t// Merge the two Record<string, Mentor> objects into one.\n\tmentorList: Record<string, Mentor> = {\n\t\t...Topics,\n\t\t...Individuals,\n\t}",
"score": 0.7464295625686646
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tclearButton.innerHTML = CleanIcon\n\t\tclearButton.onclick = () => this.handleClear()\n\t}\n\tasync onClose() {\n\t\t// Nothing to clean up.\n\t}\n\tasync handleMentorChange(id: string) {\n\t\tconst newMentor = this.mentorList[id]\n\t\tthis.mentor.changeIdentity(id, newMentor)\n\t\tthis.displayedMessages = [",
"score": 0.7463217973709106
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tthis.preferredLanguage = preferredLanguage\n\t\tthis.model = model\n\t\t// Mentor selection.\n\t\tconst selectedMentor = this.mentorList[preferredMentorId]\n\t\tthis.mentor = new MentorModel(\n\t\t\tpreferredMentorId,\n\t\t\tselectedMentor,\n\t\t\tthis.model,\n\t\t\ttoken,\n\t\t\tpreferredLanguage",
"score": 0.7186861038208008
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t{\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: newMentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n\tasync handleKeywordsInPrompt(prompt: string): Promise<string> {\n\t\t// Todo: return a prompt that do not contain the note to be inserted in the chat",
"score": 0.7019374966621399
}
] | typescript | prompts = command.pattern.map((prompt) => { |
import { addIcon, Menu, Notice, Plugin } from "obsidian"
import { commands } from "./ai/commands"
import { Individuals } from "./ai/mentors"
import { MentorModel, ModelType } from "./ai/model"
import { MentorIcon } from "./assets/icons/mentor"
import { ChatView, VIEW_TYPE_CHAT } from "./components/chatview"
import { MentorModal } from "./components/modals"
import SettingTab from "./settings"
import { supportedLanguage } from "./types"
interface MentorSettings {
preferredMentorId: string
language: supportedLanguage
token: string
model: ModelType
}
const DEFAULT_SETTINGS: MentorSettings = {
preferredMentorId: "default",
language: "en",
token: "",
model: ModelType.Default,
}
export default class ObsidianMentor extends Plugin {
settings: MentorSettings = DEFAULT_SETTINGS
async onload() {
await this.loadSettings()
this.registerView(
VIEW_TYPE_CHAT,
(leaf) =>
new ChatView(
leaf,
this.settings.token,
this.settings.preferredMentorId,
this.settings.model,
this.settings.language
)
)
// This creates an icon in the left ribbon.
addIcon("aimentor", MentorIcon)
const ribbonIconEl = this.addRibbonIcon(
"aimentor",
"Mentor",
(evt: MouseEvent) => {
// Called when the user clicks the icon.
this.activateView()
}
)
// Perform additional things with the ribbon
ribbonIconEl.addClass("mentor-ribbon")
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({
id: "open-mentor",
name: "Open Mentor",
callback: () => {
this.activateView()
},
})
// AI COMMANDS
const alfred = new MentorModel(
"default",
Individuals["default"],
this.settings.model,
this.settings.token,
this.settings.language
)
// This adds the "ELI5" command.
this.addCommand({
id: "eli5",
name: "ELI5",
editorCallback: async (editor) => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
| .then((response) => { |
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice("Error: Could not get explanation.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add ELI5 to the right-click context menu
// todo: clean to avoid code duplication
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Explain Like I'm 5")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice(
"Error: Could not get explanation."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "redact" command.
this.addCommand({
id: "redact",
name: "Redact",
editorCallback: async (editor) => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice("Error: Could not redact your note.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add redact to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Redact")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice(
"Error: Could not redact your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "enhance" command.
this.addCommand({
id: "enhance",
name: "Enhance",
editorCallback: async (editor) => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] = response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add enhance to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Enhance")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] =
response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
}
async activateView() {
// Pass token from settings to the view
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
await this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_CHAT,
active: true,
})
this.app.workspace.revealLeaf(
this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]
)
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
)
}
async saveSettings() {
await this.saveData(this.settings)
}
async getCompletion() {
console.log("OK")
}
}
| src/main.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tcontent: prompt,\n\t\t})\n\t\t// Add the loading message\n\t\tthis.displayedMessages.push(this.loadingMessage)\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t\tthis.mentor\n\t\t\t.getCompletion(prompt)\n\t\t\t.then(async (response) => {\n\t\t\t\t// Clear the input.",
"score": 0.7967395782470703
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 0.7785388827323914
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\tthis.plugin.saveSettings()\n\t\t\t\t})\n\t\t\t})\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"OpenAI API Key\")\n\t\t\t.setDesc(\"The token generated in your OpenAI dashboard.\")\n\t\t\t.addText((text: TextComponent) => {\n\t\t\t\ttext.setPlaceholder(\"Token\")\n\t\t\t\t\t.setValue(this.plugin.settings.token || \"\")\n\t\t\t\t\t.onChange((change) => {",
"score": 0.7684043645858765
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t.catch(async (error) => {\n\t\t\t\tconsole.log(\"error\", error)\n\t\t\t\t// Clear the input.\n\t\t\t\tthis.currentInput = \"\"\n\t\t\t\t// Display the error message.\n\t\t\t\tthis.displayedMessages.pop()\n\t\t\t\tthis.displayedMessages.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: \"An error occurred. Please try again.\",\n\t\t\t\t})",
"score": 0.7662080526351929
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 0.7661598920822144
}
] | typescript | .then((response) => { |
import { addIcon, Menu, Notice, Plugin } from "obsidian"
import { commands } from "./ai/commands"
import { Individuals } from "./ai/mentors"
import { MentorModel, ModelType } from "./ai/model"
import { MentorIcon } from "./assets/icons/mentor"
import { ChatView, VIEW_TYPE_CHAT } from "./components/chatview"
import { MentorModal } from "./components/modals"
import SettingTab from "./settings"
import { supportedLanguage } from "./types"
interface MentorSettings {
preferredMentorId: string
language: supportedLanguage
token: string
model: ModelType
}
const DEFAULT_SETTINGS: MentorSettings = {
preferredMentorId: "default",
language: "en",
token: "",
model: ModelType.Default,
}
export default class ObsidianMentor extends Plugin {
settings: MentorSettings = DEFAULT_SETTINGS
async onload() {
await this.loadSettings()
this.registerView(
VIEW_TYPE_CHAT,
(leaf) =>
new ChatView(
leaf,
this.settings.token,
this.settings.preferredMentorId,
this.settings.model,
this.settings.language
)
)
// This creates an icon in the left ribbon.
addIcon("aimentor", MentorIcon)
const ribbonIconEl = this.addRibbonIcon(
"aimentor",
"Mentor",
(evt: MouseEvent) => {
// Called when the user clicks the icon.
this.activateView()
}
)
// Perform additional things with the ribbon
ribbonIconEl.addClass("mentor-ribbon")
// This adds a settings tab so the user can configure various aspects of the plugin
| this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({ |
id: "open-mentor",
name: "Open Mentor",
callback: () => {
this.activateView()
},
})
// AI COMMANDS
const alfred = new MentorModel(
"default",
Individuals["default"],
this.settings.model,
this.settings.token,
this.settings.language
)
// This adds the "ELI5" command.
this.addCommand({
id: "eli5",
name: "ELI5",
editorCallback: async (editor) => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice("Error: Could not get explanation.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add ELI5 to the right-click context menu
// todo: clean to avoid code duplication
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Explain Like I'm 5")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice(
"Error: Could not get explanation."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "redact" command.
this.addCommand({
id: "redact",
name: "Redact",
editorCallback: async (editor) => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice("Error: Could not redact your note.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add redact to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Redact")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice(
"Error: Could not redact your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "enhance" command.
this.addCommand({
id: "enhance",
name: "Enhance",
editorCallback: async (editor) => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] = response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add enhance to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Enhance")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] =
response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
}
async activateView() {
// Pass token from settings to the view
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
await this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_CHAT,
active: true,
})
this.app.workspace.revealLeaf(
this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]
)
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
)
}
async saveSettings() {
await this.saveData(this.settings)
}
async getCompletion() {
console.log("OK")
}
}
| src/main.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tactionButton.innerHTML = CopyIcon\n\t\t\tactionButton.onclick = () => {\n\t\t\t\tnavigator.clipboard.writeText(message.content)\n\t\t\t\tnew Notice(\"Copied to clipboard.\")\n\t\t\t}\n\t\t\t// When the user hovers over the message, show the copy button.\n\t\t\tmessageDiv.onmouseenter = () => {\n\t\t\t\tactionButton.removeClass(\"icon-button--hidden\")\n\t\t\t}\n\t\t\tmessageDiv.onmouseleave = () => {",
"score": 0.7314974069595337
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\tthis.plugin.saveSettings()\n\t\t\t\t})\n\t\t\t})\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"OpenAI API Key\")\n\t\t\t.setDesc(\"The token generated in your OpenAI dashboard.\")\n\t\t\t.addText((text: TextComponent) => {\n\t\t\t\ttext.setPlaceholder(\"Token\")\n\t\t\t\t\t.setValue(this.plugin.settings.token || \"\")\n\t\t\t\t\t.onChange((change) => {",
"score": 0.6991045475006104
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t\t// Refresh the view.\n\t\t\t\tawait this.onOpen()\n\t\t\t})\n\t}\n\tasync handleClear() {\n\t\t// Keep only the first message.\n\t\tthis.mentor.reset()\n\t\t// Clear the displayed messages.\n\t\tthis.displayedMessages = [\n\t\t\t{",
"score": 0.6796492338180542
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tif (!evt.shiftKey) {\n\t\t\t\tif (evt.key === \"Enter\") {\n\t\t\t\t\tthis.handleSend()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tinputEl.onkeyup = (evt) => {\n\t\t\t// Resize the input element to fit the text.\n\t\t\tinputEl.style.height = calcHeight(this.currentInput) + \"px\"\n\t\t}",
"score": 0.6659332513809204
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tcontent: prompt,\n\t\t})\n\t\t// Add the loading message\n\t\tthis.displayedMessages.push(this.loadingMessage)\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t\tthis.mentor\n\t\t\t.getCompletion(prompt)\n\t\t\t.then(async (response) => {\n\t\t\t\t// Clear the input.",
"score": 0.6519355177879333
}
] | typescript | this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({ |
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
async execute(text: string, command: Command): Promise<string[]> {
| const params = command.settings
const mentorList: Record<string, Mentor> = { |
...Topics,
...Individuals,
}
const requestedMentor = mentorList[command.mentor]
const prompts = command.pattern.map((prompt) => {
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command.prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) {
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
| src/ai/model.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t{\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: newMentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n\tasync handleKeywordsInPrompt(prompt: string): Promise<string> {\n\t\t// Todo: return a prompt that do not contain the note to be inserted in the chat",
"score": 0.7948638200759888
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\treturn prompt\n\t}\n\tasync handleSend() {\n\t\t// Don't send empty messages.\n\t\tif (this.currentInput === \"\") {\n\t\t\tnew Notice(\"Cannot send empty messages.\")\n\t\t\treturn\n\t\t}\n\t\t// Wait for the mentor to respond.\n\t\tif (",
"score": 0.756009578704834
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 0.7376484274864197
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\tDEFAULT_SETTINGS,\n\t\t\tawait this.loadData()\n\t\t)\n\t}\n\tasync saveSettings() {\n\t\tawait this.saveData(this.settings)\n\t}\n\tasync getCompletion() {\n\t\tconsole.log(\"OK\")\n\t}",
"score": 0.7217857837677002
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t.catch(async (error) => {\n\t\t\t\tconsole.log(\"error\", error)\n\t\t\t\t// Clear the input.\n\t\t\t\tthis.currentInput = \"\"\n\t\t\t\t// Display the error message.\n\t\t\t\tthis.displayedMessages.pop()\n\t\t\t\tthis.displayedMessages.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: \"An error occurred. Please try again.\",\n\t\t\t\t})",
"score": 0.7205246686935425
}
] | typescript | const params = command.settings
const mentorList: Record<string, Mentor> = { |
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
async execute(text: string, command: Command): Promise<string[]> {
const params = command.settings
const mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
const requestedMentor | = mentorList[command.mentor]
const prompts = command.pattern.map((prompt) => { |
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command.prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) {
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
| src/ai/model.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 0.8010344505310059
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tclearButton.innerHTML = CleanIcon\n\t\tclearButton.onclick = () => this.handleClear()\n\t}\n\tasync onClose() {\n\t\t// Nothing to clean up.\n\t}\n\tasync handleMentorChange(id: string) {\n\t\tconst newMentor = this.mentorList[id]\n\t\tthis.mentor.changeIdentity(id, newMentor)\n\t\tthis.displayedMessages = [",
"score": 0.7508941888809204
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\tpreferredLanguage = \"en\"\n\tmodel: ModelType\n\tfirstOpen = true\n\t// isTyping = false\n\tdisplayedMessages: Message[] = []\n\t// Merge the two Record<string, Mentor> objects into one.\n\tmentorList: Record<string, Mentor> = {\n\t\t...Topics,\n\t\t...Individuals,\n\t}",
"score": 0.7364574074745178
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tthis.preferredLanguage = preferredLanguage\n\t\tthis.model = model\n\t\t// Mentor selection.\n\t\tconst selectedMentor = this.mentorList[preferredMentorId]\n\t\tthis.mentor = new MentorModel(\n\t\t\tpreferredMentorId,\n\t\t\tselectedMentor,\n\t\t\tthis.model,\n\t\t\ttoken,\n\t\t\tpreferredLanguage",
"score": 0.7232993245124817
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t.setDesc(\"The mentor you'd like to talk to in priority.\")\n\t\t\t.addDropdown((dropdown) => {\n\t\t\t\tmentorIds.forEach((id) => {\n\t\t\t\t\tdropdown.addOption(id, mentorList[id].name.en)\n\t\t\t\t})\n\t\t\t\tdropdown.setValue(\n\t\t\t\t\tthis.plugin.settings.preferredMentorId || \"default\"\n\t\t\t\t)\n\t\t\t\tdropdown.onChange((value) => {\n\t\t\t\t\tthis.plugin.settings.preferredMentorId = value",
"score": 0.6989264488220215
}
] | typescript | = mentorList[command.mentor]
const prompts = command.pattern.map((prompt) => { |
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
async execute(text: string, command: Command): Promise<string[]> {
const params = command.settings
const mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
const requestedMentor = mentorList[command.mentor]
const prompts = command.pattern.map((prompt) => {
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command | .prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) { |
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
| src/ai/model.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tthis.mentor.history.length !== 0 &&\n\t\t\tthis.mentor.history[this.mentor.history.length - 1].role === \"user\"\n\t\t) {\n\t\t\tnew Notice(\"Please wait for your mentor to respond.\")\n\t\t\treturn\n\t\t}\n\t\tconst prompt = await this.handleKeywordsInPrompt(this.currentInput)\n\t\t// Display the prompt\n\t\tthis.displayedMessages.push({\n\t\t\trole: \"user\",",
"score": 0.7443427443504333
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t{\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: newMentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n\tasync handleKeywordsInPrompt(prompt: string): Promise<string> {\n\t\t// Todo: return a prompt that do not contain the note to be inserted in the chat",
"score": 0.7262969613075256
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t// Display messages in the chat.\n\t\tconst chatDiv = container.createDiv()\n\t\tchatDiv.addClass(\"chat__messages\")\n\t\t// Add history to selectedMentor.firstMessage\n\t\t// const firstMessage: Message = {\n\t\t// \trole: \"assistant\",\n\t\t// \tcontent: selectedMentor.firstMessage[this.preferredLanguage],\n\t\t// }\n\t\t// Add the first message to the chat.\n\t\tconst history =",
"score": 0.7178077697753906
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent:\n\t\t\t\t\tthis.mentor.mentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n}",
"score": 0.7060413956642151
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t\tthis.currentInput = \"\"\n\t\t\t\t// Display the response.\n\t\t\t\tthis.displayedMessages.pop()\n\t\t\t\tthis.displayedMessages.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: response,\n\t\t\t\t})\n\t\t\t\t// Refresh the view.\n\t\t\t\tawait this.onOpen()\n\t\t\t})",
"score": 0.7032139301300049
}
] | typescript | .prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) { |
import { addIcon, Menu, Notice, Plugin } from "obsidian"
import { commands } from "./ai/commands"
import { Individuals } from "./ai/mentors"
import { MentorModel, ModelType } from "./ai/model"
import { MentorIcon } from "./assets/icons/mentor"
import { ChatView, VIEW_TYPE_CHAT } from "./components/chatview"
import { MentorModal } from "./components/modals"
import SettingTab from "./settings"
import { supportedLanguage } from "./types"
interface MentorSettings {
preferredMentorId: string
language: supportedLanguage
token: string
model: ModelType
}
const DEFAULT_SETTINGS: MentorSettings = {
preferredMentorId: "default",
language: "en",
token: "",
model: ModelType.Default,
}
export default class ObsidianMentor extends Plugin {
settings: MentorSettings = DEFAULT_SETTINGS
async onload() {
await this.loadSettings()
this.registerView(
VIEW_TYPE_CHAT,
(leaf) =>
new ChatView(
leaf,
this.settings.token,
this.settings.preferredMentorId,
this.settings.model,
this.settings.language
)
)
// This creates an icon in the left ribbon.
addIcon("aimentor", MentorIcon)
const ribbonIconEl = this.addRibbonIcon(
"aimentor",
"Mentor",
(evt: MouseEvent) => {
// Called when the user clicks the icon.
this.activateView()
}
)
// Perform additional things with the ribbon
ribbonIconEl.addClass("mentor-ribbon")
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({
id: "open-mentor",
name: "Open Mentor",
callback: () => {
this.activateView()
},
})
// AI COMMANDS
const alfred = new MentorModel(
"default",
Individuals["default"],
this.settings.model,
this.settings.token,
this.settings.language
)
// This adds the "ELI5" command.
this.addCommand({
id: "eli5",
name: "ELI5",
editorCallback: async (editor) => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
. | execute(selection, commands.explain)
.then((response) => { |
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice("Error: Could not get explanation.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add ELI5 to the right-click context menu
// todo: clean to avoid code duplication
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Explain Like I'm 5")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice(
"Error: Could not get explanation."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "redact" command.
this.addCommand({
id: "redact",
name: "Redact",
editorCallback: async (editor) => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice("Error: Could not redact your note.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add redact to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Redact")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice(
"Error: Could not redact your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "enhance" command.
this.addCommand({
id: "enhance",
name: "Enhance",
editorCallback: async (editor) => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] = response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add enhance to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Enhance")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] =
response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
}
async activateView() {
// Pass token from settings to the view
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
await this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_CHAT,
active: true,
})
this.app.workspace.revealLeaf(
this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]
)
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
)
}
async saveSettings() {
await this.saveData(this.settings)
}
async getCompletion() {
console.log("OK")
}
}
| src/main.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tcontent: prompt,\n\t\t})\n\t\t// Add the loading message\n\t\tthis.displayedMessages.push(this.loadingMessage)\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t\tthis.mentor\n\t\t\t.getCompletion(prompt)\n\t\t\t.then(async (response) => {\n\t\t\t\t// Clear the input.",
"score": 0.7911726832389832
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 0.7680755853652954
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\tthis.plugin.saveSettings()\n\t\t\t\t})\n\t\t\t})\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"OpenAI API Key\")\n\t\t\t.setDesc(\"The token generated in your OpenAI dashboard.\")\n\t\t\t.addText((text: TextComponent) => {\n\t\t\t\ttext.setPlaceholder(\"Token\")\n\t\t\t\t\t.setValue(this.plugin.settings.token || \"\")\n\t\t\t\t\t.onChange((change) => {",
"score": 0.7559654116630554
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t.catch(async (error) => {\n\t\t\t\tconsole.log(\"error\", error)\n\t\t\t\t// Clear the input.\n\t\t\t\tthis.currentInput = \"\"\n\t\t\t\t// Display the error message.\n\t\t\t\tthis.displayedMessages.pop()\n\t\t\t\tthis.displayedMessages.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: \"An error occurred. Please try again.\",\n\t\t\t\t})",
"score": 0.7513678669929504
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 0.7504755854606628
}
] | typescript | execute(selection, commands.explain)
.then((response) => { |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
.then(async (response) => {
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
| .catch(async (error) => { |
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 0.8443132638931274
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 0.8118137121200562
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t\t\talfred\n\t\t\t\t\t\t\t\t.execute(selection, commands.explain)\n\t\t\t\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\t\t\t\tif (response) {\n\t\t\t\t\t\t\t\t\t\t// Show the explanation\n\t\t\t\t\t\t\t\t\t\tloadingModal.close()\n\t\t\t\t\t\t\t\t\t\tnew MentorModal(\n\t\t\t\t\t\t\t\t\t\t\tthis.app,\n\t\t\t\t\t\t\t\t\t\t\ttitle,\n\t\t\t\t\t\t\t\t\t\t\tresponse[0] // Only one possible response",
"score": 0.7922446131706238
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t// Get the explanation\n\t\t\t\t\talfred\n\t\t\t\t\t\t.execute(selection, commands.explain)\n\t\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\t\tif (response) {\n\t\t\t\t\t\t\t\t// Show the explanation\n\t\t\t\t\t\t\t\tloadingModal.close()\n\t\t\t\t\t\t\t\tnew MentorModal(\n\t\t\t\t\t\t\t\t\tthis.app,\n\t\t\t\t\t\t\t\t\ttitle,",
"score": 0.791258692741394
},
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "\t\t\tnew Notice(\"Copied to clipboard\")\n\t\t})\n\t\ttextEl.addEventListener(\"contextmenu\", () => {\n\t\t\tnavigator.clipboard.writeText(this.displayedText)\n\t\t\tnew Notice(\"Copied to clipboard\")\n\t\t})\n\t}\n\tonClose() {\n\t\tconst { contentEl } = this\n\t\tcontentEl.empty()",
"score": 0.7473949790000916
}
] | typescript | .catch(async (error) => { |
import { addIcon, Menu, Notice, Plugin } from "obsidian"
import { commands } from "./ai/commands"
import { Individuals } from "./ai/mentors"
import { MentorModel, ModelType } from "./ai/model"
import { MentorIcon } from "./assets/icons/mentor"
import { ChatView, VIEW_TYPE_CHAT } from "./components/chatview"
import { MentorModal } from "./components/modals"
import SettingTab from "./settings"
import { supportedLanguage } from "./types"
interface MentorSettings {
preferredMentorId: string
language: supportedLanguage
token: string
model: ModelType
}
const DEFAULT_SETTINGS: MentorSettings = {
preferredMentorId: "default",
language: "en",
token: "",
model: ModelType.Default,
}
export default class ObsidianMentor extends Plugin {
settings: MentorSettings = DEFAULT_SETTINGS
async onload() {
await this.loadSettings()
this.registerView(
VIEW_TYPE_CHAT,
(leaf) =>
new ChatView(
leaf,
this.settings.token,
this.settings.preferredMentorId,
this.settings.model,
this.settings.language
)
)
// This creates an icon in the left ribbon.
addIcon("aimentor", MentorIcon)
const ribbonIconEl = this.addRibbonIcon(
"aimentor",
"Mentor",
(evt: MouseEvent) => {
// Called when the user clicks the icon.
this.activateView()
}
)
// Perform additional things with the ribbon
ribbonIconEl.addClass("mentor-ribbon")
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({
id: "open-mentor",
name: "Open Mentor",
callback: () => {
this.activateView()
},
})
// AI COMMANDS
const alfred = new MentorModel(
"default",
Individuals["default"],
this.settings.model,
this.settings.token,
this.settings.language
)
// This adds the "ELI5" command.
this.addCommand({
id: "eli5",
name: "ELI5",
editorCallback: async (editor) => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice("Error: Could not get explanation.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add ELI5 to the right-click context menu
// todo: clean to avoid code duplication
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Explain Like I'm 5")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice(
"Error: Could not get explanation."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "redact" command.
this.addCommand({
id: "redact",
name: "Redact",
editorCallback: async (editor) => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice("Error: Could not redact your note.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add redact to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Redact")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice(
"Error: Could not redact your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "enhance" command.
this.addCommand({
id: "enhance",
name: "Enhance",
editorCallback: async (editor) => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
| .execute(selection, commands.enhance)
.then((response) => { |
if (response) {
const [enhancedText, explanations] = response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add enhance to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Enhance")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] =
response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
}
async activateView() {
// Pass token from settings to the view
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
await this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_CHAT,
active: true,
})
this.app.workspace.revealLeaf(
this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]
)
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
)
}
async saveSettings() {
await this.saveData(this.settings)
}
async getCompletion() {
console.log("OK")
}
}
| src/main.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tcontent: prompt,\n\t\t})\n\t\t// Add the loading message\n\t\tthis.displayedMessages.push(this.loadingMessage)\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t\tthis.mentor\n\t\t\t.getCompletion(prompt)\n\t\t\t.then(async (response) => {\n\t\t\t\t// Clear the input.",
"score": 0.7794649600982666
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\tthis.plugin.saveSettings()\n\t\t\t\t})\n\t\t\t})\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"OpenAI API Key\")\n\t\t\t.setDesc(\"The token generated in your OpenAI dashboard.\")\n\t\t\t.addText((text: TextComponent) => {\n\t\t\t\ttext.setPlaceholder(\"Token\")\n\t\t\t\t\t.setValue(this.plugin.settings.token || \"\")\n\t\t\t\t\t.onChange((change) => {",
"score": 0.748957633972168
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 0.7477973699569702
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 0.7461313605308533
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t.catch(async (error) => {\n\t\t\t\tconsole.log(\"error\", error)\n\t\t\t\t// Clear the input.\n\t\t\t\tthis.currentInput = \"\"\n\t\t\t\t// Display the error message.\n\t\t\t\tthis.displayedMessages.pop()\n\t\t\t\tthis.displayedMessages.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: \"An error occurred. Please try again.\",\n\t\t\t\t})",
"score": 0.7445348501205444
}
] | typescript | .execute(selection, commands.enhance)
.then((response) => { |
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Req,
} from '@nestjs/common';
import { Request } from 'express';
import { PostDocument } from 'src/common/schemas';
import { CreatePostDto } from 'src/common/dto';
import { PostService } from './post.service';
@Controller('post')
export class PostController {
constructor(private readonly postService: PostService) {}
@Get('/id/:id')
getPost(@Param('id') id: string): Promise<PostDocument> {
return this.postService.getPostById(id);
}
@Get('/my')
getMyPost(@Req() request: Request): Promise<PostDocument[]> {
return this.postService.getMyPost(request.user);
}
@Post()
createPost(
@Req() request: Request,
@Body() data: CreatePostDto,
): Promise<PostDocument> {
return this.postService.createPost(data, request.user);
}
@Delete('/:id')
removePost(
@Req() request: Request,
@Param('id') id: string,
): Promise<boolean> {
return this.postService.removePost(id, request.user);
}
@Patch('/:id')
modifyPost(
@Req() request: Request,
@Param('id') id: string,
@Body() data: CreatePostDto,
): Promise<PostDocument> {
| return this.postService.modifyPost(data, id, request.user); |
}
}
| src/api/post/post.controller.ts | whguswo-trust-back-v1-b47407d | [
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": " if (post.user.equals(user._id) && user.role !== 'ADMIN')\n throw new HttpException('Permission denied', 403);\n const result = await this.postModel.deleteOne({ _id });\n return result.deletedCount > 0;\n }\n async modifyPost(\n data: CreatePostDto,\n _id: string,\n user: UserDocument,\n ): Promise<PostDocument> {",
"score": 0.7896403074264526
},
{
"filename": "src/api/user/user.controller.ts",
"retrieved_chunk": "@Controller('user')\nexport class UserController {\n constructor(private readonly userService: UserService) {}\n @Get()\n async getAllUser(): Promise<UserDocument[]> {\n return await this.userService.getAllUser();\n }\n @Post()\n async createUser(@Body() data: CreateUserDto): Promise<ResponseDto> {\n return await this.userService.createUser(data);",
"score": 0.7885174751281738
},
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": " }\n async getMyPost(user: UserDocument): Promise<PostDocument[]> {\n const posts = await this.postModel.find({ user: user._id });\n return posts;\n }\n async getPostByUserId(_id: string): Promise<PostDocument[]> {\n const posts = await this.postModel.find({ user: new Types.ObjectId(_id) });\n return posts;\n }\n async createPost(data: CreatePostDto, user: UserDocument): Promise<PostDocument> {",
"score": 0.7730741500854492
},
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": "@Injectable()\nexport class PostService {\n constructor(\n @InjectModel(Post.name)\n private postModel: Model<PostDocument>,\n ) {}\n async getPostById(_id: string): Promise<PostDocument> {\n const post = await this.postModel.findById(new Types.ObjectId(_id));\n if (!post) throw new HttpException('No Post', 404);\n return post;",
"score": 0.7705639600753784
},
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": " const post = new this.postModel({\n ...data,\n user: new Types.ObjectId(user._id),\n });\n await post.save();\n return post;\n }\n async removePost(_id: string, user: UserDocument): Promise<boolean> {\n const post = await this.postModel.findById(new Types.ObjectId(_id));\n if (!post) throw new HttpException('해당 Post가 존재하지 않습니다.', 404);",
"score": 0.7093498706817627
}
] | typescript | return this.postService.modifyPost(data, id, request.user); |
import { addIcon, Menu, Notice, Plugin } from "obsidian"
import { commands } from "./ai/commands"
import { Individuals } from "./ai/mentors"
import { MentorModel, ModelType } from "./ai/model"
import { MentorIcon } from "./assets/icons/mentor"
import { ChatView, VIEW_TYPE_CHAT } from "./components/chatview"
import { MentorModal } from "./components/modals"
import SettingTab from "./settings"
import { supportedLanguage } from "./types"
interface MentorSettings {
preferredMentorId: string
language: supportedLanguage
token: string
model: ModelType
}
const DEFAULT_SETTINGS: MentorSettings = {
preferredMentorId: "default",
language: "en",
token: "",
model: ModelType.Default,
}
export default class ObsidianMentor extends Plugin {
settings: MentorSettings = DEFAULT_SETTINGS
async onload() {
await this.loadSettings()
this.registerView(
VIEW_TYPE_CHAT,
(leaf) =>
new ChatView(
leaf,
this.settings.token,
this.settings.preferredMentorId,
this.settings.model,
this.settings.language
)
)
// This creates an icon in the left ribbon.
addIcon("aimentor", MentorIcon)
const ribbonIconEl = this.addRibbonIcon(
"aimentor",
"Mentor",
(evt: MouseEvent) => {
// Called when the user clicks the icon.
this.activateView()
}
)
// Perform additional things with the ribbon
ribbonIconEl.addClass("mentor-ribbon")
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({
id: "open-mentor",
name: "Open Mentor",
callback: () => {
this.activateView()
},
})
// AI COMMANDS
const alfred = new MentorModel(
"default",
Individuals["default"],
this.settings.model,
this.settings.token,
this.settings.language
)
// This adds the "ELI5" command.
this.addCommand({
id: "eli5",
name: "ELI5",
editorCallback: async (editor) => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands | .explain)
.then((response) => { |
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice("Error: Could not get explanation.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add ELI5 to the right-click context menu
// todo: clean to avoid code duplication
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Explain Like I'm 5")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice(
"Error: Could not get explanation."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "redact" command.
this.addCommand({
id: "redact",
name: "Redact",
editorCallback: async (editor) => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice("Error: Could not redact your note.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add redact to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Redact")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice(
"Error: Could not redact your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "enhance" command.
this.addCommand({
id: "enhance",
name: "Enhance",
editorCallback: async (editor) => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] = response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add enhance to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Enhance")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] =
response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
}
async activateView() {
// Pass token from settings to the view
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
await this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_CHAT,
active: true,
})
this.app.workspace.revealLeaf(
this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]
)
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
)
}
async saveSettings() {
await this.saveData(this.settings)
}
async getCompletion() {
console.log("OK")
}
}
| src/main.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tcontent: prompt,\n\t\t})\n\t\t// Add the loading message\n\t\tthis.displayedMessages.push(this.loadingMessage)\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t\tthis.mentor\n\t\t\t.getCompletion(prompt)\n\t\t\t.then(async (response) => {\n\t\t\t\t// Clear the input.",
"score": 0.791167676448822
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 0.7700492739677429
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t.catch(async (error) => {\n\t\t\t\tconsole.log(\"error\", error)\n\t\t\t\t// Clear the input.\n\t\t\t\tthis.currentInput = \"\"\n\t\t\t\t// Display the error message.\n\t\t\t\tthis.displayedMessages.pop()\n\t\t\t\tthis.displayedMessages.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: \"An error occurred. Please try again.\",\n\t\t\t\t})",
"score": 0.7517982721328735
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 0.7505292892456055
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\tthis.plugin.saveSettings()\n\t\t\t\t})\n\t\t\t})\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"OpenAI API Key\")\n\t\t\t.setDesc(\"The token generated in your OpenAI dashboard.\")\n\t\t\t.addText((text: TextComponent) => {\n\t\t\t\ttext.setPlaceholder(\"Token\")\n\t\t\t\t\t.setValue(this.plugin.settings.token || \"\")\n\t\t\t\t\t.onChange((change) => {",
"score": 0.7504598498344421
}
] | typescript | .explain)
.then((response) => { |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor | .changeIdentity(id, newMentor)
this.displayedMessages = [
{ |
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
.then(async (response) => {
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t// Reset history\n\t\tthis.reset()\n\t\treturn answers\n\t}\n\tchangeIdentity(id: string, newMentor: Mentor) {\n\t\tthis.id = id\n\t\tthis.mentor = newMentor\n\t\tthis.history = [\n\t\t\t{\n\t\t\t\trole: \"system\",",
"score": 0.8457950353622437
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t.setDesc(\"The mentor you'd like to talk to in priority.\")\n\t\t\t.addDropdown((dropdown) => {\n\t\t\t\tmentorIds.forEach((id) => {\n\t\t\t\t\tdropdown.addOption(id, mentorList[id].name.en)\n\t\t\t\t})\n\t\t\t\tdropdown.setValue(\n\t\t\t\t\tthis.plugin.settings.preferredMentorId || \"default\"\n\t\t\t\t)\n\t\t\t\tdropdown.onChange((value) => {\n\t\t\t\t\tthis.plugin.settings.preferredMentorId = value",
"score": 0.7456870079040527
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t})\n\t\treturn answer\n\t}\n\tasync execute(text: string, command: Command): Promise<string[]> {\n\t\tconst params = command.settings\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}",
"score": 0.7292571663856506
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\tcontent: newMentor.systemPrompt[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t}\n\treset() {\n\t\tthis.history = [\n\t\t\t{\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: this.mentor.systemPrompt[this.preferredLanguage],\n\t\t\t},",
"score": 0.7289905548095703
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 0.7207042574882507
}
] | typescript | .changeIdentity(id, newMentor)
this.displayedMessages = [
{ |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
. | getCompletion(prompt)
.then(async (response) => { |
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t// Get the explanation\n\t\t\t\t\talfred\n\t\t\t\t\t\t.execute(selection, commands.explain)\n\t\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\t\tif (response) {\n\t\t\t\t\t\t\t\t// Show the explanation\n\t\t\t\t\t\t\t\tloadingModal.close()\n\t\t\t\t\t\t\t\tnew MentorModal(\n\t\t\t\t\t\t\t\t\tthis.app,\n\t\t\t\t\t\t\t\t\ttitle,",
"score": 0.7993015050888062
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\tDEFAULT_SETTINGS,\n\t\t\tawait this.loadData()\n\t\t)\n\t}\n\tasync saveSettings() {\n\t\tawait this.saveData(this.settings)\n\t}\n\tasync getCompletion() {\n\t\tconsole.log(\"OK\")\n\t}",
"score": 0.7921935319900513
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t\t\talfred\n\t\t\t\t\t\t\t\t.execute(selection, commands.explain)\n\t\t\t\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\t\t\t\tif (response) {\n\t\t\t\t\t\t\t\t\t\t// Show the explanation\n\t\t\t\t\t\t\t\t\t\tloadingModal.close()\n\t\t\t\t\t\t\t\t\t\tnew MentorModal(\n\t\t\t\t\t\t\t\t\t\t\tthis.app,\n\t\t\t\t\t\t\t\t\t\t\ttitle,\n\t\t\t\t\t\t\t\t\t\t\tresponse[0] // Only one possible response",
"score": 0.7799844145774841
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 0.7634994387626648
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\tthis.plugin.saveSettings()\n\t\t\t\t})\n\t\t\t})\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"OpenAI API Key\")\n\t\t\t.setDesc(\"The token generated in your OpenAI dashboard.\")\n\t\t\t.addText((text: TextComponent) => {\n\t\t\t\ttext.setPlaceholder(\"Token\")\n\t\t\t\t\t.setValue(this.plugin.settings.token || \"\")\n\t\t\t\t\t.onChange((change) => {",
"score": 0.7481503486633301
}
] | typescript | getCompletion(prompt)
.then(async (response) => { |
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Req,
} from '@nestjs/common';
import { Request } from 'express';
import { PostDocument } from 'src/common/schemas';
import { CreatePostDto } from 'src/common/dto';
import { PostService } from './post.service';
@Controller('post')
export class PostController {
constructor(private readonly postService: PostService) {}
@Get('/id/:id')
getPost(@Param('id') id: string): Promise<PostDocument> {
return this.postService.getPostById(id);
}
@Get('/my')
getMyPost(@Req() request: Request): Promise<PostDocument[]> {
return this.postService.getMyPost(request.user);
}
@Post()
createPost(
@Req() request: Request,
@Body() data: CreatePostDto,
): Promise<PostDocument> {
return this.postService.createPost(data, request.user);
}
@Delete('/:id')
removePost(
@Req() request: Request,
@Param('id') id: string,
): Promise<boolean> {
| return this.postService.removePost(id, request.user); |
}
@Patch('/:id')
modifyPost(
@Req() request: Request,
@Param('id') id: string,
@Body() data: CreatePostDto,
): Promise<PostDocument> {
return this.postService.modifyPost(data, id, request.user);
}
}
| src/api/post/post.controller.ts | whguswo-trust-back-v1-b47407d | [
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": " if (post.user.equals(user._id) && user.role !== 'ADMIN')\n throw new HttpException('Permission denied', 403);\n const result = await this.postModel.deleteOne({ _id });\n return result.deletedCount > 0;\n }\n async modifyPost(\n data: CreatePostDto,\n _id: string,\n user: UserDocument,\n ): Promise<PostDocument> {",
"score": 0.8266177177429199
},
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": " }\n async getMyPost(user: UserDocument): Promise<PostDocument[]> {\n const posts = await this.postModel.find({ user: user._id });\n return posts;\n }\n async getPostByUserId(_id: string): Promise<PostDocument[]> {\n const posts = await this.postModel.find({ user: new Types.ObjectId(_id) });\n return posts;\n }\n async createPost(data: CreatePostDto, user: UserDocument): Promise<PostDocument> {",
"score": 0.823455810546875
},
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": "@Injectable()\nexport class PostService {\n constructor(\n @InjectModel(Post.name)\n private postModel: Model<PostDocument>,\n ) {}\n async getPostById(_id: string): Promise<PostDocument> {\n const post = await this.postModel.findById(new Types.ObjectId(_id));\n if (!post) throw new HttpException('No Post', 404);\n return post;",
"score": 0.8043975830078125
},
{
"filename": "src/api/user/user.controller.ts",
"retrieved_chunk": "@Controller('user')\nexport class UserController {\n constructor(private readonly userService: UserService) {}\n @Get()\n async getAllUser(): Promise<UserDocument[]> {\n return await this.userService.getAllUser();\n }\n @Post()\n async createUser(@Body() data: CreateUserDto): Promise<ResponseDto> {\n return await this.userService.createUser(data);",
"score": 0.800125002861023
},
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": " const post = new this.postModel({\n ...data,\n user: new Types.ObjectId(user._id),\n });\n await post.save();\n return post;\n }\n async removePost(_id: string, user: UserDocument): Promise<boolean> {\n const post = await this.postModel.findById(new Types.ObjectId(_id));\n if (!post) throw new HttpException('해당 Post가 존재하지 않습니다.', 404);",
"score": 0.7654664516448975
}
] | typescript | return this.postService.removePost(id, request.user); |
import fs from 'node:fs';
import { join } from 'path';
import InternalDb from './db/InternalDb';
import { getActiveProjectId } from './db/localStorageUtils';
import { exportProject } from './exportData';
import { importProject, readProjectData } from './importData';
import renderModal from './ui/react/renderModal';
import confirmModal from './ui/react/confirmModal';
let prevExport = '';
export default async function autoExport() {
const projectId = getActiveProjectId();
if (!projectId) {
return;
}
const config = InternalDb.create();
const { repositoryPath: path, autoExport } = config.getProject(projectId);
if (!path || !autoExport || projectId === 'proj_default-project') {
return;
}
const [projectData, workspaces] = await exportProject(projectId);
const newExportJson = JSON.stringify([projectData, workspaces]);
if (newExportJson === prevExport) {
// Nothing to export, so lets try to Import
await autoImportProject(path);
return;
}
prevExport = newExportJson;
const targetFile = join(path, 'project.json');
fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));
for (const workspace of workspaces) {
const targetFile = join(path, workspace.id + '.json');
fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));
}
}
let prevImport = '';
async function autoImportProject(path: string) {
let project, workspaceData;
try {
[project, workspaceData] = readProjectData(path);
} catch (e) {
console.error('[IPGI] Error while gathering import data during auto import. This might not be a bug', e);
return;
}
const newImportJson = JSON.stringify([project, workspaceData]);
// Do not import the first time
if (prevImport === '') {
prevImport = newImportJson;
return;
}
if (prevImport === newImportJson) {
// Nothing to import
return;
}
const doImport = await | renderModal<boolean>(confirmModal(
'Import project',
'Import chhanged project data? Insomnia will restart.',
)); |
if (!doImport) {
return;
}
await importProject(project, workspaceData);
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
}
| src/autoExport.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/configureGitRepoButton.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannnot configure Folder',\n 'Cannot configure folder for default repository. Please create a now Project',\n ));\n return;\n }\n await renderModal(configureProject(projectId));\n });\n // Hover effect\n configureProjectButton.addEventListener('mouseover', () => {",
"score": 0.8735417723655701
},
{
"filename": "src/index.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannot import workspace',\n 'You must first configure the project folder before importing',\n ));\n return;\n }\n const targetFile = join(path, workspaceId + '.json');\n const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());\n await importWorkspaceData(dataRaw);\n // Force Insomnia to read all data",
"score": 0.858338475227356
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 0.8434929251670837
},
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [project, workspaceData] = readProjectData(path);\n await importProject(project, workspaceData);\n // Force Insomnia to read all data again.\n // Wrapped with requestIdleCallback to make sure NeDB had enough time to save everything\n // @ts-ignore\n window.requestIdleCallback(window.main.restart);",
"score": 0.8293454647064209
},
{
"filename": "src/index.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannot export workspace',\n 'You must first configure the project folder before exporting',\n ));\n return;\n }\n const data = await exportWorkspaceData(workspaceId);\n const targetFile = join(path, workspaceId + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));\n },",
"score": 0.8231657147407532
}
] | typescript | renderModal<boolean>(confirmModal(
'Import project',
'Import chhanged project data? Insomnia will restart.',
)); |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
| ): Promise<GitSavedRequest[]> { |
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " requests: GitSavedRequest[],\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n) {\n for (const request of requests) {\n if (request.type === 'group') {\n await requestGroupDb.upsert(request.group);",
"score": 0.8799020051956177
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "async function removeOldData(\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n environmentDb: BaseDb<Environment>,\n testSuitesDb: BaseDb<UnittestSuite>,\n testDb: BaseDb<UnitTest>,\n) {",
"score": 0.855069637298584
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " sidebarHidden: false,\n sidebarWidth: 19,\n pushSnapshotOnInitialize: false,\n };\n await workspaceMetaDb.upsert(fullMeta);\n const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);",
"score": 0.8305217623710632
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 0.8125197887420654
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 0.7966398596763611
}
] | typescript | ): Promise<GitSavedRequest[]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string) | : Promise<ApiSpec | null> { |
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " }\n for (const testSuites of oldIds.getTestSuites()) {\n await testSuitesDb.deleteBy('_id', testSuites);\n }\n for (const test of oldIds.getTests()) {\n await testDb.deleteBy('_id', test);\n }\n}\nexport async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {\n const workspaceDb = new BaseDb<Workspace>('Workspace');",
"score": 0.844049870967865
},
{
"filename": "src/types.ts",
"retrieved_chunk": " workspace: Workspace,\n meta: GitSavedWorkspaceMeta,\n requests: GitSavedRequest[],\n environments: Environment[],\n apiSpec?: ApiSpec,\n unitTestSuites: GitSavedUnitTestSuite[],\n}\nexport type GitSavedUnitTestSuite = {\n testSuite: UnittestSuite,\n tests: UnitTest[],",
"score": 0.7891049385070801
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 0.7706934213638306
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 0.7581961154937744
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " tests.push(test._id);\n }\n return testSuite.testSuite._id;\n });\n return new OldIds(environmentIds, requestIds, requestGroupIds, testSuites, tests);\n }\n private static getIdsRecursive(requests: GitSavedRequest[], requestIds: string[], requestGroupIds: string[]) {\n for (const request of requests) {\n if (request.type === 'group') {\n requestGroupIds.push(request.id);",
"score": 0.7569283246994019
}
] | typescript | : Promise<ApiSpec | null> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
| const meta: GitSavedWorkspaceMeta = { |
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 0.9042423963546753
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " // Collect OldIds of Requests / Folders so we can delete deleted Docs at the end\n const oldIds = await workspaceDb.findById(data.id)\n ? OldIds.fromOldData(await exportWorkspaceData(data.id))\n : OldIds.createEmpty();\n // Update Workspace metadata\n await workspaceDb.upsert(data.workspace);\n const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');\n const fullMeta: WorkspaceMeta = {\n ...data.meta,\n // These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here",
"score": 0.8780156373977661
},
{
"filename": "src/ui/importNewProjectButton.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n const configDb = InternalDb.create();\n const projectConfig = configDb.getProject(project.id);\n projectConfig.repositoryPath = openResult.filePaths[0];\n configDb.upsertProject(projectConfig);\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(targetDir, workspaceId + '.json');",
"score": 0.8366445302963257
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 0.8230819702148438
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(path, workspaceId + '.json');\n // TODO: Validate this using Zod\n const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());\n workspaceData.push(workspace);\n }",
"score": 0.8152279257774353
}
] | typescript | const meta: GitSavedWorkspaceMeta = { |
import fs from 'node:fs';
import { join } from 'path';
import InternalDb from './db/InternalDb';
import { getActiveProjectId } from './db/localStorageUtils';
import { exportProject } from './exportData';
import { importProject, readProjectData } from './importData';
import renderModal from './ui/react/renderModal';
import confirmModal from './ui/react/confirmModal';
let prevExport = '';
export default async function autoExport() {
const projectId = getActiveProjectId();
if (!projectId) {
return;
}
const config = InternalDb.create();
const { repositoryPath: path, autoExport } = config.getProject(projectId);
if (!path || !autoExport || projectId === 'proj_default-project') {
return;
}
const [projectData, workspaces] = await exportProject(projectId);
const newExportJson = JSON.stringify([projectData, workspaces]);
if (newExportJson === prevExport) {
// Nothing to export, so lets try to Import
await autoImportProject(path);
return;
}
prevExport = newExportJson;
const targetFile = join(path, 'project.json');
fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));
for (const workspace of workspaces) {
const targetFile = join(path, workspace.id + '.json');
fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));
}
}
let prevImport = '';
async function autoImportProject(path: string) {
let project, workspaceData;
try {
[project, workspaceData] = readProjectData(path);
} catch (e) {
console.error('[IPGI] Error while gathering import data during auto import. This might not be a bug', e);
return;
}
const newImportJson = JSON.stringify([project, workspaceData]);
// Do not import the first time
if (prevImport === '') {
prevImport = newImportJson;
return;
}
if (prevImport === newImportJson) {
// Nothing to import
return;
}
| const doImport = await renderModal<boolean>(confirmModal(
'Import project',
'Import chhanged project data? Insomnia will restart.',
)); |
if (!doImport) {
return;
}
await importProject(project, workspaceData);
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
}
| src/autoExport.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/configureGitRepoButton.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannnot configure Folder',\n 'Cannot configure folder for default repository. Please create a now Project',\n ));\n return;\n }\n await renderModal(configureProject(projectId));\n });\n // Hover effect\n configureProjectButton.addEventListener('mouseover', () => {",
"score": 0.8720090985298157
},
{
"filename": "src/index.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannot import workspace',\n 'You must first configure the project folder before importing',\n ));\n return;\n }\n const targetFile = join(path, workspaceId + '.json');\n const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());\n await importWorkspaceData(dataRaw);\n // Force Insomnia to read all data",
"score": 0.8594103455543518
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 0.843746542930603
},
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [project, workspaceData] = readProjectData(path);\n await importProject(project, workspaceData);\n // Force Insomnia to read all data again.\n // Wrapped with requestIdleCallback to make sure NeDB had enough time to save everything\n // @ts-ignore\n window.requestIdleCallback(window.main.restart);",
"score": 0.8270373940467834
},
{
"filename": "src/index.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannot export workspace',\n 'You must first configure the project folder before exporting',\n ));\n return;\n }\n const data = await exportWorkspaceData(workspaceId);\n const targetFile = join(path, workspaceId + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));\n },",
"score": 0.8230147361755371
}
] | typescript | const doImport = await renderModal<boolean>(confirmModal(
'Import project',
'Import chhanged project data? Insomnia will restart.',
)); |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise< | [GitSavedProject, GitSavedWorkspace[]]> { |
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 0.81136155128479
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 0.8047907948493958
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " remoteId?: string, // Only remote projects have a remote id\n} & BaseModel;\n// Workspace\nexport type Workspace = {\n name: string;\n description: string;\n certificates?: any; // deprecate\n scope: 'design' | 'collection',\n} & BaseModel;\n// WorkspaceMeta",
"score": 0.7914388179779053
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 0.7857872843742371
},
{
"filename": "src/db/InternalDb.ts",
"retrieved_chunk": " return {\n id: projectId,\n remote: null,\n repositoryPath: null,\n autoExport: false,\n };\n }\n return this.config.projects[index];\n }\n public upsertProject(project: ProjectConfig) {",
"score": 0.779553234577179
}
] | typescript | [GitSavedProject, GitSavedWorkspace[]]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
| async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> { |
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " tests.push(test._id);\n }\n return testSuite.testSuite._id;\n });\n return new OldIds(environmentIds, requestIds, requestGroupIds, testSuites, tests);\n }\n private static getIdsRecursive(requests: GitSavedRequest[], requestIds: string[], requestGroupIds: string[]) {\n for (const request of requests) {\n if (request.type === 'group') {\n requestGroupIds.push(request.id);",
"score": 0.8533445596694946
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " requests: GitSavedRequest[],\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n) {\n for (const request of requests) {\n if (request.type === 'group') {\n await requestGroupDb.upsert(request.group);",
"score": 0.819042444229126
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 0.8036472201347351
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 0.7953646183013916
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " }\n for (const testSuites of oldIds.getTestSuites()) {\n await testSuitesDb.deleteBy('_id', testSuites);\n }\n for (const test of oldIds.getTests()) {\n await testDb.deleteBy('_id', test);\n }\n}\nexport async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {\n const workspaceDb = new BaseDb<Workspace>('Workspace');",
"score": 0.7924275398254395
}
] | typescript | async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject | , GitSavedWorkspace[]]> { |
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 0.8088430166244507
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 0.8066601753234863
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " remoteId?: string, // Only remote projects have a remote id\n} & BaseModel;\n// Workspace\nexport type Workspace = {\n name: string;\n description: string;\n certificates?: any; // deprecate\n scope: 'design' | 'collection',\n} & BaseModel;\n// WorkspaceMeta",
"score": 0.789098858833313
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 0.7837236523628235
},
{
"filename": "src/db/InternalDb.ts",
"retrieved_chunk": " return {\n id: projectId,\n remote: null,\n repositoryPath: null,\n autoExport: false,\n };\n }\n return this.config.projects[index];\n }\n public upsertProject(project: ProjectConfig) {",
"score": 0.7817526459693909
}
] | typescript | , GitSavedWorkspace[]]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId | : string): Promise<[GitSavedProject, GitSavedWorkspace[]]> { |
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 0.8093125820159912
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 0.8065674304962158
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " remoteId?: string, // Only remote projects have a remote id\n} & BaseModel;\n// Workspace\nexport type Workspace = {\n name: string;\n description: string;\n certificates?: any; // deprecate\n scope: 'design' | 'collection',\n} & BaseModel;\n// WorkspaceMeta",
"score": 0.7904390096664429
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 0.7851451635360718
},
{
"filename": "src/db/InternalDb.ts",
"retrieved_chunk": " return {\n id: projectId,\n remote: null,\n repositoryPath: null,\n autoExport: false,\n };\n }\n return this.config.projects[index];\n }\n public upsertProject(project: ProjectConfig) {",
"score": 0.7821826934814453
}
] | typescript | : string): Promise<[GitSavedProject, GitSavedWorkspace[]]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
| requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> { |
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " requests: GitSavedRequest[],\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n) {\n for (const request of requests) {\n if (request.type === 'group') {\n await requestGroupDb.upsert(request.group);",
"score": 0.8799020051956177
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "async function removeOldData(\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n environmentDb: BaseDb<Environment>,\n testSuitesDb: BaseDb<UnittestSuite>,\n testDb: BaseDb<UnitTest>,\n) {",
"score": 0.855069637298584
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " sidebarHidden: false,\n sidebarWidth: 19,\n pushSnapshotOnInitialize: false,\n };\n await workspaceMetaDb.upsert(fullMeta);\n const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);",
"score": 0.8305217623710632
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 0.8125197887420654
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 0.7966398596763611
}
] | typescript | requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
| requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.9371401071548462
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8237112760543823
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.8184288740158081
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.8123272657394409
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 0.7550005912780762
}
] | typescript | requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
| export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> { |
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 0.8393586874008179
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " remoteId?: string, // Only remote projects have a remote id\n} & BaseModel;\n// Workspace\nexport type Workspace = {\n name: string;\n description: string;\n certificates?: any; // deprecate\n scope: 'design' | 'collection',\n} & BaseModel;\n// WorkspaceMeta",
"score": 0.8181683421134949
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " // - Workspace optionally has a parentId (which will be the id of a Project)\n parentId: string; // or null\n modified: number;\n created: number;\n isPrivate: boolean;\n name: string;\n}\n// Environment\nexport type Environment = {\n name: string;",
"score": 0.8014292120933533
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 0.7980043292045593
},
{
"filename": "src/db/InternalDb.ts",
"retrieved_chunk": " return {\n id: projectId,\n remote: null,\n repositoryPath: null,\n autoExport: false,\n };\n }\n return this.config.projects[index];\n }\n public upsertProject(project: ProjectConfig) {",
"score": 0.7965499758720398
}
] | typescript | export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb | : BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.9228496551513672
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.8145037889480591
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.8037133812904358
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.802520751953125
},
{
"filename": "src/types.ts",
"retrieved_chunk": " workspace: Workspace,\n meta: GitSavedWorkspaceMeta,\n requests: GitSavedRequest[],\n environments: Environment[],\n apiSpec?: ApiSpec,\n unitTestSuites: GitSavedUnitTestSuite[],\n}\nexport type GitSavedUnitTestSuite = {\n testSuite: UnittestSuite,\n tests: UnitTest[],",
"score": 0.7580474615097046
}
] | typescript | : BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
| environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.8486347198486328
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8322790861129761
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.7979647517204285
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.792372465133667
},
{
"filename": "src/db/BaseDb.ts",
"retrieved_chunk": "import Nedb from 'nedb';\nimport fsPath from 'node:path';\nimport { BaseModel } from '../insomniaDbTypes';\ntype DbTargets = 'Request' | 'RequestMeta' | 'RequestGroup' | 'RequestGroupMeta' | 'Workspace' | 'WorkspaceMeta' | 'Project' | 'Environment' | 'ApiSpec' | 'UnitTest' | 'UnitTestSuite';\nexport default class BaseDb<T extends BaseModel> {\n private neDb: Nedb;\n constructor(target: DbTargets) {\n // @ts-ignore\n const filename = fsPath.join(window.app.getPath('userData'), `insomnia.${target}.db`);\n this.neDb = new Nedb({",
"score": 0.7621265053749084
}
] | typescript | environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
| requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.9371401071548462
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8237112760543823
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.8184288740158081
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.8123272657394409
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 0.7550005912780762
}
] | typescript | requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: | BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.9257169365882874
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.8156689405441284
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.8130068182945251
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8090696334838867
},
{
"filename": "src/types.ts",
"retrieved_chunk": " workspace: Workspace,\n meta: GitSavedWorkspaceMeta,\n requests: GitSavedRequest[],\n environments: Environment[],\n apiSpec?: ApiSpec,\n unitTestSuites: GitSavedUnitTestSuite[],\n}\nexport type GitSavedUnitTestSuite = {\n testSuite: UnittestSuite,\n tests: UnitTest[],",
"score": 0.7665128707885742
}
] | typescript | BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
| testDb: BaseDb<UnitTest>,
) { |
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.8486347198486328
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8322790861129761
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.7979647517204285
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.792372465133667
},
{
"filename": "src/db/BaseDb.ts",
"retrieved_chunk": "import Nedb from 'nedb';\nimport fsPath from 'node:path';\nimport { BaseModel } from '../insomniaDbTypes';\ntype DbTargets = 'Request' | 'RequestMeta' | 'RequestGroup' | 'RequestGroupMeta' | 'Workspace' | 'WorkspaceMeta' | 'Project' | 'Environment' | 'ApiSpec' | 'UnitTest' | 'UnitTestSuite';\nexport default class BaseDb<T extends BaseModel> {\n private neDb: Nedb;\n constructor(target: DbTargets) {\n // @ts-ignore\n const filename = fsPath.join(window.app.getPath('userData'), `insomnia.${target}.db`);\n this.neDb = new Nedb({",
"score": 0.7621265053749084
}
] | typescript | testDb: BaseDb<UnitTest>,
) { |
import { exportProject, exportWorkspaceData } from './exportData';
import fs from 'node:fs';
import { importWorkspaceData } from './importData';
import InternalDb from './db/InternalDb';
import { getActiveProjectId, getActiveWorkspace } from './db/localStorageUtils';
import { join } from 'node:path';
import importNewProjectButton from './ui/importNewProjectButton';
import projectDropdown from './ui/projectDropdown';
import alertModal from './ui/react/alertModal';
import renderModal from './ui/react/renderModal';
import injectStyles from './ui/injectStyles';
import autoExport from './autoExport';
// Inject UI elements.
// @ts-ignore
const currentVersion = (window.gitIntegrationInjectCounter || 0) + 1;
// @ts-ignore
window.gitIntegrationInjectCounter = currentVersion;
function doInject() {
// @ts-ignore
// Check if the window was reloaded. When it was reloaded the Global counter changed
if (window.gitIntegrationInjectCounter !== currentVersion) {
return;
}
injectStyles();
projectDropdown();
importNewProjectButton();
window.requestAnimationFrame(doInject);
}
window.requestAnimationFrame(doInject);
setInterval(autoExport, 5000);
module.exports.workspaceActions = [
{
label: 'Export workspace to Git',
icon: 'download',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot export workspace',
'You must first configure the project folder before exporting',
));
return;
}
const data = await exportWorkspaceData(workspaceId);
const targetFile = join(path, workspaceId + '.json');
fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));
},
},
{
label: 'Import workspace from Git',
icon: 'upload',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot import workspace',
'You must first configure the project folder before importing',
));
return;
}
const targetFile = join(path, workspaceId + '.json');
const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());
| await importWorkspaceData(dataRaw); |
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
},
},
];
| src/index.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 0.9344613552093506
},
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');",
"score": 0.9029718637466431
},
{
"filename": "src/autoExport.ts",
"retrieved_chunk": " const newExportJson = JSON.stringify([projectData, workspaces]);\n if (newExportJson === prevExport) {\n // Nothing to export, so lets try to Import\n await autoImportProject(path);\n return;\n }\n prevExport = newExportJson;\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {",
"score": 0.8902221918106079
},
{
"filename": "src/ui/importNewProjectButton.ts",
"retrieved_chunk": " }\n const targetDir = openResult.filePaths[0];\n const projectFile = join(targetDir, 'project.json');\n if (!fs.existsSync(projectFile)) {\n await renderModal(alertModal(\n 'Invalid folder',\n 'This folder does not contain files to import (e.g. \"project.json\", \"wrk_*.json\")',\n ));\n return;\n }",
"score": 0.8876314759254456
},
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " const projectId = getActiveProjectId();\n if (!projectId) {\n await renderModal(alertModal('Internal error', 'No ProjectId found in LocalStorage'));\n return;\n }\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot import Project',",
"score": 0.8810228109359741
}
] | typescript | await importWorkspaceData(dataRaw); |
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/pages/users/user.entity';
import { UserRepository } from 'src/pages/users/user.repository';
import { AuthCredentialDto } from './dto/auth-credential.dto';
import { UnauthorizedException } from "@nestjs/common/exceptions";
import * as bcrypt from 'bcryptjs';
import { AuthLoginDto } from './dto/auth-login.dto';
import { DefaultResponseDto } from './dto/default-response.dto';
import { EntityManager } from 'typeorm';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
private jwtService: JwtService
) {}
async signUp(args:{
authCredentialDto: AuthCredentialDto,
queryRunner: EntityManager,
}) : Promise<DefaultResponseDto> {
try{
const IdCheck = await args.queryRunner.findOne(User,{
where:{ customId : args.authCredentialDto.customId }
});
if(IdCheck){
throw new UnauthorizedException('Id already exists');
}
const EmailCheck = await args.queryRunner.findOne(User,{
where:{ email : args.authCredentialDto.email }
});
if(EmailCheck){
throw new UnauthorizedException('Email already exists');
}
} catch (error) {
throw new UnauthorizedException(error.message);
}
const user = await this.userRepository.createUser(args.authCredentialDto);
return {statusCode:"200", contents : user};
}
async signIn(args:{
authLoginDto: | AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> { |
const {customId , password } = args.authLoginDto;
const user = await this.userRepository.findOne(
{where:{ customId : customId }}
);
if(user && await bcrypt.compare(password, user.password)){
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload, {
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_SECRET_EXPIRATION_TIME,
});
const refreshToken = await this.jwtService.sign({id: user.id}, {
secret: process.env.JWT_REFRESH_TOKEN_SECRET,
expiresIn: process.env.JWT_REFRESH_TOKEN_EXPIRATION_TIME,
});
await this.setCurrentRefreshToken(refreshToken, user.id)
return {statusCode:"200", contents : {accessToken, refreshToken}};
}
else{
throw new UnauthorizedException('login failed');
}
}
async setCurrentRefreshToken(refreshToken: string, id: number) {
const hashedRefreshToken = await bcrypt.hash(refreshToken, 10);
await this.userRepository.update(id, { refreshToken : hashedRefreshToken });
}
async getUserIfRefreshTokenMatches(refreshToken: string, id: number) {
const user = await this.userRepository.findOne({
where: { id },
});
if(user.refreshToken == null){
throw new UnauthorizedException('refresh token is null');
}
const isRefreshTokenMatching = await bcrypt.compare(
refreshToken,
user.refreshToken,
);
if (isRefreshTokenMatching) {
return user;
}else{
throw new UnauthorizedException('not matching refresh token');
}
}
async removeRefreshToken(id: number) {
return this.userRepository.update(id, {
refreshToken: null,
});
}
async getAccessToken(user:User) {
try{
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload);
return accessToken;
}catch(e){
throw new UnauthorizedException(e.message);
}
}
async signOut(user:User){
const userObject = await this.userRepository.findOne({
where: { customId : user.customId },
});
if(userObject){
await this.removeRefreshToken(userObject.id);
return {statusCode:"200", contents : "sign out success"};
}
else{
throw new UnauthorizedException('user not found');
}
}
}
| src/auth/auth.service.ts | jungsungwook-nestjs-core-game-ab8e09b | [
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n @UseGuards(AuthGuard('jwt-refresh-token'))\n async signInByRefreshToken(\n @TransactionManager() queryRunnerManager: EntityManager,\n @GetUser() user: User,\n ): Promise<DefaultResponseDto> {\n try{\n const accessToken = await this.authService.getAccessToken(user);\n return {\n statusCode: \"200\",",
"score": 0.853769063949585
},
{
"filename": "src/auth/jwt.strategy.ts",
"retrieved_chunk": " private UserRepository: UserRepository\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.JWT_SECRET,\n });\n }\n async validate(payload) : Promise<User> {\n const { customId } = payload;\n const user = await this.UserRepository.findOne({ where : {customId} });",
"score": 0.8270261287689209
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }\n async updateDisconnectSocketId(customId: string): Promise<{ statusCode: string, contents: User }> {\n const userObj = await this.userRepository.findOne({ where: { customId: customId } });\n userObj.socketId = null;\n userObj.exitAt = new Date();\n await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }",
"score": 0.8158297538757324
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " const userObj = await this.userRepository.findOne({ where: { customId: user.customId } });\n return { statusCode: '200', contents: userObj };\n }\n async getUser(refreshToken: string): Promise<{ statusCode: string, contents: User }> {\n const userId = await jwt.verify(refreshToken, process.env.JWT_REFRESH_TOKEN_SECRET, (err, decoded) => {\n if (err) {\n return null;\n }\n return decoded['id'];\n });",
"score": 0.81561279296875
},
{
"filename": "src/pages/match/match.service.ts",
"retrieved_chunk": " }\n } catch (e) {\n throw new Error(e);\n }\n }\n async createCustomMatch(customId: string, dto: MatchCreateDto) {\n try {\n const user = await this.usersService.getUserByCustomId(customId);\n const user_status: UserInfo = await this.redisService.get(customId + \"_info\");\n if (",
"score": 0.8109002113342285
}
] | typescript | AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
| ? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty(); |
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 0.8756202459335327
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 0.8719972968101501
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " modified: Date.now(),\n type: 'RequestMeta',\n _id: 'reqm_' + randomBytes(16).toString('hex'),\n name: '', // This is not used by insomnia.\n }\n}\nexport async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {\n // Load the Project\n const projectDb = new BaseDb<Project>('Project');\n const fullProject = await projectDb.findById(projectId);",
"score": 0.8480575680732727
},
{
"filename": "src/ui/importNewProjectButton.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n const configDb = InternalDb.create();\n const projectConfig = configDb.getProject(project.id);\n projectConfig.repositoryPath = openResult.filePaths[0];\n configDb.upsertProject(projectConfig);\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(targetDir, workspaceId + '.json');",
"score": 0.8377496004104614
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 0.8373850584030151
}
] | typescript | ? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty(); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
| export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> { |
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.8531277179718018
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const unittestDb = new BaseDb<UnitTest>('UnitTest');\n const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);\n for (const testSuite of unitTestSuites) {\n const tests = await unittestDb.findBy('parentId', testSuite._id);\n savedUnittestSuites.push({\n tests,\n testSuite,\n });\n }\n return savedUnittestSuites;",
"score": 0.8408122062683105
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 0.8062851428985596
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 0.8048593997955322
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 0.7820216417312622
}
] | typescript | export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> { |
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/pages/users/user.entity';
import { UserRepository } from 'src/pages/users/user.repository';
import { AuthCredentialDto } from './dto/auth-credential.dto';
import { UnauthorizedException } from "@nestjs/common/exceptions";
import * as bcrypt from 'bcryptjs';
import { AuthLoginDto } from './dto/auth-login.dto';
import { DefaultResponseDto } from './dto/default-response.dto';
import { EntityManager } from 'typeorm';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
private jwtService: JwtService
) {}
async signUp(args:{
authCredentialDto: AuthCredentialDto,
queryRunner: EntityManager,
}) : Promise<DefaultResponseDto> {
try{
const IdCheck = await args.queryRunner.findOne(User,{
where:{ customId : args.authCredentialDto.customId }
});
if(IdCheck){
throw new UnauthorizedException('Id already exists');
}
const EmailCheck = await args.queryRunner.findOne(User,{
where:{ email : args.authCredentialDto.email }
});
if(EmailCheck){
throw new UnauthorizedException('Email already exists');
}
} catch (error) {
throw new UnauthorizedException(error.message);
}
const user = await this.userRepository.createUser(args.authCredentialDto);
return {statusCode:"200", contents : user};
}
async signIn(args:{
| authLoginDto: AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> { |
const {customId , password } = args.authLoginDto;
const user = await this.userRepository.findOne(
{where:{ customId : customId }}
);
if(user && await bcrypt.compare(password, user.password)){
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload, {
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_SECRET_EXPIRATION_TIME,
});
const refreshToken = await this.jwtService.sign({id: user.id}, {
secret: process.env.JWT_REFRESH_TOKEN_SECRET,
expiresIn: process.env.JWT_REFRESH_TOKEN_EXPIRATION_TIME,
});
await this.setCurrentRefreshToken(refreshToken, user.id)
return {statusCode:"200", contents : {accessToken, refreshToken}};
}
else{
throw new UnauthorizedException('login failed');
}
}
async setCurrentRefreshToken(refreshToken: string, id: number) {
const hashedRefreshToken = await bcrypt.hash(refreshToken, 10);
await this.userRepository.update(id, { refreshToken : hashedRefreshToken });
}
async getUserIfRefreshTokenMatches(refreshToken: string, id: number) {
const user = await this.userRepository.findOne({
where: { id },
});
if(user.refreshToken == null){
throw new UnauthorizedException('refresh token is null');
}
const isRefreshTokenMatching = await bcrypt.compare(
refreshToken,
user.refreshToken,
);
if (isRefreshTokenMatching) {
return user;
}else{
throw new UnauthorizedException('not matching refresh token');
}
}
async removeRefreshToken(id: number) {
return this.userRepository.update(id, {
refreshToken: null,
});
}
async getAccessToken(user:User) {
try{
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload);
return accessToken;
}catch(e){
throw new UnauthorizedException(e.message);
}
}
async signOut(user:User){
const userObject = await this.userRepository.findOne({
where: { customId : user.customId },
});
if(userObject){
await this.removeRefreshToken(userObject.id);
return {statusCode:"200", contents : "sign out success"};
}
else{
throw new UnauthorizedException('user not found');
}
}
}
| src/auth/auth.service.ts | jungsungwook-nestjs-core-game-ab8e09b | [
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n @UseGuards(AuthGuard('jwt-refresh-token'))\n async signInByRefreshToken(\n @TransactionManager() queryRunnerManager: EntityManager,\n @GetUser() user: User,\n ): Promise<DefaultResponseDto> {\n try{\n const accessToken = await this.authService.getAccessToken(user);\n return {\n statusCode: \"200\",",
"score": 0.8490228652954102
},
{
"filename": "src/auth/jwt.strategy.ts",
"retrieved_chunk": " private UserRepository: UserRepository\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.JWT_SECRET,\n });\n }\n async validate(payload) : Promise<User> {\n const { customId } = payload;\n const user = await this.UserRepository.findOne({ where : {customId} });",
"score": 0.836043119430542
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " const userObj = await this.userRepository.findOne({ where: { customId: user.customId } });\n return { statusCode: '200', contents: userObj };\n }\n async getUser(refreshToken: string): Promise<{ statusCode: string, contents: User }> {\n const userId = await jwt.verify(refreshToken, process.env.JWT_REFRESH_TOKEN_SECRET, (err, decoded) => {\n if (err) {\n return null;\n }\n return decoded['id'];\n });",
"score": 0.8317605257034302
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }\n async updateDisconnectSocketId(customId: string): Promise<{ statusCode: string, contents: User }> {\n const userObj = await this.userRepository.findOne({ where: { customId: customId } });\n userObj.socketId = null;\n userObj.exitAt = new Date();\n await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }",
"score": 0.8274773359298706
},
{
"filename": "src/pages/match/match.controller.ts",
"retrieved_chunk": " try {\n const result = await this.matchService.createCustomMatch(user.customId, body);\n return {\n statusCode: 200,\n contents: result\n }\n } catch (e) {\n throw new HttpException(e.message, e.status);\n }\n }",
"score": 0.8226222991943359
}
] | typescript | authLoginDto: AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> { |
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/pages/users/user.entity';
import { UserRepository } from 'src/pages/users/user.repository';
import { AuthCredentialDto } from './dto/auth-credential.dto';
import { UnauthorizedException } from "@nestjs/common/exceptions";
import * as bcrypt from 'bcryptjs';
import { AuthLoginDto } from './dto/auth-login.dto';
import { DefaultResponseDto } from './dto/default-response.dto';
import { EntityManager } from 'typeorm';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
private jwtService: JwtService
) {}
async signUp(args:{
authCredentialDto: AuthCredentialDto,
queryRunner: EntityManager,
}) : Promise<DefaultResponseDto> {
try{
const IdCheck = await args.queryRunner.findOne(User,{
where:{ customId : args.authCredentialDto.customId }
});
if(IdCheck){
throw new UnauthorizedException('Id already exists');
}
const EmailCheck = await args.queryRunner.findOne(User,{
where:{ email : args.authCredentialDto.email }
});
if(EmailCheck){
throw new UnauthorizedException('Email already exists');
}
} catch (error) {
throw new UnauthorizedException(error.message);
}
const user = await this.userRepository.createUser(args.authCredentialDto);
return {statusCode:"200", contents : user};
}
async signIn(args:{
authLoginDto: AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> {
const {customId , | password } = args.authLoginDto; |
const user = await this.userRepository.findOne(
{where:{ customId : customId }}
);
if(user && await bcrypt.compare(password, user.password)){
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload, {
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_SECRET_EXPIRATION_TIME,
});
const refreshToken = await this.jwtService.sign({id: user.id}, {
secret: process.env.JWT_REFRESH_TOKEN_SECRET,
expiresIn: process.env.JWT_REFRESH_TOKEN_EXPIRATION_TIME,
});
await this.setCurrentRefreshToken(refreshToken, user.id)
return {statusCode:"200", contents : {accessToken, refreshToken}};
}
else{
throw new UnauthorizedException('login failed');
}
}
async setCurrentRefreshToken(refreshToken: string, id: number) {
const hashedRefreshToken = await bcrypt.hash(refreshToken, 10);
await this.userRepository.update(id, { refreshToken : hashedRefreshToken });
}
async getUserIfRefreshTokenMatches(refreshToken: string, id: number) {
const user = await this.userRepository.findOne({
where: { id },
});
if(user.refreshToken == null){
throw new UnauthorizedException('refresh token is null');
}
const isRefreshTokenMatching = await bcrypt.compare(
refreshToken,
user.refreshToken,
);
if (isRefreshTokenMatching) {
return user;
}else{
throw new UnauthorizedException('not matching refresh token');
}
}
async removeRefreshToken(id: number) {
return this.userRepository.update(id, {
refreshToken: null,
});
}
async getAccessToken(user:User) {
try{
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload);
return accessToken;
}catch(e){
throw new UnauthorizedException(e.message);
}
}
async signOut(user:User){
const userObject = await this.userRepository.findOne({
where: { customId : user.customId },
});
if(userObject){
await this.removeRefreshToken(userObject.id);
return {statusCode:"200", contents : "sign out success"};
}
else{
throw new UnauthorizedException('user not found');
}
}
}
| src/auth/auth.service.ts | jungsungwook-nestjs-core-game-ab8e09b | [
{
"filename": "src/auth/jwt.strategy.ts",
"retrieved_chunk": " private UserRepository: UserRepository\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.JWT_SECRET,\n });\n }\n async validate(payload) : Promise<User> {\n const { customId } = payload;\n const user = await this.UserRepository.findOne({ where : {customId} });",
"score": 0.8581226468086243
},
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n @UseGuards(AuthGuard('jwt-refresh-token'))\n async signInByRefreshToken(\n @TransactionManager() queryRunnerManager: EntityManager,\n @GetUser() user: User,\n ): Promise<DefaultResponseDto> {\n try{\n const accessToken = await this.authService.getAccessToken(user);\n return {\n statusCode: \"200\",",
"score": 0.8494058847427368
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " const userObj = await this.userRepository.findOne({ where: { customId: user.customId } });\n return { statusCode: '200', contents: userObj };\n }\n async getUser(refreshToken: string): Promise<{ statusCode: string, contents: User }> {\n const userId = await jwt.verify(refreshToken, process.env.JWT_REFRESH_TOKEN_SECRET, (err, decoded) => {\n if (err) {\n return null;\n }\n return decoded['id'];\n });",
"score": 0.8478243350982666
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }\n async updateDisconnectSocketId(customId: string): Promise<{ statusCode: string, contents: User }> {\n const userObj = await this.userRepository.findOne({ where: { customId: customId } });\n userObj.socketId = null;\n userObj.exitAt = new Date();\n await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }",
"score": 0.8349632024765015
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": "export class UsersService {\n constructor(\n @InjectRepository(UserRepository)\n private userRepository: UserRepository\n ) { }\n async getAllUsers(): Promise<{ statusCode: string, contents: User[] }> {\n const userObj = await this.userRepository.find();\n return { statusCode: '200', contents: userObj };\n }\n async getUserInfo(user: User): Promise<{ statusCode: string, contents: User }> {",
"score": 0.8296421766281128
}
] | typescript | password } = args.authLoginDto; |
import { CacheModule, MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common';
import { GatewayModule } from './socket-gateways/gateway.module';
import path from 'path';
import { resolve } from 'path';
import * as dotenv from 'dotenv';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { AuthTokenMiddleware } from './auth/authToken.middleware';
import { UsersModule } from './pages/users/users.module';
import { User } from './pages/users/user.entity';
import { SchedulerModule } from './pages/schedule/scheduler.module';
import { MatchModule } from './pages/match/match.module';
dotenv.config({ path: resolve(__dirname, '../.env') });
@Module({
imports: [
CacheModule.register(
{
isGlobal: true,
ttl: 60*60*12, // seconds
max: 1000, // maximum number of items in cache
},
),
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
TypeOrmModule.forRoot({
type: 'mariadb',
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT) as number,
username: process.env.DB_USER as string || 'abcd',
password: process.env.DB_PASS,
database: process.env.DB_DATABASE,
timezone: '+09:00',
entities: [User,],
synchronize: true,
}),
GatewayModule,
UsersModule,
AuthModule,
SchedulerModule,
MatchModule,
],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply( | AuthTokenMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL }); |
}
}
| src/app.module.ts | jungsungwook-nestjs-core-game-ab8e09b | [
{
"filename": "src/pages/match/match.module.ts",
"retrieved_chunk": " TypeOrmModule.forFeature([]),\n AuthModule,\n RedisCacheModule,\n UsersModule,\n forwardRef(() => GatewayModule),\n ],\n controllers: [MatchController,],\n providers: [MatchService,],\n exports: [MatchService],\n})",
"score": 0.794807493686676
},
{
"filename": "src/auth/auth.service.ts",
"retrieved_chunk": "import { EntityManager } from 'typeorm';\n@Injectable()\nexport class AuthService {\n constructor(\n @InjectRepository(UserRepository)\n private userRepository: UserRepository,\n private jwtService: JwtService\n ) {}\n async signUp(args:{\n authCredentialDto: AuthCredentialDto,",
"score": 0.7915459871292114
},
{
"filename": "src/socket-gateways/gateway.core.ts",
"retrieved_chunk": " origin: '*',\n },\n})\nexport class CoreGateway {\n @WebSocketServer()\n server: Server;\n @SubscribeMessage('ClientToServer')\n async handleMessage(@MessageBody() data) {\n const returnText = 'Server received: ' + data;\n console.log(returnText);",
"score": 0.7847082018852234
},
{
"filename": "src/pages/chat/chat.module.ts",
"retrieved_chunk": " AuthModule,\n RedisCacheModule,\n forwardRef(() => GatewayModule),\n ],\n controllers: [ChatController],\n providers: [ChatService],\n exports: [ChatService],\n})\nexport class ChatModule { }",
"score": 0.7716237902641296
},
{
"filename": "src/socket-gateways/gateway.core.ts",
"retrieved_chunk": "import {\n MessageBody,\n SubscribeMessage,\n WebSocketGateway,\n WebSocketServer,\n} from '@nestjs/websockets';\nimport { Server, Socket } from 'socket.io';\n@WebSocketGateway(8080, { \n transports: ['websocket'] ,\n cors: {",
"score": 0.7689380645751953
}
] | typescript | AuthTokenMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL }); |
import { exportProject, exportWorkspaceData } from './exportData';
import fs from 'node:fs';
import { importWorkspaceData } from './importData';
import InternalDb from './db/InternalDb';
import { getActiveProjectId, getActiveWorkspace } from './db/localStorageUtils';
import { join } from 'node:path';
import importNewProjectButton from './ui/importNewProjectButton';
import projectDropdown from './ui/projectDropdown';
import alertModal from './ui/react/alertModal';
import renderModal from './ui/react/renderModal';
import injectStyles from './ui/injectStyles';
import autoExport from './autoExport';
// Inject UI elements.
// @ts-ignore
const currentVersion = (window.gitIntegrationInjectCounter || 0) + 1;
// @ts-ignore
window.gitIntegrationInjectCounter = currentVersion;
function doInject() {
// @ts-ignore
// Check if the window was reloaded. When it was reloaded the Global counter changed
if (window.gitIntegrationInjectCounter !== currentVersion) {
return;
}
injectStyles();
projectDropdown();
importNewProjectButton();
window.requestAnimationFrame(doInject);
}
window.requestAnimationFrame(doInject);
setInterval(autoExport, 5000);
module.exports.workspaceActions = [
{
label: 'Export workspace to Git',
icon: 'download',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot export workspace',
'You must first configure the project folder before exporting',
));
return;
}
const data = | await exportWorkspaceData(workspaceId); |
const targetFile = join(path, workspaceId + '.json');
fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));
},
},
{
label: 'Import workspace from Git',
icon: 'upload',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot import workspace',
'You must first configure the project folder before importing',
));
return;
}
const targetFile = join(path, workspaceId + '.json');
const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());
await importWorkspaceData(dataRaw);
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
},
},
];
| src/index.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 0.9720739722251892
},
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " const projectId = getActiveProjectId();\n if (!projectId) {\n await renderModal(alertModal('Internal error', 'No ProjectId found in LocalStorage'));\n return;\n }\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot import Project',",
"score": 0.9023122191429138
},
{
"filename": "src/ui/projectDropdown/configureGitRepoButton.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannnot configure Folder',\n 'Cannot configure folder for default repository. Please create a now Project',\n ));\n return;\n }\n await renderModal(configureProject(projectId));\n });\n // Hover effect\n configureProjectButton.addEventListener('mouseover', () => {",
"score": 0.8751018643379211
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " `;\n gitCommitButton.addEventListener('click', async () => {\n // \"Close\" the dropdown\n projectDropdown.remove();\n const projectId = getActiveProjectId();\n if (!projectId) {\n await renderModal(alertModal('Internal error', 'No ProjectId found in LocalStorage'));\n return;\n }\n const config = InternalDb.create();",
"score": 0.8710957765579224
},
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');",
"score": 0.8689417839050293
}
] | typescript | await exportWorkspaceData(workspaceId); |
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/pages/users/user.entity';
import { UserRepository } from 'src/pages/users/user.repository';
import { AuthCredentialDto } from './dto/auth-credential.dto';
import { UnauthorizedException } from "@nestjs/common/exceptions";
import * as bcrypt from 'bcryptjs';
import { AuthLoginDto } from './dto/auth-login.dto';
import { DefaultResponseDto } from './dto/default-response.dto';
import { EntityManager } from 'typeorm';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
private jwtService: JwtService
) {}
async signUp(args:{
authCredentialDto: AuthCredentialDto,
queryRunner: EntityManager,
}) : Promise<DefaultResponseDto> {
try{
const IdCheck = await args.queryRunner.findOne(User,{
where:{ customId : args.authCredentialDto.customId }
});
if(IdCheck){
throw new UnauthorizedException('Id already exists');
}
const EmailCheck = await args.queryRunner.findOne(User,{
where:{ email : args.authCredentialDto.email }
});
if(EmailCheck){
throw new UnauthorizedException('Email already exists');
}
} catch (error) {
throw new UnauthorizedException(error.message);
}
const user = await this.userRepository.createUser(args.authCredentialDto);
return {statusCode:"200", contents : user};
}
async signIn(args:{
authLoginDto: AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> {
| const {customId , password } = args.authLoginDto; |
const user = await this.userRepository.findOne(
{where:{ customId : customId }}
);
if(user && await bcrypt.compare(password, user.password)){
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload, {
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_SECRET_EXPIRATION_TIME,
});
const refreshToken = await this.jwtService.sign({id: user.id}, {
secret: process.env.JWT_REFRESH_TOKEN_SECRET,
expiresIn: process.env.JWT_REFRESH_TOKEN_EXPIRATION_TIME,
});
await this.setCurrentRefreshToken(refreshToken, user.id)
return {statusCode:"200", contents : {accessToken, refreshToken}};
}
else{
throw new UnauthorizedException('login failed');
}
}
async setCurrentRefreshToken(refreshToken: string, id: number) {
const hashedRefreshToken = await bcrypt.hash(refreshToken, 10);
await this.userRepository.update(id, { refreshToken : hashedRefreshToken });
}
async getUserIfRefreshTokenMatches(refreshToken: string, id: number) {
const user = await this.userRepository.findOne({
where: { id },
});
if(user.refreshToken == null){
throw new UnauthorizedException('refresh token is null');
}
const isRefreshTokenMatching = await bcrypt.compare(
refreshToken,
user.refreshToken,
);
if (isRefreshTokenMatching) {
return user;
}else{
throw new UnauthorizedException('not matching refresh token');
}
}
async removeRefreshToken(id: number) {
return this.userRepository.update(id, {
refreshToken: null,
});
}
async getAccessToken(user:User) {
try{
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload);
return accessToken;
}catch(e){
throw new UnauthorizedException(e.message);
}
}
async signOut(user:User){
const userObject = await this.userRepository.findOne({
where: { customId : user.customId },
});
if(userObject){
await this.removeRefreshToken(userObject.id);
return {statusCode:"200", contents : "sign out success"};
}
else{
throw new UnauthorizedException('user not found');
}
}
}
| src/auth/auth.service.ts | jungsungwook-nestjs-core-game-ab8e09b | [
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n @UseGuards(AuthGuard('jwt-refresh-token'))\n async signInByRefreshToken(\n @TransactionManager() queryRunnerManager: EntityManager,\n @GetUser() user: User,\n ): Promise<DefaultResponseDto> {\n try{\n const accessToken = await this.authService.getAccessToken(user);\n return {\n statusCode: \"200\",",
"score": 0.8581370115280151
},
{
"filename": "src/auth/jwt.strategy.ts",
"retrieved_chunk": " private UserRepository: UserRepository\n ) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: process.env.JWT_SECRET,\n });\n }\n async validate(payload) : Promise<User> {\n const { customId } = payload;\n const user = await this.UserRepository.findOne({ where : {customId} });",
"score": 0.8575236201286316
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " const userObj = await this.userRepository.findOne({ where: { customId: user.customId } });\n return { statusCode: '200', contents: userObj };\n }\n async getUser(refreshToken: string): Promise<{ statusCode: string, contents: User }> {\n const userId = await jwt.verify(refreshToken, process.env.JWT_REFRESH_TOKEN_SECRET, (err, decoded) => {\n if (err) {\n return null;\n }\n return decoded['id'];\n });",
"score": 0.8422852158546448
},
{
"filename": "src/pages/match/match.service.ts",
"retrieved_chunk": " }\n } catch (e) {\n throw new Error(e);\n }\n }\n async createCustomMatch(customId: string, dto: MatchCreateDto) {\n try {\n const user = await this.usersService.getUserByCustomId(customId);\n const user_status: UserInfo = await this.redisService.get(customId + \"_info\");\n if (",
"score": 0.8391898274421692
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }\n async updateDisconnectSocketId(customId: string): Promise<{ statusCode: string, contents: User }> {\n const userObj = await this.userRepository.findOne({ where: { customId: customId } });\n userObj.socketId = null;\n userObj.exitAt = new Date();\n await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }",
"score": 0.8322656154632568
}
] | typescript | const {customId , password } = args.authLoginDto; |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb | .findById(projectId); |
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 0.8796299695968628
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 0.841353178024292
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 0.8386777639389038
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " // Collect OldIds of Requests / Folders so we can delete deleted Docs at the end\n const oldIds = await workspaceDb.findById(data.id)\n ? OldIds.fromOldData(await exportWorkspaceData(data.id))\n : OldIds.createEmpty();\n // Update Workspace metadata\n await workspaceDb.upsert(data.workspace);\n const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');\n const fullMeta: WorkspaceMeta = {\n ...data.meta,\n // These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here",
"score": 0.8376498222351074
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 0.8285351991653442
}
] | typescript | .findById(projectId); |
import fs from 'node:fs';
import { join } from 'path';
import InternalDb from './db/InternalDb';
import { getActiveProjectId } from './db/localStorageUtils';
import { exportProject } from './exportData';
import { importProject, readProjectData } from './importData';
import renderModal from './ui/react/renderModal';
import confirmModal from './ui/react/confirmModal';
let prevExport = '';
export default async function autoExport() {
const projectId = getActiveProjectId();
if (!projectId) {
return;
}
const config = InternalDb.create();
const { repositoryPath: path, autoExport } = config.getProject(projectId);
if (!path || !autoExport || projectId === 'proj_default-project') {
return;
}
const [projectData, workspaces] = await exportProject(projectId);
const newExportJson = JSON.stringify([projectData, workspaces]);
if (newExportJson === prevExport) {
// Nothing to export, so lets try to Import
await autoImportProject(path);
return;
}
prevExport = newExportJson;
const targetFile = join(path, 'project.json');
fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));
for (const workspace of workspaces) {
const targetFile = join(path, workspace.id + '.json');
fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));
}
}
let prevImport = '';
async function autoImportProject(path: string) {
let project, workspaceData;
try {
| [project, workspaceData] = readProjectData(path); |
} catch (e) {
console.error('[IPGI] Error while gathering import data during auto import. This might not be a bug', e);
return;
}
const newImportJson = JSON.stringify([project, workspaceData]);
// Do not import the first time
if (prevImport === '') {
prevImport = newImportJson;
return;
}
if (prevImport === newImportJson) {
// Nothing to import
return;
}
const doImport = await renderModal<boolean>(confirmModal(
'Import project',
'Import chhanged project data? Insomnia will restart.',
));
if (!doImport) {
return;
}
await importProject(project, workspaceData);
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
}
| src/autoExport.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');",
"score": 0.9103482961654663
},
{
"filename": "src/index.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannot export workspace',\n 'You must first configure the project folder before exporting',\n ));\n return;\n }\n const data = await exportWorkspaceData(workspaceId);\n const targetFile = join(path, workspaceId + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));\n },",
"score": 0.8768796324729919
},
{
"filename": "src/index.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannot import workspace',\n 'You must first configure the project folder before importing',\n ));\n return;\n }\n const targetFile = join(path, workspaceId + '.json');\n const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());\n await importWorkspaceData(dataRaw);\n // Force Insomnia to read all data",
"score": 0.8732559084892273
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(path, workspaceId + '.json');\n // TODO: Validate this using Zod\n const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());\n workspaceData.push(workspace);\n }",
"score": 0.858282208442688
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n await gitClient.add(targetFile);\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));\n await gitClient.add(targetFile);\n }\n const status = await gitClient.status();\n if (status.staged.length === 0) {\n await renderModal(alertModal('No changes', 'There are no changes to commited'));",
"score": 0.8512387275695801
}
] | typescript | [project, workspaceData] = readProjectData(path); |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function | getApiSpec(workspaceId: string): Promise<ApiSpec | null> { |
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " }\n for (const testSuites of oldIds.getTestSuites()) {\n await testSuitesDb.deleteBy('_id', testSuites);\n }\n for (const test of oldIds.getTests()) {\n await testDb.deleteBy('_id', test);\n }\n}\nexport async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {\n const workspaceDb = new BaseDb<Workspace>('Workspace');",
"score": 0.8452063798904419
},
{
"filename": "src/types.ts",
"retrieved_chunk": " workspace: Workspace,\n meta: GitSavedWorkspaceMeta,\n requests: GitSavedRequest[],\n environments: Environment[],\n apiSpec?: ApiSpec,\n unitTestSuites: GitSavedUnitTestSuite[],\n}\nexport type GitSavedUnitTestSuite = {\n testSuite: UnittestSuite,\n tests: UnitTest[],",
"score": 0.7901968955993652
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 0.7684550285339355
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 0.7597503066062927
},
{
"filename": "src/autoExport.ts",
"retrieved_chunk": " const targetFile = join(path, workspace.id + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));\n }\n}\nlet prevImport = '';\nasync function autoImportProject(path: string) {\n let project, workspaceData;\n try {\n [project, workspaceData] = readProjectData(path);\n } catch (e) {",
"score": 0.7553661465644836
}
] | typescript | getApiSpec(workspaceId: string): Promise<ApiSpec | null> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
| const unittestDb = new BaseDb<UnitTest>('UnitTest'); |
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " }\n for (const testSuites of oldIds.getTestSuites()) {\n await testSuitesDb.deleteBy('_id', testSuites);\n }\n for (const test of oldIds.getTests()) {\n await testDb.deleteBy('_id', test);\n }\n}\nexport async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {\n const workspaceDb = new BaseDb<Workspace>('Workspace');",
"score": 0.8300690650939941
},
{
"filename": "src/types.ts",
"retrieved_chunk": " workspace: Workspace,\n meta: GitSavedWorkspaceMeta,\n requests: GitSavedRequest[],\n environments: Environment[],\n apiSpec?: ApiSpec,\n unitTestSuites: GitSavedUnitTestSuite[],\n}\nexport type GitSavedUnitTestSuite = {\n testSuite: UnittestSuite,\n tests: UnitTest[],",
"score": 0.8280242681503296
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " sidebarHidden: false,\n sidebarWidth: 19,\n pushSnapshotOnInitialize: false,\n };\n await workspaceMetaDb.upsert(fullMeta);\n const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);",
"score": 0.826181173324585
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "async function removeOldData(\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n environmentDb: BaseDb<Environment>,\n testSuitesDb: BaseDb<UnittestSuite>,\n testDb: BaseDb<UnitTest>,\n) {",
"score": 0.813360869884491
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " requests: GitSavedRequest[],\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n) {\n for (const request of requests) {\n if (request.type === 'group') {\n await requestGroupDb.upsert(request.group);",
"score": 0.8067746162414551
}
] | typescript | const unittestDb = new BaseDb<UnitTest>('UnitTest'); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
| testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.8486347198486328
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8322790861129761
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.7979647517204285
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.792372465133667
},
{
"filename": "src/db/BaseDb.ts",
"retrieved_chunk": "import Nedb from 'nedb';\nimport fsPath from 'node:path';\nimport { BaseModel } from '../insomniaDbTypes';\ntype DbTargets = 'Request' | 'RequestMeta' | 'RequestGroup' | 'RequestGroupMeta' | 'Workspace' | 'WorkspaceMeta' | 'Project' | 'Environment' | 'ApiSpec' | 'UnitTest' | 'UnitTestSuite';\nexport default class BaseDb<T extends BaseModel> {\n private neDb: Nedb;\n constructor(target: DbTargets) {\n // @ts-ignore\n const filename = fsPath.join(window.app.getPath('userData'), `insomnia.${target}.db`);\n this.neDb = new Nedb({",
"score": 0.7621265053749084
}
] | typescript | testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
| const workspaces = await workspaceDb.findBy('parentId', fullProject._id); |
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 0.9086405634880066
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 0.8925005197525024
},
{
"filename": "src/ui/importNewProjectButton.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n const configDb = InternalDb.create();\n const projectConfig = configDb.getProject(project.id);\n projectConfig.repositoryPath = openResult.filePaths[0];\n configDb.upsertProject(projectConfig);\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(targetDir, workspaceId + '.json');",
"score": 0.8606725931167603
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " // Collect OldIds of Requests / Folders so we can delete deleted Docs at the end\n const oldIds = await workspaceDb.findById(data.id)\n ? OldIds.fromOldData(await exportWorkspaceData(data.id))\n : OldIds.createEmpty();\n // Update Workspace metadata\n await workspaceDb.upsert(data.workspace);\n const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');\n const fullMeta: WorkspaceMeta = {\n ...data.meta,\n // These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here",
"score": 0.8550550937652588
},
{
"filename": "src/index.ts",
"retrieved_chunk": " },\n {\n label: 'Import workspace from Git',\n icon: 'upload',\n action: async () => {\n const projectId = getActiveProjectId();\n const workspaceId = getActiveWorkspace();\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {",
"score": 0.8465902209281921
}
] | typescript | const workspaces = await workspaceDb.findBy('parentId', fullProject._id); |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, | GitSavedWorkspace[]]> { |
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 0.8279551267623901
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " remoteId?: string, // Only remote projects have a remote id\n} & BaseModel;\n// Workspace\nexport type Workspace = {\n name: string;\n description: string;\n certificates?: any; // deprecate\n scope: 'design' | 'collection',\n} & BaseModel;\n// WorkspaceMeta",
"score": 0.810288667678833
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 0.80376136302948
},
{
"filename": "src/db/InternalDb.ts",
"retrieved_chunk": " return {\n id: projectId,\n remote: null,\n repositoryPath: null,\n autoExport: false,\n };\n }\n return this.config.projects[index];\n }\n public upsertProject(project: ProjectConfig) {",
"score": 0.8012011051177979
},
{
"filename": "src/db/InternalDb.ts",
"retrieved_chunk": "import fsPath from 'node:path';\nimport fs from 'node:fs';\nexport type ProjectConfig = {\n id: string,\n repositoryPath: string | null,\n remote: string | null,\n autoExport?: boolean\n // TODO: For later, enable Sync using GitHub / GitLab OAuth-Apis (#1)\n}\ntype InternalConfig = {",
"score": 0.7909451127052307
}
] | typescript | GitSavedWorkspace[]]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
| requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> { |
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " requests: GitSavedRequest[],\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n) {\n for (const request of requests) {\n if (request.type === 'group') {\n await requestGroupDb.upsert(request.group);",
"score": 0.8799020051956177
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "async function removeOldData(\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n environmentDb: BaseDb<Environment>,\n testSuitesDb: BaseDb<UnittestSuite>,\n testDb: BaseDb<UnitTest>,\n) {",
"score": 0.855069637298584
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " sidebarHidden: false,\n sidebarWidth: 19,\n pushSnapshotOnInitialize: false,\n };\n await workspaceMetaDb.upsert(fullMeta);\n const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);",
"score": 0.8305217623710632
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 0.8125197887420654
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 0.7966398596763611
}
] | typescript | requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let | oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id); |
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " if (!workspace) {\n throw new Error('No Workspace found for id: ' + workspaceId);\n }\n const name = workspace.name;\n // Find WorkspaceMeta\n const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');\n const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);\n const fullMeta = fullMetas[0];\n const meta: GitSavedWorkspaceMeta = {\n _id: fullMeta._id,",
"score": 0.8745170831680298
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 0.8508995771408081
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " modified: Date.now(),\n type: 'RequestMeta',\n _id: 'reqm_' + randomBytes(16).toString('hex'),\n name: '', // This is not used by insomnia.\n }\n}\nexport async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {\n // Load the Project\n const projectDb = new BaseDb<Project>('Project');\n const fullProject = await projectDb.findById(projectId);",
"score": 0.8472014665603638
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 0.8468334674835205
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8005532026290894
}
] | typescript | oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
| requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.9371401071548462
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8237112760543823
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.8184288740158081
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.8123272657394409
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 0.7550005912780762
}
] | typescript | requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { Plugin } from "obsidian";
import RveStyles, { BlockColorRule } from "./styles";
import { RveSettingTab, RveSettings, DEFAULT_SETTINGS } from "./settings";
import Commands from "./commands";
import BlockSelector from "./block-selector";
export default class ReadingViewEnhancer extends Plugin {
settings: RveSettings;
styles: RveStyles;
blockSelector: BlockSelector;
/**
* On load,
*
* - Load settings & styles
* - Activate block selector
* - It actually do its work if settings.enableBlockSelector is true
* - Register all commands
* - Add settings tab
*/
async onload() {
// Settings & Styles
await this.loadSettings();
this.styles = new RveStyles();
this.app.workspace.onLayoutReady(() => this.applySettingsToStyles());
// Activate block selector.
this.blockSelector = new BlockSelector(this);
this.blockSelector.activate();
// Register commands
new Commands(this).register();
// Add settings tab at last
this.addSettingTab(new RveSettingTab(this));
// Leave a message in the console
console.log("Loaded 'Reading View Enhancer'");
}
/**
* On unload,
*
* - Remove all styles
*/
async onunload() {
this.styles.cleanup();
// Leave a message in the console
console.log("Unloaded 'Reading View Enhancer'");
}
// ===================================================================
/**
* Load settings
*/
async loadSettings() {
| this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); |
}
/**
* Save settings
*/
async saveSettings() {
await this.saveData(this.settings);
}
/**
* Apply settings to styles
*
* - Apply block color
* - Apply always on collapse indicator
* - Apply prevent table overflowing
* - Apply scrollable code
*/
private applySettingsToStyles() {
this.applyBlockColor();
this.applyAlwaysOnCollapse();
this.applyPreventTableOverflowing();
this.applyScrollableCode();
this.styles.apply();
}
/**
* Apply block color
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyBlockColor(isImmediate = false) {
const blockColor = this.styles.of("block-color") as BlockColorRule;
blockColor.set(this.settings.blockColor);
if (isImmediate) this.styles.apply();
}
/**
* Apply always on collapse indicator
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyAlwaysOnCollapse(isImmediate = false) {
this.styles.of("collapse-indicator").isActive =
this.settings.alwaysOnCollapseIndicator;
if (isImmediate) this.styles.apply();
}
/**
* Apply prevent table overflowing
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyPreventTableOverflowing(isImmediate = false) {
this.styles.of("prevent-table-overflowing").isActive =
this.settings.preventTableOverflowing;
if (isImmediate) this.styles.apply();
}
/**
* Apply scrollable code
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyScrollableCode(isImmediate = false) {
this.styles.of("scrollable-code").isActive = this.settings.scrollableCode;
if (isImmediate) this.styles.apply();
}
}
| src/main.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/settings/index.ts",
"retrieved_chunk": "\tconstructor(plugin: ReadingViewEnhancer) {\n\t\tsuper(app, plugin);\n\t\tthis.plugin = plugin;\n\t}\n\t/**\n\t * Displays settings tab.\n\t */\n\tdisplay() {\n\t\tconst { containerEl } = this;\n\t\t// Clear all first",
"score": 0.8388561010360718
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Activate BlockSelector\n\t */\n\tactivate() {\n\t\tthis.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));\n\t}\n\t/**\n\t * Select top block in the view\n\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */",
"score": 0.7472196817398071
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\tthis.template = template;\n\t\tthis.isActive = false;\n\t\tthis.injectVariables = injectVariables;\n\t}\n\t/**\n\t * Get the rule after injecting variables\n\t *\n\t * @returns {string} The rule\n\t */\n\tgetRule() {",
"score": 0.7390605807304382
},
{
"filename": "src/settings/block/block-selector-mobile.ts",
"retrieved_chunk": "import { Setting, ToggleComponent } from \"obsidian\";\nimport ReadingViewEnhancer from \"src/main\";\n/**\n * Disable block selector on mobile setting component\n */\nexport default class DisableBlockSelectorOnMobileSetting extends Setting {\n\tplugin: ReadingViewEnhancer;\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tsuper(containerEl);\n\t\tthis.plugin = plugin;",
"score": 0.7378408312797546
},
{
"filename": "src/settings/miscellaneous/scrollable-code.ts",
"retrieved_chunk": "import { Setting, ToggleComponent } from \"obsidian\";\nimport ReadingViewEnhancer from \"src/main\";\n/**\n * Scrollable code setting component\n */\nexport default class ScrollableCodeSetting extends Setting {\n\tplugin: ReadingViewEnhancer;\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tsuper(containerEl);\n\t\tthis.plugin = plugin;",
"score": 0.7377768754959106
}
] | typescript | this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb. | deleteBy('_id', oldWorkspace); |
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 0.8868494033813477
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 0.8143088817596436
},
{
"filename": "src/ui/importNewProjectButton.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n const configDb = InternalDb.create();\n const projectConfig = configDb.getProject(project.id);\n projectConfig.repositoryPath = openResult.filePaths[0];\n configDb.upsertProject(projectConfig);\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(targetDir, workspaceId + '.json');",
"score": 0.811366081237793
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " if (!workspace) {\n throw new Error('No Workspace found for id: ' + workspaceId);\n }\n const name = workspace.name;\n // Find WorkspaceMeta\n const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');\n const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);\n const fullMeta = fullMetas[0];\n const meta: GitSavedWorkspaceMeta = {\n _id: fullMeta._id,",
"score": 0.8100199699401855
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " }\n const baseEnvironment = baseEnvironments[0];\n // Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top\n const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))\n .filter((env) => env.isPrivate === false);\n environments.unshift(baseEnvironment);\n const apiSpec = await getApiSpec(workspaceId);\n const unitTestSuites = await getTestSuites(workspaceId);\n return {\n id: workspaceId,",
"score": 0.7869808077812195
}
] | typescript | deleteBy('_id', oldWorkspace); |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
| el.setAttribute(BLOCK_ATTR, "true"); |
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 0.8566746711730957
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * Fold/Unfold block.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tprivate toggleFold(block: HTMLElement) {\n\t\tconst collapseIndicator = block.querySelector(\n\t\t\tCOLLAPSE_INDICATORS.join(\",\")\n\t\t) as HTMLElement;\n\t\tif (collapseIndicator) {\n\t\t\tcollapseIndicator.click();",
"score": 0.8492698669433594
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Trigger 'select' on clicked block element.\n\t *\n\t * @param e {MouseEvent} Mouse event\n\t */\n\tonBlockClick(e: MouseEvent) {\n\t\tconst target = e.target as HTMLElement;\n\t\tconst block = target.closest(`[${BLOCK_ATTR}=true]`);\n\t\tif (block instanceof HTMLElement) {",
"score": 0.8381102681159973
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " * @param element {HTMLElement} Element to search\n * @returns {HTMLElement | null} First block element\n */\nconst findBlock = (element: HTMLElement): HTMLElement | null => {\n\tif (isBlock(element)) {\n\t\treturn element;\n\t}\n\tlet block = null;\n\tconst childElements = element.children;\n\tfor (let i = 0; i < childElements.length; i++) {",
"score": 0.8327310085296631
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tselect(block: HTMLElement) {\n\t\tblock.focus();\n\t\tblock.addClass(SELECTED_BLOCK);\n\t\tthis.selectedBlock = block;\n\t}\n\t/**\n\t * Unselect block element.",
"score": 0.7962045669555664
}
] | typescript | el.setAttribute(BLOCK_ATTR, "true"); |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element | .querySelectorAll(BLOCKS.join(", ")); |
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t} else {\n\t\t\tconst next = findNextBlock(block);\n\t\t\tif (next) this.select(next as HTMLElement);\n\t\t}\n\t}\n\t/**\n\t * Select previous block or scroll to see the block's top.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */",
"score": 0.8428828716278076
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " * @param element {HTMLElement} Element to search\n * @returns {HTMLElement | null} First block element\n */\nconst findBlock = (element: HTMLElement): HTMLElement | null => {\n\tif (isBlock(element)) {\n\t\treturn element;\n\t}\n\tlet block = null;\n\tconst childElements = element.children;\n\tfor (let i = 0; i < childElements.length; i++) {",
"score": 0.834570050239563
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Trigger 'select' on clicked block element.\n\t *\n\t * @param e {MouseEvent} Mouse event\n\t */\n\tonBlockClick(e: MouseEvent) {\n\t\tconst target = e.target as HTMLElement;\n\t\tconst block = target.closest(`[${BLOCK_ATTR}=true]`);\n\t\tif (block instanceof HTMLElement) {",
"score": 0.8283179402351379
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 0.8263521194458008
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\telse return null;\n};\n/**\n * Check if the given element is a block element\n *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is a block element\n */\nconst isBlock = (element: HTMLElement) => {\n\treturn element.getAttribute(BLOCK_ATTR) === \"true\";",
"score": 0.8237411975860596
}
] | typescript | .querySelectorAll(BLOCKS.join(", ")); |
import { BLOCK_ATTR, IS_COLLAPSED, MARKDOWN_PREVIEW_VIEW } from "../constants";
export const isBottomInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.bottom <= window.innerHeight;
};
export const scrollBottomIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.bottom - scrollable.clientHeight + 200,
});
};
export const isTopInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.top >= 0;
};
export const scrollTopIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.top - 200,
});
};
/**
* Find next block element to select.
* Return null if there is no next block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Next block element
*/
export const findNextBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
let nextBlock = null;
// Start by checking if there's a block element inside the current element
if (!isCollapsed(currentElement)) {
const children = currentElement.children;
for (let i = 0; i < children.length; i++) {
nextBlock = findBlock(children[i] as HTMLElement);
if (nextBlock) return nextBlock;
}
}
// Check next siblings of current element
let nextSibling = currentElement.nextElementSibling;
while (nextSibling) {
nextBlock = findBlock(nextSibling as HTMLElement);
if (nextBlock) return nextBlock;
nextSibling = nextSibling.nextElementSibling;
}
// Check next siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) {
let parentSibling = parent.nextElementSibling;
while (parentSibling) {
nextBlock = findBlock(parentSibling as HTMLElement);
if (nextBlock) return nextBlock;
parentSibling = parentSibling.nextElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Find previous block element to select.
* Return null if there is no previous block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Previous block element
*/
export const findPreviousBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
// Check previous siblings of current element
let prevSibling = currentElement.previousElementSibling;
while (prevSibling) {
const prevBlock = findLastBlock(prevSibling as HTMLElement);
if (prevBlock) return prevBlock;
prevSibling = prevSibling.previousElementSibling;
}
// Check previous siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.classList.contains(MARKDOWN_PREVIEW_VIEW)) {
// Check ancestors of current element first
if (isBlock(parent)) return parent;
let parentSibling = parent.previousElementSibling;
while (parentSibling) {
const prevBlock = findLastBlock(parentSibling as HTMLElement);
if (prevBlock) return prevBlock;
parentSibling = parentSibling.previousElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Check if the given element is collapsed
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is collapsed
*/
const isCollapsed = (element: HTMLElement) => {
return element.hasClass(IS_COLLAPSED);
};
/**
* Find first block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} First block element
*/
const findBlock = (element: HTMLElement): HTMLElement | null => {
if (isBlock(element)) {
return element;
}
let block = null;
const childElements = element.children;
for (let i = 0; i < childElements.length; i++) {
block = findBlock(childElements[i] as HTMLElement);
if (block) return block;
}
return null;
};
/**
* Find last block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} Last block element
*/
const findLastBlock = (element: HTMLElement): HTMLElement | null => {
if (isCollapsed(element) && isBlock(element)) return element;
let block = null;
const childElements = element.children;
for (let i = childElements.length - 1; i >= 0; i--) {
block = findLastBlock(childElements[i] as HTMLElement);
if (block) return block;
}
if (isBlock(element)) return element;
else return null;
};
/**
* Check if the given element is a block element
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is a block element
*/
const isBlock = (element: HTMLElement) => {
| return element.getAttribute(BLOCK_ATTR) === "true"; |
};
/**
* Return the scrollable parent element of the given element
*
* @param node {HTMLElement} Element to start searching
* @returns {HTMLElement | null} Scrollable parent element
*/
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
if (node == null) return null;
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode as HTMLElement);
}
};
| src/block-selector/selection-util.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If selected block is too long,\n\t * `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.\n\t * This is for loading adjacent blocks which are not in the DOM tree.\n\t *\n\t * @param e {KeyboardEvent} Keyboard event\n\t * @param scrollable {HTMLElement} Scrollable parent element\n\t */\n\tonKeyDown(e: KeyboardEvent) {\n\t\tconst block = e.target as HTMLElement;\n\t\tif (e.key === \"ArrowDown\") {",
"score": 0.83938068151474
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\treturn this.injectVariables(this.template);\n\t}\n}\n/**\n * Block color rule.\n *\n * Accepts a block color and injects it into the template.\n */\nexport class BlockColorRule extends StyleRule {\n\tprivate blockColor: string;",
"score": 0.8332447409629822
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t} else {\n\t\t\tconst next = findNextBlock(block);\n\t\t\tif (next) this.select(next as HTMLElement);\n\t\t}\n\t}\n\t/**\n\t * Select previous block or scroll to see the block's top.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */",
"score": 0.820749044418335
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "import { MarkdownPostProcessorContext, Platform } from \"obsidian\";\nimport ReadingViewEnhancer from \"src/main\";\nimport SelectionHandler from \"./selection-handler\";\nimport { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from \"../constants\";\n/**\n * BlockSelector enables to navigate between blocks and fold/unfold blocks.\n *\n * Block elements are elements that are having block level elements.\n * For example, a paragraph is a block element.\n *",
"score": 0.8129788041114807
},
{
"filename": "src/commands/commands.ts",
"retrieved_chunk": "\t\t\t}\n\t\t});\n\t},\n});\n/**\n * Select top block in the view\n *\n * @param plugin {ReadingViewEnhancer} Plugin instance\n * @returns {RveCommand} Select top block in the view command\n */",
"score": 0.8029059171676636
}
] | typescript | return element.getAttribute(BLOCK_ATTR) === "true"; |
import { Plugin } from "obsidian";
import RveStyles, { BlockColorRule } from "./styles";
import { RveSettingTab, RveSettings, DEFAULT_SETTINGS } from "./settings";
import Commands from "./commands";
import BlockSelector from "./block-selector";
export default class ReadingViewEnhancer extends Plugin {
settings: RveSettings;
styles: RveStyles;
blockSelector: BlockSelector;
/**
* On load,
*
* - Load settings & styles
* - Activate block selector
* - It actually do its work if settings.enableBlockSelector is true
* - Register all commands
* - Add settings tab
*/
async onload() {
// Settings & Styles
await this.loadSettings();
this.styles = new RveStyles();
this.app.workspace.onLayoutReady(() => this.applySettingsToStyles());
// Activate block selector.
this.blockSelector = new BlockSelector(this);
this.blockSelector.activate();
// Register commands
new Commands(this).register();
// Add settings tab at last
this.addSettingTab(new RveSettingTab(this));
// Leave a message in the console
console.log("Loaded 'Reading View Enhancer'");
}
/**
* On unload,
*
* - Remove all styles
*/
async onunload() {
this.styles.cleanup();
// Leave a message in the console
console.log("Unloaded 'Reading View Enhancer'");
}
// ===================================================================
/**
* Load settings
*/
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
/**
* Save settings
*/
async saveSettings() {
await this.saveData(this.settings);
}
/**
* Apply settings to styles
*
* - Apply block color
* - Apply always on collapse indicator
* - Apply prevent table overflowing
* - Apply scrollable code
*/
private applySettingsToStyles() {
this.applyBlockColor();
this.applyAlwaysOnCollapse();
this.applyPreventTableOverflowing();
this.applyScrollableCode();
this.styles.apply();
}
/**
* Apply block color
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyBlockColor(isImmediate = false) {
| const blockColor = this.styles.of("block-color") as BlockColorRule; |
blockColor.set(this.settings.blockColor);
if (isImmediate) this.styles.apply();
}
/**
* Apply always on collapse indicator
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyAlwaysOnCollapse(isImmediate = false) {
this.styles.of("collapse-indicator").isActive =
this.settings.alwaysOnCollapseIndicator;
if (isImmediate) this.styles.apply();
}
/**
* Apply prevent table overflowing
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyPreventTableOverflowing(isImmediate = false) {
this.styles.of("prevent-table-overflowing").isActive =
this.settings.preventTableOverflowing;
if (isImmediate) this.styles.apply();
}
/**
* Apply scrollable code
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyScrollableCode(isImmediate = false) {
this.styles.of("scrollable-code").isActive = this.settings.scrollableCode;
if (isImmediate) this.styles.apply();
}
}
| src/main.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set the block color\n\t *\n\t * @param blockColor {string} The block color\n\t */\n\tset(blockColor: string) {\n\t\tthis.blockColor = blockColor;\n\t}\n}",
"score": 0.8445927500724792
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\tcleanup() {\n\t\tthis.styleTag.remove();\n\t}\n\t/**\n\t * Get a rule by key\n\t *\n\t * @param rule {RuleKey} rule's key\n\t * @returns {StyleRule} One of the rules\n\t */\n\tof(rule: RuleKey) {",
"score": 0.8227561712265015
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t\t\tthis.plugin.applyBlockColor(true);\n\t\t});\n\t\tthis.addButton((button) => this.accentColorButton(button, color));\n\t}\n\t/**\n\t * Creates a button to use current accent color.\n\t * Used in {@link colorPicker}.\n\t *\n\t * @param button {ButtonComponent} Button component\n\t * @param color {ColorComponent} Color component",
"score": 0.8219915628433228
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\tthis.template = template;\n\t\tthis.isActive = false;\n\t\tthis.injectVariables = injectVariables;\n\t}\n\t/**\n\t * Get the rule after injecting variables\n\t *\n\t * @returns {string} The rule\n\t */\n\tgetRule() {",
"score": 0.8108840584754944
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Activate BlockSelector\n\t */\n\tactivate() {\n\t\tthis.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));\n\t}\n\t/**\n\t * Select top block in the view\n\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */",
"score": 0.8022534847259521
}
] | typescript | const blockColor = this.styles.of("block-color") as BlockColorRule; |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: | BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.9255027770996094
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.8149334788322449
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.8147940039634705
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8089350461959839
},
{
"filename": "src/types.ts",
"retrieved_chunk": " workspace: Workspace,\n meta: GitSavedWorkspaceMeta,\n requests: GitSavedRequest[],\n environments: Environment[],\n apiSpec?: ApiSpec,\n unitTestSuites: GitSavedUnitTestSuite[],\n}\nexport type GitSavedUnitTestSuite = {\n testSuite: UnittestSuite,\n tests: UnitTest[],",
"score": 0.7674410343170166
}
] | typescript | BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb | : BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.9231337904930115
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.813454270362854
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8040127158164978
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.8019840717315674
},
{
"filename": "src/types.ts",
"retrieved_chunk": " workspace: Workspace,\n meta: GitSavedWorkspaceMeta,\n requests: GitSavedRequest[],\n environments: Environment[],\n apiSpec?: ApiSpec,\n unitTestSuites: GitSavedUnitTestSuite[],\n}\nexport type GitSavedUnitTestSuite = {\n testSuite: UnittestSuite,\n tests: UnitTest[],",
"score": 0.7578133344650269
}
] | typescript | : BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { BLOCK_ATTR, IS_COLLAPSED, MARKDOWN_PREVIEW_VIEW } from "../constants";
export const isBottomInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.bottom <= window.innerHeight;
};
export const scrollBottomIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.bottom - scrollable.clientHeight + 200,
});
};
export const isTopInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.top >= 0;
};
export const scrollTopIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.top - 200,
});
};
/**
* Find next block element to select.
* Return null if there is no next block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Next block element
*/
export const findNextBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
let nextBlock = null;
// Start by checking if there's a block element inside the current element
if (!isCollapsed(currentElement)) {
const children = currentElement.children;
for (let i = 0; i < children.length; i++) {
nextBlock = findBlock(children[i] as HTMLElement);
if (nextBlock) return nextBlock;
}
}
// Check next siblings of current element
let nextSibling = currentElement.nextElementSibling;
while (nextSibling) {
nextBlock = findBlock(nextSibling as HTMLElement);
if (nextBlock) return nextBlock;
nextSibling = nextSibling.nextElementSibling;
}
// Check next siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) {
let parentSibling = parent.nextElementSibling;
while (parentSibling) {
nextBlock = findBlock(parentSibling as HTMLElement);
if (nextBlock) return nextBlock;
parentSibling = parentSibling.nextElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Find previous block element to select.
* Return null if there is no previous block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Previous block element
*/
export const findPreviousBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
// Check previous siblings of current element
let prevSibling = currentElement.previousElementSibling;
while (prevSibling) {
const prevBlock = findLastBlock(prevSibling as HTMLElement);
if (prevBlock) return prevBlock;
prevSibling = prevSibling.previousElementSibling;
}
// Check previous siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.classList.contains(MARKDOWN_PREVIEW_VIEW)) {
// Check ancestors of current element first
if (isBlock(parent)) return parent;
let parentSibling = parent.previousElementSibling;
while (parentSibling) {
const prevBlock = findLastBlock(parentSibling as HTMLElement);
if (prevBlock) return prevBlock;
parentSibling = parentSibling.previousElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Check if the given element is collapsed
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is collapsed
*/
const isCollapsed = (element: HTMLElement) => {
| return element.hasClass(IS_COLLAPSED); |
};
/**
* Find first block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} First block element
*/
const findBlock = (element: HTMLElement): HTMLElement | null => {
if (isBlock(element)) {
return element;
}
let block = null;
const childElements = element.children;
for (let i = 0; i < childElements.length; i++) {
block = findBlock(childElements[i] as HTMLElement);
if (block) return block;
}
return null;
};
/**
* Find last block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} Last block element
*/
const findLastBlock = (element: HTMLElement): HTMLElement | null => {
if (isCollapsed(element) && isBlock(element)) return element;
let block = null;
const childElements = element.children;
for (let i = childElements.length - 1; i >= 0; i--) {
block = findLastBlock(childElements[i] as HTMLElement);
if (block) return block;
}
if (isBlock(element)) return element;
else return null;
};
/**
* Check if the given element is a block element
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is a block element
*/
const isBlock = (element: HTMLElement) => {
return element.getAttribute(BLOCK_ATTR) === "true";
};
/**
* Return the scrollable parent element of the given element
*
* @param node {HTMLElement} Element to start searching
* @returns {HTMLElement | null} Scrollable parent element
*/
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
if (node == null) return null;
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode as HTMLElement);
}
};
| src/block-selector/selection-util.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If selected block is too long,\n\t * `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.\n\t * This is for loading adjacent blocks which are not in the DOM tree.\n\t *\n\t * @param e {KeyboardEvent} Keyboard event\n\t * @param scrollable {HTMLElement} Scrollable parent element\n\t */\n\tonKeyDown(e: KeyboardEvent) {\n\t\tconst block = e.target as HTMLElement;\n\t\tif (e.key === \"ArrowDown\") {",
"score": 0.8205075263977051
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t} else {\n\t\t\tconst next = findNextBlock(block);\n\t\t\tif (next) this.select(next as HTMLElement);\n\t\t}\n\t}\n\t/**\n\t * Select previous block or scroll to see the block's top.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */",
"score": 0.7966669201850891
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\treturn this.injectVariables(this.template);\n\t}\n}\n/**\n * Block color rule.\n *\n * Accepts a block color and injects it into the template.\n */\nexport class BlockColorRule extends StyleRule {\n\tprivate blockColor: string;",
"score": 0.794113039970398
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": " * You can select a block by clicking on it and then use arrow keys to navigate between blocks.\n * For selected block, the background color will be changed.\n * You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.\n * Foldable blocks are having `collapse-indicator` or `callout-fold` class.\n */\nexport default class BlockSelector {\n\tplugin: ReadingViewEnhancer;\n\tselectionHandler: SelectionHandler;\n\tselectedBlock: HTMLElement | null;\n\t/**",
"score": 0.7800100445747375
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\t`;\n\t\tsuper(template, (template: string) => template);\n\t}\n}\n/**\n * Scrollable code rule.\n *\n * No variables to inject.\n */\nexport class ScrollableCodeRule extends StyleRule {",
"score": 0.7787933349609375
}
] | typescript | return element.hasClass(IS_COLLAPSED); |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
| if (el.hasClass(FRONTMATTER)) return; |
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 0.8600001335144043
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Trigger 'select' on clicked block element.\n\t *\n\t * @param e {MouseEvent} Mouse event\n\t */\n\tonBlockClick(e: MouseEvent) {\n\t\tconst target = e.target as HTMLElement;\n\t\tconst block = target.closest(`[${BLOCK_ATTR}=true]`);\n\t\tif (block instanceof HTMLElement) {",
"score": 0.8559608459472656
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " * @param element {HTMLElement} Element to search\n * @returns {HTMLElement | null} First block element\n */\nconst findBlock = (element: HTMLElement): HTMLElement | null => {\n\tif (isBlock(element)) {\n\t\treturn element;\n\t}\n\tlet block = null;\n\tconst childElements = element.children;\n\tfor (let i = 0; i < childElements.length; i++) {",
"score": 0.8541020154953003
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * Fold/Unfold block.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tprivate toggleFold(block: HTMLElement) {\n\t\tconst collapseIndicator = block.querySelector(\n\t\t\tCOLLAPSE_INDICATORS.join(\",\")\n\t\t) as HTMLElement;\n\t\tif (collapseIndicator) {\n\t\t\tcollapseIndicator.click();",
"score": 0.8462315797805786
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " * @returns {HTMLElement | null} Next block element\n */\nexport const findNextBlock = (\n\tcurrentElement: HTMLElement\n): HTMLElement | null => {\n\tlet nextBlock = null;\n\t// Start by checking if there's a block element inside the current element\n\tif (!isCollapsed(currentElement)) {\n\t\tconst children = currentElement.children;\n\t\tfor (let i = 0; i < children.length; i++) {",
"score": 0.8109158277511597
}
] | typescript | if (el.hasClass(FRONTMATTER)) return; |
import { BLOCK_ATTR, COLLAPSE_INDICATORS, SELECTED_BLOCK } from "../constants";
import {
findNextBlock,
findPreviousBlock,
isBottomInView,
isTopInView,
scrollBottomIntoView,
scrollTopIntoView,
} from "./selection-util";
/**
* Handle block selection.
* This class is used by BlockSelector.
*/
export default class SelectionHandler {
selectedBlock: HTMLElement | null;
constructor() {
this.selectedBlock = null;
}
/**
* Select block element
*
* @param block {HTMLElement} Block element
*/
select(block: HTMLElement) {
block.focus();
block.addClass(SELECTED_BLOCK);
this.selectedBlock = block;
}
/**
* Unselect block element.
* If there is no selected block, do nothing.
*
* @param block {HTMLElement} Block element
*/
unselect() {
if (this.selectedBlock) {
this.selectedBlock.removeClass(SELECTED_BLOCK);
this.selectedBlock.blur();
this.selectedBlock = null;
}
}
/**
* Trigger 'select' on clicked block element.
*
* @param e {MouseEvent} Mouse event
*/
onBlockClick(e: MouseEvent) {
const target = e.target as HTMLElement;
| const block = target.closest(`[${BLOCK_ATTR}=true]`); |
if (block instanceof HTMLElement) {
this.select(block);
}
}
/**
* On keydown, navigate between blocks or fold/unfold blocks.
*
* - `ArrowDown`: Select next block
* - `ArrowUp`: Select previous block
* - `ArrowLeft` & `ArrowRight`: Fold/Unfold block
*
* If selected block is too long,
* `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.
* This is for loading adjacent blocks which are not in the DOM tree.
*
* @param e {KeyboardEvent} Keyboard event
* @param scrollable {HTMLElement} Scrollable parent element
*/
onKeyDown(e: KeyboardEvent) {
const block = e.target as HTMLElement;
if (e.key === "ArrowDown") {
e.preventDefault();
this.selectNextBlockOrScroll(block);
} else if (e.key === "ArrowUp") {
e.preventDefault();
this.selectPreviousBlockOrScroll(block);
} else if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
e.preventDefault();
this.toggleFold(block);
} else if (e.key === "Escape") {
this.unselect();
}
}
/**
* Select next block or scroll to see the block's bottom.
*
* @param block {HTMLElement} Block element
*/
private selectNextBlockOrScroll(block: HTMLElement) {
if (!isBottomInView(block)) {
scrollBottomIntoView(block);
} else {
const next = findNextBlock(block);
if (next) this.select(next as HTMLElement);
}
}
/**
* Select previous block or scroll to see the block's top.
*
* @param block {HTMLElement} Block element
*/
private selectPreviousBlockOrScroll(block: HTMLElement) {
if (!isTopInView(block)) {
scrollTopIntoView(block);
} else {
const prev = findPreviousBlock(block);
if (prev) this.select(prev as HTMLElement);
}
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
const blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);
// If there is no block, do nothing
if (blocks.length === 0) return;
// Get the index of the topmost block in the view
let topIndex = -1;
for (let i = 0; i < blocks.length; i++) {
topIndex = i;
const rect = blocks[i].getBoundingClientRect();
if (rect.bottom > 120) {
break;
}
}
const topBlock = blocks[topIndex];
this.select(topBlock as HTMLElement);
}
/**
* Fold/Unfold block.
*
* @param block {HTMLElement} Block element
*/
private toggleFold(block: HTMLElement) {
const collapseIndicator = block.querySelector(
COLLAPSE_INDICATORS.join(",")
) as HTMLElement;
if (collapseIndicator) {
collapseIndicator.click();
}
}
}
| src/block-selector/selection-handler.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set `data-rve-block` attribute to block elements.\n\t *\n\t * @param element {HTMLElement} Element to start searching\n\t */\n\tprivate elementsToBlocks(element: HTMLElement) {\n\t\tconst elements = element.querySelectorAll(BLOCKS.join(\", \"));\n\t\telements.forEach((el) => {\n\t\t\tif (el.hasClass(FRONTMATTER)) return;",
"score": 0.8306699991226196
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Initialize container.\n\t * Add some event listeners to container.\n\t *\n\t * @param container {MarkdownPostProcessorContext.containerEl} Container element\n\t */\n\tprivate initializeContainer(container: HTMLElement) {\n\t\t// Mark container as initialized\n\t\tcontainer.addClass(BLOCK_SELECTOR);\n\t\t// On click, select block element\n\t\tcontainer.addEventListener(\"click\", (e) =>",
"score": 0.8262279629707336
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Activate BlockSelector\n\t */\n\tactivate() {\n\t\tthis.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));\n\t}\n\t/**\n\t * Select top block in the view\n\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */",
"score": 0.7985583543777466
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " * @param element {HTMLElement} Element to search\n * @returns {HTMLElement | null} First block element\n */\nconst findBlock = (element: HTMLElement): HTMLElement | null => {\n\tif (isBlock(element)) {\n\t\treturn element;\n\t}\n\tlet block = null;\n\tconst childElements = element.children;\n\tfor (let i = 0; i < childElements.length; i++) {",
"score": 0.771927535533905
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t *\n\t * @param container {MarkdownPostProcessorContext.containerEl} Container element\n\t * @returns {boolean} True if container is initialized\n\t */\n\tprivate isContainerNotInitialized(container: HTMLElement) {\n\t\treturn (\n\t\t\tcontainer instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)\n\t\t);\n\t}\n\t/**",
"score": 0.7693266868591309
}
] | typescript | const block = target.closest(`[${BLOCK_ATTR}=true]`); |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
| container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
); |
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is collapsed\n */\nconst isCollapsed = (element: HTMLElement) => {\n\treturn element.hasClass(IS_COLLAPSED);\n};\n/**\n * Find first block element inside the given element\n *",
"score": 0.8458731770515442
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\telse return null;\n};\n/**\n * Check if the given element is a block element\n *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is a block element\n */\nconst isBlock = (element: HTMLElement) => {\n\treturn element.getAttribute(BLOCK_ATTR) === \"true\";",
"score": 0.8418131470680237
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "};\n/**\n * Return the scrollable parent element of the given element\n *\n * @param node {HTMLElement} Element to start searching\n * @returns {HTMLElement | null} Scrollable parent element\n */\nconst getScrollParent = (node: HTMLElement): HTMLElement | null => {\n\tif (node == null) return null;\n\tif (node.scrollHeight > node.clientHeight) {",
"score": 0.8090150356292725
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " * @returns {HTMLElement | null} Next block element\n */\nexport const findNextBlock = (\n\tcurrentElement: HTMLElement\n): HTMLElement | null => {\n\tlet nextBlock = null;\n\t// Start by checking if there's a block element inside the current element\n\tif (!isCollapsed(currentElement)) {\n\t\tconst children = currentElement.children;\n\t\tfor (let i = 0; i < children.length; i++) {",
"score": 0.8086172342300415
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 0.8067195415496826
}
] | typescript | container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
); |
import { BLOCK_ATTR, IS_COLLAPSED, MARKDOWN_PREVIEW_VIEW } from "../constants";
export const isBottomInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.bottom <= window.innerHeight;
};
export const scrollBottomIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.bottom - scrollable.clientHeight + 200,
});
};
export const isTopInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.top >= 0;
};
export const scrollTopIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.top - 200,
});
};
/**
* Find next block element to select.
* Return null if there is no next block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Next block element
*/
export const findNextBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
let nextBlock = null;
// Start by checking if there's a block element inside the current element
if (!isCollapsed(currentElement)) {
const children = currentElement.children;
for (let i = 0; i < children.length; i++) {
nextBlock = findBlock(children[i] as HTMLElement);
if (nextBlock) return nextBlock;
}
}
// Check next siblings of current element
let nextSibling = currentElement.nextElementSibling;
while (nextSibling) {
nextBlock = findBlock(nextSibling as HTMLElement);
if (nextBlock) return nextBlock;
nextSibling = nextSibling.nextElementSibling;
}
// Check next siblings of parent block element
let parent = currentElement.parentElement;
while (parent && | !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) { |
let parentSibling = parent.nextElementSibling;
while (parentSibling) {
nextBlock = findBlock(parentSibling as HTMLElement);
if (nextBlock) return nextBlock;
parentSibling = parentSibling.nextElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Find previous block element to select.
* Return null if there is no previous block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Previous block element
*/
export const findPreviousBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
// Check previous siblings of current element
let prevSibling = currentElement.previousElementSibling;
while (prevSibling) {
const prevBlock = findLastBlock(prevSibling as HTMLElement);
if (prevBlock) return prevBlock;
prevSibling = prevSibling.previousElementSibling;
}
// Check previous siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.classList.contains(MARKDOWN_PREVIEW_VIEW)) {
// Check ancestors of current element first
if (isBlock(parent)) return parent;
let parentSibling = parent.previousElementSibling;
while (parentSibling) {
const prevBlock = findLastBlock(parentSibling as HTMLElement);
if (prevBlock) return prevBlock;
parentSibling = parentSibling.previousElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Check if the given element is collapsed
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is collapsed
*/
const isCollapsed = (element: HTMLElement) => {
return element.hasClass(IS_COLLAPSED);
};
/**
* Find first block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} First block element
*/
const findBlock = (element: HTMLElement): HTMLElement | null => {
if (isBlock(element)) {
return element;
}
let block = null;
const childElements = element.children;
for (let i = 0; i < childElements.length; i++) {
block = findBlock(childElements[i] as HTMLElement);
if (block) return block;
}
return null;
};
/**
* Find last block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} Last block element
*/
const findLastBlock = (element: HTMLElement): HTMLElement | null => {
if (isCollapsed(element) && isBlock(element)) return element;
let block = null;
const childElements = element.children;
for (let i = childElements.length - 1; i >= 0; i--) {
block = findLastBlock(childElements[i] as HTMLElement);
if (block) return block;
}
if (isBlock(element)) return element;
else return null;
};
/**
* Check if the given element is a block element
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is a block element
*/
const isBlock = (element: HTMLElement) => {
return element.getAttribute(BLOCK_ATTR) === "true";
};
/**
* Return the scrollable parent element of the given element
*
* @param node {HTMLElement} Element to start searching
* @returns {HTMLElement | null} Scrollable parent element
*/
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
if (node == null) return null;
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode as HTMLElement);
}
};
| src/block-selector/selection-util.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\tprivate selectPreviousBlockOrScroll(block: HTMLElement) {\n\t\tif (!isTopInView(block)) {\n\t\t\tscrollTopIntoView(block);\n\t\t} else {\n\t\t\tconst prev = findPreviousBlock(block);\n\t\t\tif (prev) this.select(prev as HTMLElement);\n\t\t}\n\t}\n\t/**\n\t * Select top block in the view",
"score": 0.7542628049850464
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t\ttopIndex = i;\n\t\t\tconst rect = blocks[i].getBoundingClientRect();\n\t\t\tif (rect.bottom > 120) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tconst topBlock = blocks[topIndex];\n\t\tthis.select(topBlock as HTMLElement);\n\t}\n\t/**",
"score": 0.7048828601837158
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 0.6967706084251404
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set `data-rve-block` attribute to block elements.\n\t *\n\t * @param element {HTMLElement} Element to start searching\n\t */\n\tprivate elementsToBlocks(element: HTMLElement) {\n\t\tconst elements = element.querySelectorAll(BLOCKS.join(\", \"));\n\t\telements.forEach((el) => {\n\t\t\tif (el.hasClass(FRONTMATTER)) return;",
"score": 0.6919783353805542
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tselect(block: HTMLElement) {\n\t\tblock.focus();\n\t\tblock.addClass(SELECTED_BLOCK);\n\t\tthis.selectedBlock = block;\n\t}\n\t/**\n\t * Unselect block element.",
"score": 0.6906176805496216
}
] | typescript | !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) { |
import { PluginSettingTab } from "obsidian";
import ReadingViewEnhancer from "../main";
import BlockSelectorSettings from "./block";
import MiscellaneousSettings from "./miscellaneous";
export interface RveSettings {
blockColor: string;
enableBlockSelector: boolean;
disableBlockSelectorOnMobile: boolean;
alwaysOnCollapseIndicator: boolean;
preventTableOverflowing: boolean;
scrollableCode: boolean;
}
export const DEFAULT_SETTINGS: RveSettings = {
blockColor: "#8b6cef", // Obsidian default color
enableBlockSelector: false,
disableBlockSelectorOnMobile: false,
alwaysOnCollapseIndicator: false,
preventTableOverflowing: false,
scrollableCode: false,
};
// ===================================================================
/**
* Settings tab.
* In this tab, you can change settings.
*
* - Block color
* - Enable/Disable Block Selector
*/
export class RveSettingTab extends PluginSettingTab {
plugin: ReadingViewEnhancer;
constructor(plugin: ReadingViewEnhancer) {
super(app, plugin);
this.plugin = plugin;
}
/**
* Displays settings tab.
*/
display() {
const { containerEl } = this;
// Clear all first
containerEl.empty();
// Add header
containerEl.createEl("h1", { text: "Reading View Enhancer" });
// Add block selector settings
new BlockSelectorSettings(containerEl, this.plugin);
// Add miscellaneous settings
| new MiscellaneousSettings(containerEl, this.plugin); |
}
}
| src/settings/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Activate BlockSelector\n\t */\n\tactivate() {\n\t\tthis.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));\n\t}\n\t/**\n\t * Select top block in the view\n\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */",
"score": 0.7721670269966125
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Initialize container.\n\t * Add some event listeners to container.\n\t *\n\t * @param container {MarkdownPostProcessorContext.containerEl} Container element\n\t */\n\tprivate initializeContainer(container: HTMLElement) {\n\t\t// Mark container as initialized\n\t\tcontainer.addClass(BLOCK_SELECTOR);\n\t\t// On click, select block element\n\t\tcontainer.addEventListener(\"click\", (e) =>",
"score": 0.7671692371368408
},
{
"filename": "src/settings/block/block-selector-mobile.ts",
"retrieved_chunk": "import { Setting, ToggleComponent } from \"obsidian\";\nimport ReadingViewEnhancer from \"src/main\";\n/**\n * Disable block selector on mobile setting component\n */\nexport default class DisableBlockSelectorOnMobileSetting extends Setting {\n\tplugin: ReadingViewEnhancer;\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tsuper(containerEl);\n\t\tthis.plugin = plugin;",
"score": 0.7615214586257935
},
{
"filename": "src/settings/block/index.ts",
"retrieved_chunk": "import ReadingViewEnhancer from \"src/main\";\nimport BlockColorSetting from \"./block-color\";\nimport EnableBlockSelectorSetting from \"./block-selector\";\nimport DisableBlockSelectorOnMobileSetting from \"./block-selector-mobile\";\n/**\n * Registers settings components related to block selector.\n */\nexport default class BlockSelectorSettings {\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tcontainerEl.createEl(\"h2\", { text: \"Block Selector\" });",
"score": 0.7613430619239807
},
{
"filename": "src/settings/miscellaneous/index.ts",
"retrieved_chunk": "import ReadingViewEnhancer from \"src/main\";\nimport AlwaysOnCollapseIndicatorSetting from \"./always-on-collapse-indicator\";\nimport PreventTableOverflowingSetting from \"./prevent-table-overflow\";\nimport ScrollableCodeSetting from \"./scrollable-code\";\n/**\n * Registers settings components not related to block.\n */\nexport default class MiscellaneousSettings {\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tcontainerEl.createEl(\"h2\", { text: \"Miscellaneous\" });",
"score": 0.7603276371955872
}
] | typescript | new MiscellaneousSettings(containerEl, this.plugin); |
import { PluginSettingTab } from "obsidian";
import ReadingViewEnhancer from "../main";
import BlockSelectorSettings from "./block";
import MiscellaneousSettings from "./miscellaneous";
export interface RveSettings {
blockColor: string;
enableBlockSelector: boolean;
disableBlockSelectorOnMobile: boolean;
alwaysOnCollapseIndicator: boolean;
preventTableOverflowing: boolean;
scrollableCode: boolean;
}
export const DEFAULT_SETTINGS: RveSettings = {
blockColor: "#8b6cef", // Obsidian default color
enableBlockSelector: false,
disableBlockSelectorOnMobile: false,
alwaysOnCollapseIndicator: false,
preventTableOverflowing: false,
scrollableCode: false,
};
// ===================================================================
/**
* Settings tab.
* In this tab, you can change settings.
*
* - Block color
* - Enable/Disable Block Selector
*/
export class RveSettingTab extends PluginSettingTab {
plugin: ReadingViewEnhancer;
constructor(plugin: ReadingViewEnhancer) {
super(app, plugin);
this.plugin = plugin;
}
/**
* Displays settings tab.
*/
display() {
const { containerEl } = this;
// Clear all first
containerEl.empty();
// Add header
containerEl.createEl("h1", { text: "Reading View Enhancer" });
// Add block selector settings
new | BlockSelectorSettings(containerEl, this.plugin); |
// Add miscellaneous settings
new MiscellaneousSettings(containerEl, this.plugin);
}
}
| src/settings/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Activate BlockSelector\n\t */\n\tactivate() {\n\t\tthis.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));\n\t}\n\t/**\n\t * Select top block in the view\n\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */",
"score": 0.780280590057373
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Initialize container.\n\t * Add some event listeners to container.\n\t *\n\t * @param container {MarkdownPostProcessorContext.containerEl} Container element\n\t */\n\tprivate initializeContainer(container: HTMLElement) {\n\t\t// Mark container as initialized\n\t\tcontainer.addClass(BLOCK_SELECTOR);\n\t\t// On click, select block element\n\t\tcontainer.addEventListener(\"click\", (e) =>",
"score": 0.7774072885513306
},
{
"filename": "src/settings/block/index.ts",
"retrieved_chunk": "import ReadingViewEnhancer from \"src/main\";\nimport BlockColorSetting from \"./block-color\";\nimport EnableBlockSelectorSetting from \"./block-selector\";\nimport DisableBlockSelectorOnMobileSetting from \"./block-selector-mobile\";\n/**\n * Registers settings components related to block selector.\n */\nexport default class BlockSelectorSettings {\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tcontainerEl.createEl(\"h2\", { text: \"Block Selector\" });",
"score": 0.7608898878097534
},
{
"filename": "src/settings/block/block-selector.ts",
"retrieved_chunk": "import { Setting, ToggleComponent } from \"obsidian\";\nimport ReadingViewEnhancer from \"src/main\";\n/**\n * Enable block selector setting component\n */\nexport default class EnableBlockSelectorSetting extends Setting {\n\tplugin: ReadingViewEnhancer;\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tsuper(containerEl);\n\t\tthis.plugin = plugin;",
"score": 0.7568373680114746
},
{
"filename": "src/settings/block/block-selector-mobile.ts",
"retrieved_chunk": "import { Setting, ToggleComponent } from \"obsidian\";\nimport ReadingViewEnhancer from \"src/main\";\n/**\n * Disable block selector on mobile setting component\n */\nexport default class DisableBlockSelectorOnMobileSetting extends Setting {\n\tplugin: ReadingViewEnhancer;\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tsuper(containerEl);\n\t\tthis.plugin = plugin;",
"score": 0.7548408508300781
}
] | typescript | BlockSelectorSettings(containerEl, this.plugin); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb | : BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 0.8246344327926636
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 0.8043856024742126
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.7894301414489746
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 0.7714557647705078
},
{
"filename": "src/db/BaseDb.ts",
"retrieved_chunk": "import Nedb from 'nedb';\nimport fsPath from 'node:path';\nimport { BaseModel } from '../insomniaDbTypes';\ntype DbTargets = 'Request' | 'RequestMeta' | 'RequestGroup' | 'RequestGroupMeta' | 'Workspace' | 'WorkspaceMeta' | 'Project' | 'Environment' | 'ApiSpec' | 'UnitTest' | 'UnitTestSuite';\nexport default class BaseDb<T extends BaseModel> {\n private neDb: Nedb;\n constructor(target: DbTargets) {\n // @ts-ignore\n const filename = fsPath.join(window.app.getPath('userData'), `insomnia.${target}.db`);\n this.neDb = new Nedb({",
"score": 0.7455604076385498
}
] | typescript | : BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
import { SELECTED_BLOCK } from "./constants";
/**
* Style rule that holds the template
* and the function to inject variables
*/
class StyleRule {
private template: string;
private injectVariables: (template: string) => string;
isActive: boolean;
constructor(template: string, injectVariables: (template: string) => string) {
this.template = template;
this.isActive = false;
this.injectVariables = injectVariables;
}
/**
* Get the rule after injecting variables
*
* @returns {string} The rule
*/
getRule() {
return this.injectVariables(this.template);
}
}
/**
* Block color rule.
*
* Accepts a block color and injects it into the template.
*/
export class BlockColorRule extends StyleRule {
private blockColor: string;
constructor() {
const template = `
| .${SELECTED_BLOCK} { |
position: relative;
}
.${SELECTED_BLOCK}::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
background-color: {{BLOCK_COLOR}}1a;
}
`;
super(template, (template: string) => {
return template.replace("{{BLOCK_COLOR}}", this.blockColor);
});
this.isActive = true;
}
/**
* Set the block color
*
* @param blockColor {string} The block color
*/
set(blockColor: string) {
this.blockColor = blockColor;
}
}
/**
* Collapse indicator rule.
*
* No variables to inject.
*/
export class CollapseIndicatorRule extends StyleRule {
constructor() {
const template = `
.markdown-preview-section .collapse-indicator {
opacity: 1;
}
`;
super(template, (template: string) => template);
}
}
/**
* Prevent table overflowing rule.
*
* No variables to inject.
*/
export class PreventTableOverflowingRule extends StyleRule {
constructor() {
const template = `
.markdown-preview-section > div:has(table) {
overflow: auto;
}
.markdown-preview-section thead > tr > th,
.markdown-preview-section tbody > tr > td {
white-space: nowrap;
}
`;
super(template, (template: string) => template);
}
}
/**
* Scrollable code rule.
*
* No variables to inject.
*/
export class ScrollableCodeRule extends StyleRule {
constructor() {
const template = `
.markdown-preview-section div > pre {
overflow: hidden;
white-space: pre-wrap;
}
.markdown-preview-section div > pre > code {
display: block;
overflow: auto;
white-space: pre;
}
`;
super(template, (template: string) => template);
}
}
type RuleKey =
| "block-color"
| "collapse-indicator"
| "prevent-table-overflowing"
| "scrollable-code";
/**
* The class that manages all style rules.
*/
export default class RveStyles {
styleTag: HTMLStyleElement;
rules: Record<RuleKey, StyleRule>;
constructor() {
this.styleTag = document.createElement("style");
this.styleTag.id = "rve-styles";
document.getElementsByTagName("head")[0].appendChild(this.styleTag);
this.rules = {
"block-color": new BlockColorRule(),
"collapse-indicator": new CollapseIndicatorRule(),
"prevent-table-overflowing": new PreventTableOverflowingRule(),
"scrollable-code": new ScrollableCodeRule(),
};
}
/**
* Clean up the style tag
*/
cleanup() {
this.styleTag.remove();
}
/**
* Get a rule by key
*
* @param rule {RuleKey} rule's key
* @returns {StyleRule} One of the rules
*/
of(rule: RuleKey) {
return this.rules[rule];
}
/**
* Apply all active rules
*/
apply() {
const style = Object.values(this.rules)
.filter((rule) => rule.isActive)
.map((rule) => rule.getRule())
.join("\n");
this.styleTag.innerHTML = style;
}
}
| src/styles.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": " * Handle block selection.\n * This class is used by BlockSelector.\n */\nexport default class SelectionHandler {\n\tselectedBlock: HTMLElement | null;\n\tconstructor() {\n\t\tthis.selectedBlock = null;\n\t}\n\t/**\n\t * Select block element",
"score": 0.8354170918464661
},
{
"filename": "src/settings/index.ts",
"retrieved_chunk": "// ===================================================================\n/**\n * Settings tab.\n * In this tab, you can change settings.\n *\n * - Block color\n * - Enable/Disable Block Selector\n */\nexport class RveSettingTab extends PluginSettingTab {\n\tplugin: ReadingViewEnhancer;",
"score": 0.831544816493988
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": " * You can select a block by clicking on it and then use arrow keys to navigate between blocks.\n * For selected block, the background color will be changed.\n * You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.\n * Foldable blocks are having `collapse-indicator` or `callout-fold` class.\n */\nexport default class BlockSelector {\n\tplugin: ReadingViewEnhancer;\n\tselectionHandler: SelectionHandler;\n\tselectedBlock: HTMLElement | null;\n\t/**",
"score": 0.8230149745941162
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\telse return null;\n};\n/**\n * Check if the given element is a block element\n *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is a block element\n */\nconst isBlock = (element: HTMLElement) => {\n\treturn element.getAttribute(BLOCK_ATTR) === \"true\";",
"score": 0.8033449649810791
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "import { MarkdownPostProcessorContext, Platform } from \"obsidian\";\nimport ReadingViewEnhancer from \"src/main\";\nimport SelectionHandler from \"./selection-handler\";\nimport { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from \"../constants\";\n/**\n * BlockSelector enables to navigate between blocks and fold/unfold blocks.\n *\n * Block elements are elements that are having block level elements.\n * For example, a paragraph is a block element.\n *",
"score": 0.7911113500595093
}
] | typescript | .${SELECTED_BLOCK} { |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
| this.selectionHandler.selectTopBlockInTheView(viewContainer); |
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tselect(block: HTMLElement) {\n\t\tblock.focus();\n\t\tblock.addClass(SELECTED_BLOCK);\n\t\tthis.selectedBlock = block;\n\t}\n\t/**\n\t * Unselect block element.",
"score": 0.8240430355072021
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\tprivate selectPreviousBlockOrScroll(block: HTMLElement) {\n\t\tif (!isTopInView(block)) {\n\t\t\tscrollTopIntoView(block);\n\t\t} else {\n\t\t\tconst prev = findPreviousBlock(block);\n\t\t\tif (prev) this.select(prev as HTMLElement);\n\t\t}\n\t}\n\t/**\n\t * Select top block in the view",
"score": 0.8213056325912476
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t}\n\t}\n\t/**\n\t * Select next block or scroll to see the block's bottom.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tprivate selectNextBlockOrScroll(block: HTMLElement) {\n\t\tif (!isBottomInView(block)) {\n\t\t\tscrollBottomIntoView(block);",
"score": 0.7973065376281738
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Trigger 'select' on clicked block element.\n\t *\n\t * @param e {MouseEvent} Mouse event\n\t */\n\tonBlockClick(e: MouseEvent) {\n\t\tconst target = e.target as HTMLElement;\n\t\tconst block = target.closest(`[${BLOCK_ATTR}=true]`);\n\t\tif (block instanceof HTMLElement) {",
"score": 0.774165153503418
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If there is no selected block, do nothing.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tunselect() {\n\t\tif (this.selectedBlock) {\n\t\t\tthis.selectedBlock.removeClass(SELECTED_BLOCK);\n\t\t\tthis.selectedBlock.blur();\n\t\t\tthis.selectedBlock = null;\n\t\t}",
"score": 0.7733340263366699
}
] | typescript | this.selectionHandler.selectTopBlockInTheView(viewContainer); |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if ( | el.hasClass(FRONTMATTER)) return; |
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 0.8703888654708862
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " * @param element {HTMLElement} Element to search\n * @returns {HTMLElement | null} First block element\n */\nconst findBlock = (element: HTMLElement): HTMLElement | null => {\n\tif (isBlock(element)) {\n\t\treturn element;\n\t}\n\tlet block = null;\n\tconst childElements = element.children;\n\tfor (let i = 0; i < childElements.length; i++) {",
"score": 0.8602898716926575
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * Fold/Unfold block.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tprivate toggleFold(block: HTMLElement) {\n\t\tconst collapseIndicator = block.querySelector(\n\t\t\tCOLLAPSE_INDICATORS.join(\",\")\n\t\t) as HTMLElement;\n\t\tif (collapseIndicator) {\n\t\t\tcollapseIndicator.click();",
"score": 0.8509796857833862
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Trigger 'select' on clicked block element.\n\t *\n\t * @param e {MouseEvent} Mouse event\n\t */\n\tonBlockClick(e: MouseEvent) {\n\t\tconst target = e.target as HTMLElement;\n\t\tconst block = target.closest(`[${BLOCK_ATTR}=true]`);\n\t\tif (block instanceof HTMLElement) {",
"score": 0.8436861038208008
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " * @returns {HTMLElement | null} Next block element\n */\nexport const findNextBlock = (\n\tcurrentElement: HTMLElement\n): HTMLElement | null => {\n\tlet nextBlock = null;\n\t// Start by checking if there's a block element inside the current element\n\tif (!isCollapsed(currentElement)) {\n\t\tconst children = currentElement.children;\n\t\tfor (let i = 0; i < children.length; i++) {",
"score": 0.8273884654045105
}
] | typescript | el.hasClass(FRONTMATTER)) return; |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
| const elements = element.querySelectorAll(BLOCKS.join(", ")); |
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Trigger 'select' on clicked block element.\n\t *\n\t * @param e {MouseEvent} Mouse event\n\t */\n\tonBlockClick(e: MouseEvent) {\n\t\tconst target = e.target as HTMLElement;\n\t\tconst block = target.closest(`[${BLOCK_ATTR}=true]`);\n\t\tif (block instanceof HTMLElement) {",
"score": 0.8581581115722656
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t} else {\n\t\t\tconst next = findNextBlock(block);\n\t\t\tif (next) this.select(next as HTMLElement);\n\t\t}\n\t}\n\t/**\n\t * Select previous block or scroll to see the block's top.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */",
"score": 0.8528727293014526
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " * @param element {HTMLElement} Element to search\n * @returns {HTMLElement | null} First block element\n */\nconst findBlock = (element: HTMLElement): HTMLElement | null => {\n\tif (isBlock(element)) {\n\t\treturn element;\n\t}\n\tlet block = null;\n\tconst childElements = element.children;\n\tfor (let i = 0; i < childElements.length; i++) {",
"score": 0.8351002931594849
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tselect(block: HTMLElement) {\n\t\tblock.focus();\n\t\tblock.addClass(SELECTED_BLOCK);\n\t\tthis.selectedBlock = block;\n\t}\n\t/**\n\t * Unselect block element.",
"score": 0.8168134689331055
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 0.8159675598144531
}
] | typescript | const elements = element.querySelectorAll(BLOCKS.join(", ")); |
import { BLOCK_ATTR, IS_COLLAPSED, MARKDOWN_PREVIEW_VIEW } from "../constants";
export const isBottomInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.bottom <= window.innerHeight;
};
export const scrollBottomIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.bottom - scrollable.clientHeight + 200,
});
};
export const isTopInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.top >= 0;
};
export const scrollTopIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.top - 200,
});
};
/**
* Find next block element to select.
* Return null if there is no next block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Next block element
*/
export const findNextBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
let nextBlock = null;
// Start by checking if there's a block element inside the current element
if (!isCollapsed(currentElement)) {
const children = currentElement.children;
for (let i = 0; i < children.length; i++) {
nextBlock = findBlock(children[i] as HTMLElement);
if (nextBlock) return nextBlock;
}
}
// Check next siblings of current element
let nextSibling = currentElement.nextElementSibling;
while (nextSibling) {
nextBlock = findBlock(nextSibling as HTMLElement);
if (nextBlock) return nextBlock;
nextSibling = nextSibling.nextElementSibling;
}
// Check next siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) {
let parentSibling = parent.nextElementSibling;
while (parentSibling) {
nextBlock = findBlock(parentSibling as HTMLElement);
if (nextBlock) return nextBlock;
parentSibling = parentSibling.nextElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Find previous block element to select.
* Return null if there is no previous block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Previous block element
*/
export const findPreviousBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
// Check previous siblings of current element
let prevSibling = currentElement.previousElementSibling;
while (prevSibling) {
const prevBlock = findLastBlock(prevSibling as HTMLElement);
if (prevBlock) return prevBlock;
prevSibling = prevSibling.previousElementSibling;
}
// Check previous siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.classList.contains(MARKDOWN_PREVIEW_VIEW)) {
// Check ancestors of current element first
if (isBlock(parent)) return parent;
let parentSibling = parent.previousElementSibling;
while (parentSibling) {
const prevBlock = findLastBlock(parentSibling as HTMLElement);
if (prevBlock) return prevBlock;
parentSibling = parentSibling.previousElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Check if the given element is collapsed
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is collapsed
*/
const isCollapsed = (element: HTMLElement) => {
return | element.hasClass(IS_COLLAPSED); |
};
/**
* Find first block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} First block element
*/
const findBlock = (element: HTMLElement): HTMLElement | null => {
if (isBlock(element)) {
return element;
}
let block = null;
const childElements = element.children;
for (let i = 0; i < childElements.length; i++) {
block = findBlock(childElements[i] as HTMLElement);
if (block) return block;
}
return null;
};
/**
* Find last block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} Last block element
*/
const findLastBlock = (element: HTMLElement): HTMLElement | null => {
if (isCollapsed(element) && isBlock(element)) return element;
let block = null;
const childElements = element.children;
for (let i = childElements.length - 1; i >= 0; i--) {
block = findLastBlock(childElements[i] as HTMLElement);
if (block) return block;
}
if (isBlock(element)) return element;
else return null;
};
/**
* Check if the given element is a block element
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is a block element
*/
const isBlock = (element: HTMLElement) => {
return element.getAttribute(BLOCK_ATTR) === "true";
};
/**
* Return the scrollable parent element of the given element
*
* @param node {HTMLElement} Element to start searching
* @returns {HTMLElement | null} Scrollable parent element
*/
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
if (node == null) return null;
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode as HTMLElement);
}
};
| src/block-selector/selection-util.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If selected block is too long,\n\t * `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.\n\t * This is for loading adjacent blocks which are not in the DOM tree.\n\t *\n\t * @param e {KeyboardEvent} Keyboard event\n\t * @param scrollable {HTMLElement} Scrollable parent element\n\t */\n\tonKeyDown(e: KeyboardEvent) {\n\t\tconst block = e.target as HTMLElement;\n\t\tif (e.key === \"ArrowDown\") {",
"score": 0.8337104320526123
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": " * You can select a block by clicking on it and then use arrow keys to navigate between blocks.\n * For selected block, the background color will be changed.\n * You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.\n * Foldable blocks are having `collapse-indicator` or `callout-fold` class.\n */\nexport default class BlockSelector {\n\tplugin: ReadingViewEnhancer;\n\tselectionHandler: SelectionHandler;\n\tselectedBlock: HTMLElement | null;\n\t/**",
"score": 0.7913656234741211
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\treturn this.injectVariables(this.template);\n\t}\n}\n/**\n * Block color rule.\n *\n * Accepts a block color and injects it into the template.\n */\nexport class BlockColorRule extends StyleRule {\n\tprivate blockColor: string;",
"score": 0.7878953814506531
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t * On load,\n\t *\n\t * - Load settings & styles\n\t * - Activate block selector\n\t * - It actually do its work if settings.enableBlockSelector is true\n\t * - Register all commands\n\t * - Add settings tab\n\t */\n\tasync onload() {\n\t\t// Settings & Styles",
"score": 0.7795947790145874
},
{
"filename": "src/settings/index.ts",
"retrieved_chunk": "// ===================================================================\n/**\n * Settings tab.\n * In this tab, you can change settings.\n *\n * - Block color\n * - Enable/Disable Block Selector\n */\nexport class RveSettingTab extends PluginSettingTab {\n\tplugin: ReadingViewEnhancer;",
"score": 0.7751888036727905
}
] | typescript | element.hasClass(IS_COLLAPSED); |
import { BLOCK_ATTR, IS_COLLAPSED, MARKDOWN_PREVIEW_VIEW } from "../constants";
export const isBottomInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.bottom <= window.innerHeight;
};
export const scrollBottomIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.bottom - scrollable.clientHeight + 200,
});
};
export const isTopInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.top >= 0;
};
export const scrollTopIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.top - 200,
});
};
/**
* Find next block element to select.
* Return null if there is no next block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Next block element
*/
export const findNextBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
let nextBlock = null;
// Start by checking if there's a block element inside the current element
if (!isCollapsed(currentElement)) {
const children = currentElement.children;
for (let i = 0; i < children.length; i++) {
nextBlock = findBlock(children[i] as HTMLElement);
if (nextBlock) return nextBlock;
}
}
// Check next siblings of current element
let nextSibling = currentElement.nextElementSibling;
while (nextSibling) {
nextBlock = findBlock(nextSibling as HTMLElement);
if (nextBlock) return nextBlock;
nextSibling = nextSibling.nextElementSibling;
}
// Check next siblings of parent block element
let parent = currentElement.parentElement;
| while (parent && !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) { |
let parentSibling = parent.nextElementSibling;
while (parentSibling) {
nextBlock = findBlock(parentSibling as HTMLElement);
if (nextBlock) return nextBlock;
parentSibling = parentSibling.nextElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Find previous block element to select.
* Return null if there is no previous block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Previous block element
*/
export const findPreviousBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
// Check previous siblings of current element
let prevSibling = currentElement.previousElementSibling;
while (prevSibling) {
const prevBlock = findLastBlock(prevSibling as HTMLElement);
if (prevBlock) return prevBlock;
prevSibling = prevSibling.previousElementSibling;
}
// Check previous siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.classList.contains(MARKDOWN_PREVIEW_VIEW)) {
// Check ancestors of current element first
if (isBlock(parent)) return parent;
let parentSibling = parent.previousElementSibling;
while (parentSibling) {
const prevBlock = findLastBlock(parentSibling as HTMLElement);
if (prevBlock) return prevBlock;
parentSibling = parentSibling.previousElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Check if the given element is collapsed
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is collapsed
*/
const isCollapsed = (element: HTMLElement) => {
return element.hasClass(IS_COLLAPSED);
};
/**
* Find first block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} First block element
*/
const findBlock = (element: HTMLElement): HTMLElement | null => {
if (isBlock(element)) {
return element;
}
let block = null;
const childElements = element.children;
for (let i = 0; i < childElements.length; i++) {
block = findBlock(childElements[i] as HTMLElement);
if (block) return block;
}
return null;
};
/**
* Find last block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} Last block element
*/
const findLastBlock = (element: HTMLElement): HTMLElement | null => {
if (isCollapsed(element) && isBlock(element)) return element;
let block = null;
const childElements = element.children;
for (let i = childElements.length - 1; i >= 0; i--) {
block = findLastBlock(childElements[i] as HTMLElement);
if (block) return block;
}
if (isBlock(element)) return element;
else return null;
};
/**
* Check if the given element is a block element
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is a block element
*/
const isBlock = (element: HTMLElement) => {
return element.getAttribute(BLOCK_ATTR) === "true";
};
/**
* Return the scrollable parent element of the given element
*
* @param node {HTMLElement} Element to start searching
* @returns {HTMLElement | null} Scrollable parent element
*/
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
if (node == null) return null;
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode as HTMLElement);
}
};
| src/block-selector/selection-util.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\tprivate selectPreviousBlockOrScroll(block: HTMLElement) {\n\t\tif (!isTopInView(block)) {\n\t\t\tscrollTopIntoView(block);\n\t\t} else {\n\t\t\tconst prev = findPreviousBlock(block);\n\t\t\tif (prev) this.select(prev as HTMLElement);\n\t\t}\n\t}\n\t/**\n\t * Select top block in the view",
"score": 0.7616792321205139
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 0.7244623899459839
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set `data-rve-block` attribute to block elements.\n\t *\n\t * @param element {HTMLElement} Element to start searching\n\t */\n\tprivate elementsToBlocks(element: HTMLElement) {\n\t\tconst elements = element.querySelectorAll(BLOCKS.join(\", \"));\n\t\telements.forEach((el) => {\n\t\t\tif (el.hasClass(FRONTMATTER)) return;",
"score": 0.7145729064941406
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Trigger 'select' on clicked block element.\n\t *\n\t * @param e {MouseEvent} Mouse event\n\t */\n\tonBlockClick(e: MouseEvent) {\n\t\tconst target = e.target as HTMLElement;\n\t\tconst block = target.closest(`[${BLOCK_ATTR}=true]`);\n\t\tif (block instanceof HTMLElement) {",
"score": 0.7031334638595581
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t}\n\t}\n\t/**\n\t * Select next block or scroll to see the block's bottom.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tprivate selectNextBlockOrScroll(block: HTMLElement) {\n\t\tif (!isBottomInView(block)) {\n\t\t\tscrollBottomIntoView(block);",
"score": 0.7002254724502563
}
] | typescript | while (parent && !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: | GitSavedWorkspace): Promise<void> { |
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const unittestDb = new BaseDb<UnitTest>('UnitTest');\n const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);\n for (const testSuite of unitTestSuites) {\n const tests = await unittestDb.findBy('parentId', testSuite._id);\n savedUnittestSuites.push({\n tests,\n testSuite,\n });\n }\n return savedUnittestSuites;",
"score": 0.847347617149353
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 0.8075717687606812
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 0.7913539409637451
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 0.7854666709899902
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 0.7582346200942993
}
] | typescript | GitSavedWorkspace): Promise<void> { |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof | HTMLElement && !container.hasClass(BLOCK_SELECTOR)
); |
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is collapsed\n */\nconst isCollapsed = (element: HTMLElement) => {\n\treturn element.hasClass(IS_COLLAPSED);\n};\n/**\n * Find first block element inside the given element\n *",
"score": 0.8197456002235413
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\telse return null;\n};\n/**\n * Check if the given element is a block element\n *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is a block element\n */\nconst isBlock = (element: HTMLElement) => {\n\treturn element.getAttribute(BLOCK_ATTR) === \"true\";",
"score": 0.8113417625427246
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * Fold/Unfold block.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tprivate toggleFold(block: HTMLElement) {\n\t\tconst collapseIndicator = block.querySelector(\n\t\t\tCOLLAPSE_INDICATORS.join(\",\")\n\t\t) as HTMLElement;\n\t\tif (collapseIndicator) {\n\t\t\tcollapseIndicator.click();",
"score": 0.8084466457366943
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 0.795684278011322
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " * @returns {HTMLElement | null} Next block element\n */\nexport const findNextBlock = (\n\tcurrentElement: HTMLElement\n): HTMLElement | null => {\n\tlet nextBlock = null;\n\t// Start by checking if there's a block element inside the current element\n\tif (!isCollapsed(currentElement)) {\n\t\tconst children = currentElement.children;\n\t\tfor (let i = 0; i < children.length; i++) {",
"score": 0.7933603525161743
}
] | typescript | HTMLElement && !container.hasClass(BLOCK_SELECTOR)
); |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
| this.selectionHandler.onBlockClick(e)
); |
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tselect(block: HTMLElement) {\n\t\tblock.focus();\n\t\tblock.addClass(SELECTED_BLOCK);\n\t\tthis.selectedBlock = block;\n\t}\n\t/**\n\t * Unselect block element.",
"score": 0.8109087944030762
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Trigger 'select' on clicked block element.\n\t *\n\t * @param e {MouseEvent} Mouse event\n\t */\n\tonBlockClick(e: MouseEvent) {\n\t\tconst target = e.target as HTMLElement;\n\t\tconst block = target.closest(`[${BLOCK_ATTR}=true]`);\n\t\tif (block instanceof HTMLElement) {",
"score": 0.7993133068084717
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * Fold/Unfold block.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tprivate toggleFold(block: HTMLElement) {\n\t\tconst collapseIndicator = block.querySelector(\n\t\t\tCOLLAPSE_INDICATORS.join(\",\")\n\t\t) as HTMLElement;\n\t\tif (collapseIndicator) {\n\t\t\tcollapseIndicator.click();",
"score": 0.7917227745056152
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If there is no selected block, do nothing.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tunselect() {\n\t\tif (this.selectedBlock) {\n\t\t\tthis.selectedBlock.removeClass(SELECTED_BLOCK);\n\t\t\tthis.selectedBlock.blur();\n\t\t\tthis.selectedBlock = null;\n\t\t}",
"score": 0.7681498527526855
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t}\n\t}\n\t/**\n\t * Select next block or scroll to see the block's bottom.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tprivate selectNextBlockOrScroll(block: HTMLElement) {\n\t\tif (!isBottomInView(block)) {\n\t\t\tscrollBottomIntoView(block);",
"score": 0.7636973857879639
}
] | typescript | this.selectionHandler.onBlockClick(e)
); |
import { Plugin } from "obsidian";
import RveStyles, { BlockColorRule } from "./styles";
import { RveSettingTab, RveSettings, DEFAULT_SETTINGS } from "./settings";
import Commands from "./commands";
import BlockSelector from "./block-selector";
export default class ReadingViewEnhancer extends Plugin {
settings: RveSettings;
styles: RveStyles;
blockSelector: BlockSelector;
/**
* On load,
*
* - Load settings & styles
* - Activate block selector
* - It actually do its work if settings.enableBlockSelector is true
* - Register all commands
* - Add settings tab
*/
async onload() {
// Settings & Styles
await this.loadSettings();
this.styles = new RveStyles();
this.app.workspace.onLayoutReady(() => this.applySettingsToStyles());
// Activate block selector.
this.blockSelector = new BlockSelector(this);
this.blockSelector.activate();
// Register commands
new Commands(this).register();
// Add settings tab at last
this.addSettingTab(new RveSettingTab(this));
// Leave a message in the console
console.log("Loaded 'Reading View Enhancer'");
}
/**
* On unload,
*
* - Remove all styles
*/
async onunload() {
this.styles.cleanup();
// Leave a message in the console
console.log("Unloaded 'Reading View Enhancer'");
}
// ===================================================================
/**
* Load settings
*/
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
/**
* Save settings
*/
async saveSettings() {
await this.saveData(this.settings);
}
/**
* Apply settings to styles
*
* - Apply block color
* - Apply always on collapse indicator
* - Apply prevent table overflowing
* - Apply scrollable code
*/
private applySettingsToStyles() {
this.applyBlockColor();
this.applyAlwaysOnCollapse();
this.applyPreventTableOverflowing();
this.applyScrollableCode();
this.styles.apply();
}
/**
* Apply block color
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyBlockColor(isImmediate = false) {
const blockColor = this.styles.of("block-color") as BlockColorRule;
| blockColor.set(this.settings.blockColor); |
if (isImmediate) this.styles.apply();
}
/**
* Apply always on collapse indicator
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyAlwaysOnCollapse(isImmediate = false) {
this.styles.of("collapse-indicator").isActive =
this.settings.alwaysOnCollapseIndicator;
if (isImmediate) this.styles.apply();
}
/**
* Apply prevent table overflowing
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyPreventTableOverflowing(isImmediate = false) {
this.styles.of("prevent-table-overflowing").isActive =
this.settings.preventTableOverflowing;
if (isImmediate) this.styles.apply();
}
/**
* Apply scrollable code
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyScrollableCode(isImmediate = false) {
this.styles.of("scrollable-code").isActive = this.settings.scrollableCode;
if (isImmediate) this.styles.apply();
}
}
| src/main.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set the block color\n\t *\n\t * @param blockColor {string} The block color\n\t */\n\tset(blockColor: string) {\n\t\tthis.blockColor = blockColor;\n\t}\n}",
"score": 0.8312903046607971
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t\t\tthis.plugin.applyBlockColor(true);\n\t\t});\n\t\tthis.addButton((button) => this.accentColorButton(button, color));\n\t}\n\t/**\n\t * Creates a button to use current accent color.\n\t * Used in {@link colorPicker}.\n\t *\n\t * @param button {ButtonComponent} Button component\n\t * @param color {ColorComponent} Color component",
"score": 0.7986841201782227
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t * Also, creates a button to set color to the current accent color.\n\t *\n\t * @param color {ColorComponent} Color component\n\t */\n\tcolorPicker(color: ColorComponent) {\n\t\tconst { settings } = this.plugin;\n\t\tcolor.setValue(settings.blockColor).onChange((changed) => {\n\t\t\t// save on change\n\t\t\tsettings.blockColor = toHex(changed);\n\t\t\tthis.plugin.saveSettings();",
"score": 0.7853031754493713
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Activate BlockSelector\n\t */\n\tactivate() {\n\t\tthis.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));\n\t}\n\t/**\n\t * Select top block in the view\n\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */",
"score": 0.7804978489875793
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\tcleanup() {\n\t\tthis.styleTag.remove();\n\t}\n\t/**\n\t * Get a rule by key\n\t *\n\t * @param rule {RuleKey} rule's key\n\t * @returns {StyleRule} One of the rules\n\t */\n\tof(rule: RuleKey) {",
"score": 0.7776964902877808
}
] | typescript | blockColor.set(this.settings.blockColor); |
import { exportProject, exportWorkspaceData } from './exportData';
import fs from 'node:fs';
import { importWorkspaceData } from './importData';
import InternalDb from './db/InternalDb';
import { getActiveProjectId, getActiveWorkspace } from './db/localStorageUtils';
import { join } from 'node:path';
import importNewProjectButton from './ui/importNewProjectButton';
import projectDropdown from './ui/projectDropdown';
import alertModal from './ui/react/alertModal';
import renderModal from './ui/react/renderModal';
import injectStyles from './ui/injectStyles';
import autoExport from './autoExport';
// Inject UI elements.
// @ts-ignore
const currentVersion = (window.gitIntegrationInjectCounter || 0) + 1;
// @ts-ignore
window.gitIntegrationInjectCounter = currentVersion;
function doInject() {
// @ts-ignore
// Check if the window was reloaded. When it was reloaded the Global counter changed
if (window.gitIntegrationInjectCounter !== currentVersion) {
return;
}
injectStyles();
projectDropdown();
importNewProjectButton();
window.requestAnimationFrame(doInject);
}
window.requestAnimationFrame(doInject);
setInterval(autoExport, 5000);
module.exports.workspaceActions = [
{
label: 'Export workspace to Git',
icon: 'download',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot export workspace',
'You must first configure the project folder before exporting',
));
return;
}
| const data = await exportWorkspaceData(workspaceId); |
const targetFile = join(path, workspaceId + '.json');
fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));
},
},
{
label: 'Import workspace from Git',
icon: 'upload',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot import workspace',
'You must first configure the project folder before importing',
));
return;
}
const targetFile = join(path, workspaceId + '.json');
const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());
await importWorkspaceData(dataRaw);
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
},
},
];
| src/index.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 0.9671417474746704
},
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " const projectId = getActiveProjectId();\n if (!projectId) {\n await renderModal(alertModal('Internal error', 'No ProjectId found in LocalStorage'));\n return;\n }\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot import Project',",
"score": 0.9238609075546265
},
{
"filename": "src/autoExport.ts",
"retrieved_chunk": " const projectId = getActiveProjectId();\n if (!projectId) {\n return;\n }\n const config = InternalDb.create();\n const { repositoryPath: path, autoExport } = config.getProject(projectId);\n if (!path || !autoExport || projectId === 'proj_default-project') {\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);",
"score": 0.8893957138061523
},
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " // \"Close\" the dropdown\n projectDropdown.remove();\n const projectId = getActiveProjectId();\n if (!projectId) {\n return;\n }\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(",
"score": 0.8884081840515137
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " `;\n gitCommitButton.addEventListener('click', async () => {\n // \"Close\" the dropdown\n projectDropdown.remove();\n const projectId = getActiveProjectId();\n if (!projectId) {\n await renderModal(alertModal('Internal error', 'No ProjectId found in LocalStorage'));\n return;\n }\n const config = InternalDb.create();",
"score": 0.88090980052948
}
] | typescript | const data = await exportWorkspaceData(workspaceId); |
import { Plugin } from "obsidian";
import RveStyles, { BlockColorRule } from "./styles";
import { RveSettingTab, RveSettings, DEFAULT_SETTINGS } from "./settings";
import Commands from "./commands";
import BlockSelector from "./block-selector";
export default class ReadingViewEnhancer extends Plugin {
settings: RveSettings;
styles: RveStyles;
blockSelector: BlockSelector;
/**
* On load,
*
* - Load settings & styles
* - Activate block selector
* - It actually do its work if settings.enableBlockSelector is true
* - Register all commands
* - Add settings tab
*/
async onload() {
// Settings & Styles
await this.loadSettings();
this.styles = new RveStyles();
this.app.workspace.onLayoutReady(() => this.applySettingsToStyles());
// Activate block selector.
this.blockSelector = new BlockSelector(this);
this.blockSelector.activate();
// Register commands
new Commands(this).register();
// Add settings tab at last
this.addSettingTab(new RveSettingTab(this));
// Leave a message in the console
console.log("Loaded 'Reading View Enhancer'");
}
/**
* On unload,
*
* - Remove all styles
*/
async onunload() {
this.styles.cleanup();
// Leave a message in the console
console.log("Unloaded 'Reading View Enhancer'");
}
// ===================================================================
/**
* Load settings
*/
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
/**
* Save settings
*/
async saveSettings() {
await this.saveData(this.settings);
}
/**
* Apply settings to styles
*
* - Apply block color
* - Apply always on collapse indicator
* - Apply prevent table overflowing
* - Apply scrollable code
*/
private applySettingsToStyles() {
this.applyBlockColor();
this.applyAlwaysOnCollapse();
this.applyPreventTableOverflowing();
this.applyScrollableCode();
this.styles.apply();
}
/**
* Apply block color
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyBlockColor(isImmediate = false) {
const blockColor = this.styles | .of("block-color") as BlockColorRule; |
blockColor.set(this.settings.blockColor);
if (isImmediate) this.styles.apply();
}
/**
* Apply always on collapse indicator
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyAlwaysOnCollapse(isImmediate = false) {
this.styles.of("collapse-indicator").isActive =
this.settings.alwaysOnCollapseIndicator;
if (isImmediate) this.styles.apply();
}
/**
* Apply prevent table overflowing
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyPreventTableOverflowing(isImmediate = false) {
this.styles.of("prevent-table-overflowing").isActive =
this.settings.preventTableOverflowing;
if (isImmediate) this.styles.apply();
}
/**
* Apply scrollable code
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyScrollableCode(isImmediate = false) {
this.styles.of("scrollable-code").isActive = this.settings.scrollableCode;
if (isImmediate) this.styles.apply();
}
}
| src/main.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set the block color\n\t *\n\t * @param blockColor {string} The block color\n\t */\n\tset(blockColor: string) {\n\t\tthis.blockColor = blockColor;\n\t}\n}",
"score": 0.8539614677429199
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\tcleanup() {\n\t\tthis.styleTag.remove();\n\t}\n\t/**\n\t * Get a rule by key\n\t *\n\t * @param rule {RuleKey} rule's key\n\t * @returns {StyleRule} One of the rules\n\t */\n\tof(rule: RuleKey) {",
"score": 0.8383268117904663
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t\t\tthis.plugin.applyBlockColor(true);\n\t\t});\n\t\tthis.addButton((button) => this.accentColorButton(button, color));\n\t}\n\t/**\n\t * Creates a button to use current accent color.\n\t * Used in {@link colorPicker}.\n\t *\n\t * @param button {ButtonComponent} Button component\n\t * @param color {ColorComponent} Color component",
"score": 0.8264219760894775
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\tthis.template = template;\n\t\tthis.isActive = false;\n\t\tthis.injectVariables = injectVariables;\n\t}\n\t/**\n\t * Get the rule after injecting variables\n\t *\n\t * @returns {string} The rule\n\t */\n\tgetRule() {",
"score": 0.8162609338760376
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\treturn this.injectVariables(this.template);\n\t}\n}\n/**\n * Block color rule.\n *\n * Accepts a block color and injects it into the template.\n */\nexport class BlockColorRule extends StyleRule {\n\tprivate blockColor: string;",
"score": 0.8041507005691528
}
] | typescript | .of("block-color") as BlockColorRule; |
import { PluginSettingTab } from "obsidian";
import ReadingViewEnhancer from "../main";
import BlockSelectorSettings from "./block";
import MiscellaneousSettings from "./miscellaneous";
export interface RveSettings {
blockColor: string;
enableBlockSelector: boolean;
disableBlockSelectorOnMobile: boolean;
alwaysOnCollapseIndicator: boolean;
preventTableOverflowing: boolean;
scrollableCode: boolean;
}
export const DEFAULT_SETTINGS: RveSettings = {
blockColor: "#8b6cef", // Obsidian default color
enableBlockSelector: false,
disableBlockSelectorOnMobile: false,
alwaysOnCollapseIndicator: false,
preventTableOverflowing: false,
scrollableCode: false,
};
// ===================================================================
/**
* Settings tab.
* In this tab, you can change settings.
*
* - Block color
* - Enable/Disable Block Selector
*/
export class RveSettingTab extends PluginSettingTab {
plugin: ReadingViewEnhancer;
constructor(plugin: ReadingViewEnhancer) {
super(app, plugin);
this.plugin = plugin;
}
/**
* Displays settings tab.
*/
display() {
const { containerEl } = this;
// Clear all first
containerEl.empty();
// Add header
containerEl.createEl("h1", { text: "Reading View Enhancer" });
// Add block selector settings
| new BlockSelectorSettings(containerEl, this.plugin); |
// Add miscellaneous settings
new MiscellaneousSettings(containerEl, this.plugin);
}
}
| src/settings/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Activate BlockSelector\n\t */\n\tactivate() {\n\t\tthis.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));\n\t}\n\t/**\n\t * Select top block in the view\n\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */",
"score": 0.7978829145431519
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Initialize container.\n\t * Add some event listeners to container.\n\t *\n\t * @param container {MarkdownPostProcessorContext.containerEl} Container element\n\t */\n\tprivate initializeContainer(container: HTMLElement) {\n\t\t// Mark container as initialized\n\t\tcontainer.addClass(BLOCK_SELECTOR);\n\t\t// On click, select block element\n\t\tcontainer.addEventListener(\"click\", (e) =>",
"score": 0.7860865592956543
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t// Leave a message in the console\n\t\tconsole.log(\"Unloaded 'Reading View Enhancer'\");\n\t}\n\t// ===================================================================\n\t/**\n\t * Load settings\n\t */\n\tasync loadSettings() {\n\t\tthis.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());\n\t}",
"score": 0.7647202014923096
},
{
"filename": "src/settings/block/index.ts",
"retrieved_chunk": "import ReadingViewEnhancer from \"src/main\";\nimport BlockColorSetting from \"./block-color\";\nimport EnableBlockSelectorSetting from \"./block-selector\";\nimport DisableBlockSelectorOnMobileSetting from \"./block-selector-mobile\";\n/**\n * Registers settings components related to block selector.\n */\nexport default class BlockSelectorSettings {\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tcontainerEl.createEl(\"h2\", { text: \"Block Selector\" });",
"score": 0.7632636427879333
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set `data-rve-block` attribute to block elements.\n\t *\n\t * @param element {HTMLElement} Element to start searching\n\t */\n\tprivate elementsToBlocks(element: HTMLElement) {\n\t\tconst elements = element.querySelectorAll(BLOCKS.join(\", \"));\n\t\telements.forEach((el) => {\n\t\t\tif (el.hasClass(FRONTMATTER)) return;",
"score": 0.7620837688446045
}
] | typescript | new BlockSelectorSettings(containerEl, this.plugin); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData( | await exportWorkspaceData(data.id))
: OldIds.createEmpty(); |
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 0.8751084804534912
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 0.869632363319397
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " modified: Date.now(),\n type: 'RequestMeta',\n _id: 'reqm_' + randomBytes(16).toString('hex'),\n name: '', // This is not used by insomnia.\n }\n}\nexport async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {\n // Load the Project\n const projectDb = new BaseDb<Project>('Project');\n const fullProject = await projectDb.findById(projectId);",
"score": 0.8542009592056274
},
{
"filename": "src/ui/importNewProjectButton.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n const configDb = InternalDb.create();\n const projectConfig = configDb.getProject(project.id);\n projectConfig.repositoryPath = openResult.filePaths[0];\n configDb.upsertProject(projectConfig);\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(targetDir, workspaceId + '.json');",
"score": 0.8333443999290466
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " if (!workspace) {\n throw new Error('No Workspace found for id: ' + workspaceId);\n }\n const name = workspace.name;\n // Find WorkspaceMeta\n const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');\n const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);\n const fullMeta = fullMetas[0];\n const meta: GitSavedWorkspaceMeta = {\n _id: fullMeta._id,",
"score": 0.8313369750976562
}
] | typescript | await exportWorkspaceData(data.id))
: OldIds.createEmpty(); |
import { exportProject, exportWorkspaceData } from './exportData';
import fs from 'node:fs';
import { importWorkspaceData } from './importData';
import InternalDb from './db/InternalDb';
import { getActiveProjectId, getActiveWorkspace } from './db/localStorageUtils';
import { join } from 'node:path';
import importNewProjectButton from './ui/importNewProjectButton';
import projectDropdown from './ui/projectDropdown';
import alertModal from './ui/react/alertModal';
import renderModal from './ui/react/renderModal';
import injectStyles from './ui/injectStyles';
import autoExport from './autoExport';
// Inject UI elements.
// @ts-ignore
const currentVersion = (window.gitIntegrationInjectCounter || 0) + 1;
// @ts-ignore
window.gitIntegrationInjectCounter = currentVersion;
function doInject() {
// @ts-ignore
// Check if the window was reloaded. When it was reloaded the Global counter changed
if (window.gitIntegrationInjectCounter !== currentVersion) {
return;
}
injectStyles();
projectDropdown();
importNewProjectButton();
window.requestAnimationFrame(doInject);
}
window.requestAnimationFrame(doInject);
setInterval(autoExport, 5000);
module.exports.workspaceActions = [
{
label: 'Export workspace to Git',
icon: 'download',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot export workspace',
'You must first configure the project folder before exporting',
));
return;
}
const data = await exportWorkspaceData(workspaceId);
const targetFile = join(path, workspaceId + '.json');
fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));
},
},
{
label: 'Import workspace from Git',
icon: 'upload',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot import workspace',
'You must first configure the project folder before importing',
));
return;
}
const targetFile = join(path, workspaceId + '.json');
const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());
await | importWorkspaceData(dataRaw); |
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
},
},
];
| src/index.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');",
"score": 0.9132698774337769
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 0.9049664735794067
},
{
"filename": "src/autoExport.ts",
"retrieved_chunk": " const newExportJson = JSON.stringify([projectData, workspaces]);\n if (newExportJson === prevExport) {\n // Nothing to export, so lets try to Import\n await autoImportProject(path);\n return;\n }\n prevExport = newExportJson;\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {",
"score": 0.8913367986679077
},
{
"filename": "src/autoExport.ts",
"retrieved_chunk": " const targetFile = join(path, workspace.id + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));\n }\n}\nlet prevImport = '';\nasync function autoImportProject(path: string) {\n let project, workspaceData;\n try {\n [project, workspaceData] = readProjectData(path);\n } catch (e) {",
"score": 0.8753339052200317
},
{
"filename": "src/ui/importNewProjectButton.ts",
"retrieved_chunk": " }\n const targetDir = openResult.filePaths[0];\n const projectFile = join(targetDir, 'project.json');\n if (!fs.existsSync(projectFile)) {\n await renderModal(alertModal(\n 'Invalid folder',\n 'This folder does not contain files to import (e.g. \"project.json\", \"wrk_*.json\")',\n ));\n return;\n }",
"score": 0.8658338785171509
}
] | typescript | importWorkspaceData(dataRaw); |
import {COMPOSE_CONTENT_EDITABLE, COMPOSE_LINK_CARD_BUTTON} from '../dom/selectors';
import {log} from '../utils/logger';
import {typeText, backspace} from '../utils/text';
import {Pipeline} from './pipeline';
import {ultimatelyFind} from '../dom/utils';
import {EventKeeper} from '../utils/eventKeeper';
const STAGING_URL_REGEX = /.*(https:\/\/staging\.bsky\.app\/profile\/.*\/post\/.*\/?)$/;
const URL_REGEX = /.*(https:\/\/bsky\.app\/profile\/.*\/post\/.*\/?)$/;
export class QuotePostPipeline extends Pipeline {
#modal: HTMLElement | null;
#contentEditable: HTMLElement | null;
readonly #eventKeeper: EventKeeper;
constructor() {
super();
this.#modal = null;
this.#contentEditable = null;
this.#eventKeeper = new EventKeeper();
}
deploy(modal: HTMLElement): void {
if (this.#modal !== null) {
log('QuotePostPipeline is already deployed');
return;
}
this.#modal = modal;
ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE).then((contentEditable) => {
this.#contentEditable = contentEditable;
this.#eventKeeper.add(contentEditable, 'paste', this.onPaste.bind(this), {capture: true});
});
}
terminate(): void {
if (this.#modal === null) {
log('QuotePostPipeline is not deployed');
return;
}
this.#eventKeeper.cancelAll();
this.#modal = this.#contentEditable = null;
}
onPaste(event: ClipboardEvent): void {
if (!event.clipboardData || !this.#contentEditable) return;
if (event.clipboardData.types.indexOf('text/plain') === -1) return;
event.preventDefault();
const contentEditable = this.#contentEditable;
let data = event.clipboardData.getData('text/plain');
if (data.match(STAGING_URL_REGEX) !== null) {
data = data.replace('https://staging.bsky.app/', 'https://bsky.app/');
}
contentEditable.focus();
typeText(data);
typeText(' '); // Add a space after the link for it to resolve as one
// Wait for the text to be inserted into the contentEditable
setTimeout(() => {
const lastChar = contentEditable.textContent?.slice(-1) ?? '';
if (lastChar === ' ') backspace();
if (data.match(URL_REGEX) !== null) {
this. | #modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => { |
linkCardButton.click();
});
}
}, 50);
}
}
| src/content/pipelines/quotePost.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});\n } else {\n tip('No new posts to load');\n }\n } catch {\n tip('You are not on the feed page');\n }\n }\n async #newPost(): Promise<void> {\n const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);",
"score": 0.7767624855041504
},
{
"filename": "src/content/utils/selection.ts",
"retrieved_chunk": " node = node.parentNode as Node;\n }\n return false;\n};\nexport const getCurrentCursorPosition = (parentElement: HTMLElement): number => {\n const selection = window.getSelection();\n let charCount = -1;\n let node = null;\n if (selection && selection.focusNode) {\n if (isChildOf(selection.focusNode, parentElement)) {",
"score": 0.77420973777771
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " #findSearchBar(): Promise<HTMLElement> {\n return ultimatelyFind(document.body, SEARCH_BAR);\n }\n async #loadNewPosts(): Promise<void> {\n try {\n const tab = await this.#postList.getCurrentFeedTab();\n const tabContainer = await ultimatelyFind(this.#container, tab);\n const newPostsButton = tabContainer.childNodes[1] as HTMLElement;\n if (newPostsButton && newPostsButton.nextSibling) {\n newPostsButton.click();",
"score": 0.7736802101135254
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " return this.#activeTabSelector.clone();\n } else {\n return Promise.reject('Not on main page');\n }\n });\n }\n setCurrentPost(element: HTMLElement): Promise<HTMLElement> {\n return this.#resolveList().then((posts) => {\n for (const post of posts) {\n if (post === element || post.parentElement === element || post.contains(element)) {",
"score": 0.7731370329856873
},
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " this.#elems.contentEditable.focus();\n }\n };\n this.#modal?.addEventListener('click', clickOutside);\n document.addEventListener('click', clickOutside);\n }\n #removeElements(): void {\n for (const element of Object.values(this.#elems)) {\n try {\n if (element.parentElement) {",
"score": 0.7654938697814941
}
] | typescript | #modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => { |
import {IPausable} from '../../../interfaces';
import {TSelectorLike, ultimatelyFindAll} from '../../dom/utils';
import {LAST_CHILD, POST_ITEMS} from '../../dom/selectors';
import {Selector} from '../../dom/selector';
import {EventKeeper} from '../../utils/eventKeeper';
const LAG = 100;
const FOLLOWING_DATA = 'homeScreenFeedTabs-Following';
const WHATSHOT_DATA = 'homeScreenFeedTabs-What\'s hot';
const TAB_BUTTONS = new Selector('[data-testid="homeScreenFeedTabs"]', {exhaustAfter: LAG});
const FOLLOWING_FEED = new Selector('[data-testid="followingFeedPage"]');
const WHATSHOT_FEED = new Selector('[data-testid="whatshotFeedPage"]');
const getNextPost = (post: HTMLElement): HTMLElement | null => {
if (post.nextSibling) {
return post.nextSibling as HTMLElement;
} else {
const parent = post.parentElement;
if (parent && parent.nextSibling) {
return parent.nextSibling.firstChild as HTMLElement;
} else {
return null;
}
}
};
const getPreviousPost = (post: HTMLElement): HTMLElement | null => {
if (post.previousSibling) {
return post.previousSibling as HTMLElement;
} else {
const parent = post.parentElement;
if (parent && parent.previousSibling) {
return parent.previousSibling.lastChild as HTMLElement;
} else {
return null;
}
}
};
const isPostThreadDelimiter = (postCandidate: HTMLElement): boolean => {
return postCandidate.getAttribute('role') === 'link' && postCandidate.getAttribute('tabindex') === '0';
};
export class PostList implements IPausable {
readonly #container: HTMLElement;
readonly #mutationObserver: MutationObserver;
readonly #tabButtonEventKeeper = new EventKeeper();
#activeTabSelector: Selector = FOLLOWING_FEED;
#currentPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#mutationObserver = new MutationObserver(this.#onContainerMutation.bind(this));
this.#isPaused = startPaused;
if (!startPaused) this.start();
}
start(): void {
this.#isPaused = false;
}
pause(): void {
this.#isPaused = true;
}
getCurrentFeedTab(): Promise<Selector> {
return this.#isMainPage().then((isMainPage) => {
if (isMainPage) {
return this.#activeTabSelector.clone();
} else {
return Promise.reject('Not on main page');
}
});
}
setCurrentPost(element: HTMLElement): Promise<HTMLElement> {
return this.#resolveList().then((posts) => {
for (const post of posts) {
if (post === element || post.parentElement === element || post.contains(element)) {
this.#currentPost = post;
return this.#currentPost;
}
}
return Promise.reject('Element is not a post');
});
}
getNextPost(): Promise<HTMLElement> {
return this.#getNeighborPost(getNextPost);
}
getPreviousPost(): Promise<HTMLElement> {
return this.#getNeighborPost(getPreviousPost);
}
#getNeighborPost(retrieveFn: (post: HTMLElement) => HTMLElement | null): Promise<HTMLElement> {
if (this.#isPaused) return Promise.reject('PostList is paused');
return this.#resolveList().then((posts) => {
if (posts.length === 0) {
return Promise.reject('No posts found');
} else if (this.#currentPost) {
const neighborPost = retrieveFn(this.#currentPost);
if (neighborPost && (posts.includes(neighborPost) || isPostThreadDelimiter(neighborPost))) {
this.#currentPost = neighborPost;
} else if (!posts.includes(this.#currentPost)) {
this.#currentPost = posts[0];
}
} else {
this.#currentPost = posts[0];
}
return this.#currentPost;
});
}
#isMainPage(): Promise<boolean> {
return this.#findElements([TAB_BUTTONS]).then((tabButtonsList) => {
if (tabButtonsList.length !== 1) throw new Error('There should be exactly one tab button container');
this.#subscribeToTabButtons(tabButtonsList[0]);
return true;
}).catch(() => false);
}
#resolveList(): Promise<HTMLElement[]> {
return this.#isMainPage().then((isMainPage) => {
const prefixingSelectors = isMainPage ? [this.#activeTabSelector] : [];
| return this.#findElements([...prefixingSelectors, POST_ITEMS]).then((posts) => { |
if (posts.length === 0) {
return Promise.reject('No posts found');
} else {
return posts;
}
});
});
}
#subscribeToTabButtons(tabButtons: HTMLElement): void {
this.#tabButtonEventKeeper.cancelAll();
this.#tabButtonEventKeeper.add(tabButtons, 'click', this.#onTabButtonClick.bind(this));
}
#onContainerMutation(mutations: MutationRecord[]): void {
mutations.forEach((mutation) => {
if (mutation.target === this.#container) {
this.#currentPost = null;
}
});
}
#onTabButtonClick(event: MouseEvent): void {
const target = event.target as HTMLElement;
const data = target.getAttribute('data-testid');
if (data === FOLLOWING_DATA || target.querySelector(`[data-testid="${FOLLOWING_DATA}"]`)) {
if (this.#activeTabSelector !== FOLLOWING_FEED) this.#currentPost = null;
this.#activeTabSelector = FOLLOWING_FEED;
} else if (data === WHATSHOT_DATA || target.querySelector(`[data-testid="${WHATSHOT_DATA}"]`)) {
if (this.#activeTabSelector !== WHATSHOT_FEED) this.#currentPost = null;
this.#activeTabSelector = WHATSHOT_FEED;
}
}
#findElements(selectors: TSelectorLike[]): Promise<HTMLElement[]> {
return ultimatelyFindAll(this.#container, [LAST_CHILD, ...selectors]);
}
}
| src/content/watchers/helpers/postList.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " #findSearchBar(): Promise<HTMLElement> {\n return ultimatelyFind(document.body, SEARCH_BAR);\n }\n async #loadNewPosts(): Promise<void> {\n try {\n const tab = await this.#postList.getCurrentFeedTab();\n const tabContainer = await ultimatelyFind(this.#container, tab);\n const newPostsButton = tabContainer.childNodes[1] as HTMLElement;\n if (newPostsButton && newPostsButton.nextSibling) {\n newPostsButton.click();",
"score": 0.8338499069213867
},
{
"filename": "src/content/pipelines/quotePost.ts",
"retrieved_chunk": " setTimeout(() => {\n const lastChar = contentEditable.textContent?.slice(-1) ?? '';\n if (lastChar === ' ') backspace();\n if (data.match(URL_REGEX) !== null) {\n this.#modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => {\n linkCardButton.click();\n });\n }\n }, 50);\n }",
"score": 0.7898638844490051
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " const children = rootContainer.childNodes;\n const menuItems = children[1].childNodes;\n const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;\n if (newPostButton) {\n newPostButton.click();\n } else {\n tip('No new post button found');\n }\n }\n}",
"score": 0.7879213690757751
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " this.#currentPost?.click();\n break;\n default:\n tip(`Action \"${action}\" is not implemented yet`);\n }\n }\n #selectPost(direction: DIRECTION): void {\n if (direction === DIRECTION.NEXT) {\n this.#postList.getNextPost().then((p) => this.#highlightPost(p));\n } else {",
"score": 0.7784781455993652
},
{
"filename": "src/content/pipelines/quotePost.ts",
"retrieved_chunk": " log('QuotePostPipeline is already deployed');\n return;\n }\n this.#modal = modal;\n ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE).then((contentEditable) => {\n this.#contentEditable = contentEditable;\n this.#eventKeeper.add(contentEditable, 'paste', this.onPaste.bind(this), {capture: true});\n });\n }\n terminate(): void {",
"score": 0.7764062285423279
}
] | typescript | return this.#findElements([...prefixingSelectors, POST_ITEMS]).then((posts) => { |
import {IPausable} from '../../../interfaces';
import {TSelectorLike, ultimatelyFindAll} from '../../dom/utils';
import {LAST_CHILD, POST_ITEMS} from '../../dom/selectors';
import {Selector} from '../../dom/selector';
import {EventKeeper} from '../../utils/eventKeeper';
const LAG = 100;
const FOLLOWING_DATA = 'homeScreenFeedTabs-Following';
const WHATSHOT_DATA = 'homeScreenFeedTabs-What\'s hot';
const TAB_BUTTONS = new Selector('[data-testid="homeScreenFeedTabs"]', {exhaustAfter: LAG});
const FOLLOWING_FEED = new Selector('[data-testid="followingFeedPage"]');
const WHATSHOT_FEED = new Selector('[data-testid="whatshotFeedPage"]');
const getNextPost = (post: HTMLElement): HTMLElement | null => {
if (post.nextSibling) {
return post.nextSibling as HTMLElement;
} else {
const parent = post.parentElement;
if (parent && parent.nextSibling) {
return parent.nextSibling.firstChild as HTMLElement;
} else {
return null;
}
}
};
const getPreviousPost = (post: HTMLElement): HTMLElement | null => {
if (post.previousSibling) {
return post.previousSibling as HTMLElement;
} else {
const parent = post.parentElement;
if (parent && parent.previousSibling) {
return parent.previousSibling.lastChild as HTMLElement;
} else {
return null;
}
}
};
const isPostThreadDelimiter = (postCandidate: HTMLElement): boolean => {
return postCandidate.getAttribute('role') === 'link' && postCandidate.getAttribute('tabindex') === '0';
};
export class PostList implements IPausable {
readonly #container: HTMLElement;
readonly #mutationObserver: MutationObserver;
readonly #tabButtonEventKeeper = new EventKeeper();
#activeTabSelector: Selector = FOLLOWING_FEED;
#currentPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#mutationObserver = new MutationObserver(this.#onContainerMutation.bind(this));
this.#isPaused = startPaused;
if (!startPaused) this.start();
}
start(): void {
this.#isPaused = false;
}
pause(): void {
this.#isPaused = true;
}
getCurrentFeedTab(): Promise<Selector> {
return this.#isMainPage().then((isMainPage) => {
if (isMainPage) {
return this.#activeTabSelector.clone();
} else {
return Promise.reject('Not on main page');
}
});
}
setCurrentPost(element: HTMLElement): Promise<HTMLElement> {
return this.#resolveList().then((posts) => {
for (const post of posts) {
if (post === element || post.parentElement === element || post.contains(element)) {
this.#currentPost = post;
return this.#currentPost;
}
}
return Promise.reject('Element is not a post');
});
}
getNextPost(): Promise<HTMLElement> {
return this.#getNeighborPost(getNextPost);
}
getPreviousPost(): Promise<HTMLElement> {
return this.#getNeighborPost(getPreviousPost);
}
#getNeighborPost(retrieveFn: (post: HTMLElement) => HTMLElement | null): Promise<HTMLElement> {
if (this.#isPaused) return Promise.reject('PostList is paused');
return this.#resolveList().then((posts) => {
if (posts.length === 0) {
return Promise.reject('No posts found');
} else if (this.#currentPost) {
const neighborPost = retrieveFn(this.#currentPost);
if (neighborPost && (posts.includes(neighborPost) || isPostThreadDelimiter(neighborPost))) {
this.#currentPost = neighborPost;
} else if (!posts.includes(this.#currentPost)) {
this.#currentPost = posts[0];
}
} else {
this.#currentPost = posts[0];
}
return this.#currentPost;
});
}
#isMainPage(): Promise<boolean> {
return this.#findElements([TAB_BUTTONS]).then((tabButtonsList) => {
if (tabButtonsList.length !== 1) throw new Error('There should be exactly one tab button container');
this.#subscribeToTabButtons(tabButtonsList[0]);
return true;
}).catch(() => false);
}
#resolveList(): Promise<HTMLElement[]> {
return this.#isMainPage().then((isMainPage) => {
const prefixingSelectors = isMainPage ? [this.#activeTabSelector] : [];
return this.#findElements([...prefixingSelectors, POST_ITEMS]).then((posts) => {
if (posts.length === 0) {
return Promise.reject('No posts found');
} else {
return posts;
}
});
});
}
#subscribeToTabButtons(tabButtons: HTMLElement): void {
this.#tabButtonEventKeeper.cancelAll();
this.#tabButtonEventKeeper.add(tabButtons, 'click', this.#onTabButtonClick.bind(this));
}
#onContainerMutation(mutations: MutationRecord[]): void {
mutations.forEach((mutation) => {
if (mutation.target === this.#container) {
this.#currentPost = null;
}
});
}
#onTabButtonClick(event: MouseEvent): void {
const target = event.target as HTMLElement;
const data = target.getAttribute('data-testid');
if (data === FOLLOWING_DATA || target.querySelector(`[data-testid="${FOLLOWING_DATA}"]`)) {
if (this.#activeTabSelector !== FOLLOWING_FEED) this.#currentPost = null;
this.#activeTabSelector = FOLLOWING_FEED;
} else if (data === WHATSHOT_DATA || target.querySelector(`[data-testid="${WHATSHOT_DATA}"]`)) {
if (this.#activeTabSelector !== WHATSHOT_FEED) this.#currentPost = null;
this.#activeTabSelector = WHATSHOT_FEED;
}
}
| #findElements(selectors: TSelectorLike[]): Promise<HTMLElement[]> { |
return ultimatelyFindAll(this.#container, [LAST_CHILD, ...selectors]);
}
}
| src/content/watchers/helpers/postList.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;\n repost?.click();\n }\n #likePost(): void {\n if (!this.#currentPost) return tip(MISSING_POST_ERROR);\n const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;\n like?.click();\n }\n #expandImage(): void {\n if (!this.#currentPost) return tip(MISSING_POST_ERROR);",
"score": 0.7559915781021118
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));\n }\n }\n #replyToPost(): void {\n if (!this.#currentPost) return tip(MISSING_POST_ERROR);\n const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;\n reply?.click();\n }\n #repostPost(): void {\n if (!this.#currentPost) return tip(MISSING_POST_ERROR);",
"score": 0.7432268857955933
},
{
"filename": "src/content/watchers/countersConcealer.ts",
"retrieved_chunk": " this.#container.classList.add(CONCEALER_CLASS);\n }\n onSettingChange(name: APP_SETTINGS, value: TSetting): void {\n if (!this.SETTINGS.includes(name)) throw new Error(`Unknown setting name \"${name}\"`);\n if (typeof value !== typeof DEFAULT_SETTINGS[name]) throw new Error(`Invalid value \"${value}\" for \"${name}\"`);\n if (name === APP_SETTINGS.HIDE_FOLLOWERS_COUNT) {\n this.#toggleClass(value as boolean, HIDE_FOLLOWERS_CLASS);\n } else if (name === APP_SETTINGS.HIDE_FOLLOWING_COUNT) {\n this.#toggleClass(value as boolean, HIDE_FOLLOWING_CLASS);\n } else if (name === APP_SETTINGS.HIDE_POSTS_COUNT) {",
"score": 0.7172514200210571
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " this.#removeHighlight();\n this.#stashedPost = null;\n this.#currentPost = post;\n this.#currentPost.classList.add(FOCUSED_POST_CLASS);\n this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});\n }\n #removeHighlight(): void {\n this.#stashedPost = this.#currentPost;\n this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);\n this.#currentPost = null;",
"score": 0.7097716331481934
},
{
"filename": "src/content/dom/selectors.ts",
"retrieved_chunk": "// All the following are relative to COMPOSE_MODAL\nexport const COMPOSE_CANCEL_BUTTON = new Selector('[data-testid=\"composerCancelButton\"]');\nexport const COMPOSE_CONTENT_EDITABLE = new Selector('div.ProseMirror');\nexport const COMPOSE_LINK_CARD_BUTTON = new Selector('[data-testid=\"addLinkCardBtn\"]');\nexport const COMPOSE_PHOTO_BUTTON = new Selector('[data-testid=\"openGalleryBtn\"]');\nexport const SEARCH_BAR = new Selector('[data-testid=\"searchTextInput\"]'); // relative to FEED_CONTAINER\nexport const POST_ITEMS = new SelectorGroup([\n new Selector('[data-testid^=\"postThreadItem\"]', {exhaustAfter: 5000}),\n new Selector('[data-testid^=\"feedItem\"]', {exhaustAfter: 5000})\n]);",
"score": 0.7082623243331909
}
] | typescript | #findElements(selectors: TSelectorLike[]): Promise<HTMLElement[]> { |
import {IPausable} from '../../../interfaces';
import {ROOT_CONTAINER, SEARCH_BAR} from '../../dom/selectors';
import {EventKeeper} from '../../utils/eventKeeper';
import {noop} from '../../../shared/misc';
import {modal, tip} from '../../utils/notifications';
import {PostList} from './postList';
import {generateHelpMessage, VIM_ACTIONS, VIM_KEY_MAP} from './vimActions';
import {ultimatelyFind} from '../../dom/utils';
enum DIRECTION { NEXT, PREVIOUS }
const FOCUSED_POST_CLASS = 'bluesky-overhaul-focused-post';
const MISSING_POST_ERROR = 'No post is focused';
const REPLY_BUTTON_SELECTOR = '[data-testid="replyBtn"]';
const REPOST_BUTTON_SELECTOR = '[data-testid="repostBtn"]';
const LIKE_BUTTON_SELECTOR = '[data-testid="likeBtn"]';
export class VimKeybindingsHandler implements IPausable {
readonly #container: HTMLElement;
readonly #postList: PostList;
readonly #postClickEventKeeper = new EventKeeper();
readonly #searchBarEventKeeper = new EventKeeper();
#currentPost: HTMLElement | null = null;
#stashedPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#postList = new PostList(targetContainer, startPaused);
this.#isPaused = startPaused;
}
start(): void {
if (!this.#isPaused) return;
this.#postList.start();
this.#postClickEventKeeper.add(this.#container, 'click', this.#onPostAltClick.bind(this));
this.#blurSearchBar();
this.#isPaused = false;
}
pause(): void {
if (this.#isPaused) return;
this.#postList.pause();
this.#postClickEventKeeper.cancelAll();
this.#searchBarEventKeeper.cancelAll();
this.#removeHighlight();
this.#isPaused = true;
}
handle(event: KeyboardEvent): void {
if (this.#isPaused) return;
event.preventDefault();
const key = event.key;
if (!(key in VIM_KEY_MAP)) return;
const action = VIM_KEY_MAP[key as keyof typeof VIM_KEY_MAP];
switch (action) {
| case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage()); |
break;
case VIM_ACTIONS.SEARCH:
this.#focusSearchBar();
break;
case VIM_ACTIONS.LOAD_NEW_POSTS:
this.#loadNewPosts();
break;
case VIM_ACTIONS.NEXT_POST:
this.#selectPost(DIRECTION.NEXT);
break;
case VIM_ACTIONS.PREVIOUS_POST:
this.#selectPost(DIRECTION.PREVIOUS);
break;
case VIM_ACTIONS.LIKE:
this.#likePost();
break;
case VIM_ACTIONS.CREATE_POST:
this.#newPost();
break;
case VIM_ACTIONS.EXPAND_IMAGE:
this.#expandImage();
break;
case VIM_ACTIONS.REPLY:
this.#replyToPost();
break;
case VIM_ACTIONS.REPOST:
this.#repostPost();
break;
case VIM_ACTIONS.OPEN_POST:
this.#currentPost?.click();
break;
default:
tip(`Action "${action}" is not implemented yet`);
}
}
#selectPost(direction: DIRECTION): void {
if (direction === DIRECTION.NEXT) {
this.#postList.getNextPost().then((p) => this.#highlightPost(p));
} else {
this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));
}
}
#replyToPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;
reply?.click();
}
#repostPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;
repost?.click();
}
#likePost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;
like?.click();
}
#expandImage(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const imageContainer = this.#currentPost.querySelector('div.expo-image-container') as HTMLElement;
imageContainer?.click();
}
#onPostAltClick(event: MouseEvent): void {
if (this.#isPaused || !event.altKey) return;
event.preventDefault();
this.#postList.setCurrentPost(event.target as HTMLElement).then((p) => this.#highlightPost(p)).catch(noop);
}
#highlightPost(post: HTMLElement): void {
if (post === this.#currentPost) return;
this.#removeHighlight();
this.#stashedPost = null;
this.#currentPost = post;
this.#currentPost.classList.add(FOCUSED_POST_CLASS);
this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});
}
#removeHighlight(): void {
this.#stashedPost = this.#currentPost;
this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);
this.#currentPost = null;
}
#focusSearchBar(): void {
this.#removeHighlight();
this.#findSearchBar().then((searchBar) => {
this.#searchBarEventKeeper.cancelAll();
searchBar.focus();
this.#searchBarEventKeeper.add(searchBar, 'blur', this.#blurSearchBar.bind(this));
this.#searchBarEventKeeper.add(searchBar, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') searchBar.blur();
});
}).catch(() => tip('Search bar not found'));
}
#blurSearchBar(): void {
this.#searchBarEventKeeper.cancelAll();
this.#findSearchBar().then((searchBar) => {
searchBar.blur();
this.#stashedPost && this.#highlightPost(this.#stashedPost);
this.#searchBarEventKeeper.add(searchBar, 'focus', this.#focusSearchBar.bind(this));
});
}
#findSearchBar(): Promise<HTMLElement> {
return ultimatelyFind(document.body, SEARCH_BAR);
}
async #loadNewPosts(): Promise<void> {
try {
const tab = await this.#postList.getCurrentFeedTab();
const tabContainer = await ultimatelyFind(this.#container, tab);
const newPostsButton = tabContainer.childNodes[1] as HTMLElement;
if (newPostsButton && newPostsButton.nextSibling) {
newPostsButton.click();
this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});
} else {
tip('No new posts to load');
}
} catch {
tip('You are not on the feed page');
}
}
async #newPost(): Promise<void> {
const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);
const children = rootContainer.childNodes;
const menuItems = children[1].childNodes;
const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;
if (newPostButton) {
newPostButton.click();
} else {
tip('No new post button found');
}
}
}
| src/content/watchers/helpers/vimKeybindings.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/keydown.ts",
"retrieved_chunk": " pause(): void {\n if (this.#isPaused) return;\n this.#vimHandler.pause();\n this.#isPaused = true;\n }\n onSettingChange(name: APP_SETTINGS, value: TSetting): void {\n if (!this.SETTINGS.includes(name)) throw new Error(`Unknown setting name \"${name}\"`);\n if (typeof value !== typeof DEFAULT_SETTINGS[name]) throw new Error(`Invalid value \"${value}\" for \"${name}\"`);\n if (name === APP_SETTINGS.HANDLE_VIM_KEYBINDINGS) {\n if (value === true) {",
"score": 0.8153362274169922
},
{
"filename": "src/content/watchers/postDatetime.ts",
"retrieved_chunk": " this.#enabled = value as boolean;\n }\n }\n get SETTINGS(): APP_SETTINGS[] {\n return Object.keys(DEFAULT_SETTINGS) as APP_SETTINGS[];\n }\n async #handleMouseOver(event: MouseEvent): Promise<void> {\n if (!this.#enabled) return;\n const target = event.target as HTMLElement;\n if (target.tagName.toLowerCase() !== 'a') return;",
"score": 0.7832592725753784
},
{
"filename": "src/content/watchers/helpers/vimActions.ts",
"retrieved_chunk": " return name.charAt(0).toUpperCase() + name.slice(1);\n};\nexport const generateHelpMessage = (): string => {\n const actions: { [key: string]: string[] } = {};\n for (const [key, action] of Object.entries(VIM_KEY_MAP)) {\n if (!(action in actions)) actions[action] = [];\n actions[action].push(`<span class=\"mono\">${key}</span>`);\n }\n const helpMessage = [];\n for (const [action, buttons] of Object.entries(actions)) {",
"score": 0.7585211992263794
},
{
"filename": "src/content/watchers/keydown.ts",
"retrieved_chunk": " if (this.#isPaused || event.ctrlKey || event.metaKey) return;\n if (PHOTO_KEYS.includes(event.key)) {\n Promise.all([\n ultimatelyFind(this.#container, LEFT_ARROW_BUTTON).catch(() => null),\n ultimatelyFind(this.#container, RIGHT_ARROW_BUTTON).catch(() => null)\n ]).then(([leftArrow, rightArrow]) => {\n if (event.key === 'ArrowLeft' && leftArrow !== null) {\n leftArrow.click();\n } else if (event.key === 'ArrowRight' && rightArrow !== null) {\n rightArrow.click();",
"score": 0.7509042024612427
},
{
"filename": "src/content/watchers/keydown.ts",
"retrieved_chunk": " this.#vimHandler.start();\n } else {\n this.#vimHandler.pause();\n }\n }\n }\n get SETTINGS(): APP_SETTINGS[] {\n return Object.keys(DEFAULT_SETTINGS) as APP_SETTINGS[];\n }\n #onKeydown(event: KeyboardEvent): void {",
"score": 0.7497762441635132
}
] | typescript | case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage()); |
import {COMPOSE_CONTENT_EDITABLE, COMPOSE_LINK_CARD_BUTTON} from '../dom/selectors';
import {log} from '../utils/logger';
import {typeText, backspace} from '../utils/text';
import {Pipeline} from './pipeline';
import {ultimatelyFind} from '../dom/utils';
import {EventKeeper} from '../utils/eventKeeper';
const STAGING_URL_REGEX = /.*(https:\/\/staging\.bsky\.app\/profile\/.*\/post\/.*\/?)$/;
const URL_REGEX = /.*(https:\/\/bsky\.app\/profile\/.*\/post\/.*\/?)$/;
export class QuotePostPipeline extends Pipeline {
#modal: HTMLElement | null;
#contentEditable: HTMLElement | null;
readonly #eventKeeper: EventKeeper;
constructor() {
super();
this.#modal = null;
this.#contentEditable = null;
this.#eventKeeper = new EventKeeper();
}
deploy(modal: HTMLElement): void {
if (this.#modal !== null) {
log('QuotePostPipeline is already deployed');
return;
}
this.#modal = modal;
ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE).then((contentEditable) => {
this.#contentEditable = contentEditable;
this.#eventKeeper.add(contentEditable, 'paste', this.onPaste.bind(this), {capture: true});
});
}
terminate(): void {
if (this.#modal === null) {
log('QuotePostPipeline is not deployed');
return;
}
this.#eventKeeper.cancelAll();
this.#modal = this.#contentEditable = null;
}
onPaste(event: ClipboardEvent): void {
if (!event.clipboardData || !this.#contentEditable) return;
if (event.clipboardData.types.indexOf('text/plain') === -1) return;
event.preventDefault();
const contentEditable = this.#contentEditable;
let data = event.clipboardData.getData('text/plain');
if (data.match(STAGING_URL_REGEX) !== null) {
data = data.replace('https://staging.bsky.app/', 'https://bsky.app/');
}
contentEditable.focus();
typeText(data);
typeText(' '); // Add a space after the link for it to resolve as one
// Wait for the text to be inserted into the contentEditable
setTimeout(() => {
const lastChar = contentEditable.textContent?.slice(-1) ?? '';
if (lastChar === ' ') backspace();
if (data.match(URL_REGEX) !== null) {
| this.#modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => { |
linkCardButton.click();
});
}
}, 50);
}
}
| src/content/pipelines/quotePost.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});\n } else {\n tip('No new posts to load');\n }\n } catch {\n tip('You are not on the feed page');\n }\n }\n async #newPost(): Promise<void> {\n const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);",
"score": 0.7782008647918701
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " #findSearchBar(): Promise<HTMLElement> {\n return ultimatelyFind(document.body, SEARCH_BAR);\n }\n async #loadNewPosts(): Promise<void> {\n try {\n const tab = await this.#postList.getCurrentFeedTab();\n const tabContainer = await ultimatelyFind(this.#container, tab);\n const newPostsButton = tabContainer.childNodes[1] as HTMLElement;\n if (newPostsButton && newPostsButton.nextSibling) {\n newPostsButton.click();",
"score": 0.7763538360595703
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " return this.#activeTabSelector.clone();\n } else {\n return Promise.reject('Not on main page');\n }\n });\n }\n setCurrentPost(element: HTMLElement): Promise<HTMLElement> {\n return this.#resolveList().then((posts) => {\n for (const post of posts) {\n if (post === element || post.parentElement === element || post.contains(element)) {",
"score": 0.7762078046798706
},
{
"filename": "src/content/utils/selection.ts",
"retrieved_chunk": " node = node.parentNode as Node;\n }\n return false;\n};\nexport const getCurrentCursorPosition = (parentElement: HTMLElement): number => {\n const selection = window.getSelection();\n let charCount = -1;\n let node = null;\n if (selection && selection.focusNode) {\n if (isChildOf(selection.focusNode, parentElement)) {",
"score": 0.7732570767402649
},
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " this.#elems.contentEditable.focus();\n }\n };\n this.#modal?.addEventListener('click', clickOutside);\n document.addEventListener('click', clickOutside);\n }\n #removeElements(): void {\n for (const element of Object.values(this.#elems)) {\n try {\n if (element.parentElement) {",
"score": 0.7681187391281128
}
] | typescript | this.#modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => { |
import {COMPOSE_CONTENT_EDITABLE, COMPOSE_LINK_CARD_BUTTON} from '../dom/selectors';
import {log} from '../utils/logger';
import {typeText, backspace} from '../utils/text';
import {Pipeline} from './pipeline';
import {ultimatelyFind} from '../dom/utils';
import {EventKeeper} from '../utils/eventKeeper';
const STAGING_URL_REGEX = /.*(https:\/\/staging\.bsky\.app\/profile\/.*\/post\/.*\/?)$/;
const URL_REGEX = /.*(https:\/\/bsky\.app\/profile\/.*\/post\/.*\/?)$/;
export class QuotePostPipeline extends Pipeline {
#modal: HTMLElement | null;
#contentEditable: HTMLElement | null;
readonly #eventKeeper: EventKeeper;
constructor() {
super();
this.#modal = null;
this.#contentEditable = null;
this.#eventKeeper = new EventKeeper();
}
deploy(modal: HTMLElement): void {
if (this.#modal !== null) {
log('QuotePostPipeline is already deployed');
return;
}
this.#modal = modal;
ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE).then((contentEditable) => {
this.#contentEditable = contentEditable;
this.#eventKeeper.add(contentEditable, 'paste', this.onPaste.bind(this), {capture: true});
});
}
terminate(): void {
if (this.#modal === null) {
log('QuotePostPipeline is not deployed');
return;
}
this.#eventKeeper.cancelAll();
this.#modal = this.#contentEditable = null;
}
onPaste(event: ClipboardEvent): void {
if (!event.clipboardData || !this.#contentEditable) return;
if (event.clipboardData.types.indexOf('text/plain') === -1) return;
event.preventDefault();
const contentEditable = this.#contentEditable;
let data = event.clipboardData.getData('text/plain');
if (data.match(STAGING_URL_REGEX) !== null) {
data = data.replace('https://staging.bsky.app/', 'https://bsky.app/');
}
contentEditable.focus();
typeText(data);
typeText(' '); // Add a space after the link for it to resolve as one
// Wait for the text to be inserted into the contentEditable
setTimeout(() => {
const lastChar = contentEditable.textContent?.slice(-1) ?? '';
if ( | lastChar === ' ') backspace(); |
if (data.match(URL_REGEX) !== null) {
this.#modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => {
linkCardButton.click();
});
}
}, 50);
}
}
| src/content/pipelines/quotePost.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});\n } else {\n tip('No new posts to load');\n }\n } catch {\n tip('You are not on the feed page');\n }\n }\n async #newPost(): Promise<void> {\n const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);",
"score": 0.7696452140808105
},
{
"filename": "src/content/main.ts",
"retrieved_chunk": " log('Launched');\n}).catch(() => {\n setTimeout(() => {\n run().then(() => {\n log('Launched after the second attempt (1000ms delay)');\n }).catch((e) => {\n if (e === EXTENSION_DISABLED_CODE) return;\n console.error(`Failed to launch Bluesky Overhaul. Please, copy the error and report this issue: ${REPO_LINK}`);\n console.error(e);\n });",
"score": 0.7489386796951294
},
{
"filename": "src/content/utils/selection.ts",
"retrieved_chunk": " node = node.parentNode as Node;\n }\n return false;\n};\nexport const getCurrentCursorPosition = (parentElement: HTMLElement): number => {\n const selection = window.getSelection();\n let charCount = -1;\n let node = null;\n if (selection && selection.focusNode) {\n if (isChildOf(selection.focusNode, parentElement)) {",
"score": 0.7470155358314514
},
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " this.#elems.contentEditable.focus();\n }\n };\n this.#modal?.addEventListener('click', clickOutside);\n document.addEventListener('click', clickOutside);\n }\n #removeElements(): void {\n for (const element of Object.values(this.#elems)) {\n try {\n if (element.parentElement) {",
"score": 0.7450802326202393
},
{
"filename": "src/content/utils/selection.ts",
"retrieved_chunk": " } else if (node && node.textContent && chars.count > 0) {\n if (node.nodeType === Node.TEXT_NODE) {\n if (node.textContent.length < chars.count) {\n chars.count -= node.textContent.length;\n } else {\n range.setEnd(node, chars.count);\n chars.count = 0;\n }\n } else {\n for (let lp = 0; lp < node.childNodes.length; lp++) {",
"score": 0.7422954440116882
}
] | typescript | lastChar === ' ') backspace(); |
import '@webcomponents/custom-elements';
import {APP_SETTINGS} from '../shared/appSettings';
import {getSettingsManager} from './browser/settingsManager';
import {ultimatelyFind} from './dom/utils';
import {ROOT_CONTAINER, FEED_CONTAINER, MODAL_CONTAINER, COMPOSE_MODAL} from './dom/selectors';
import {CountersConcealer} from './watchers/countersConcealer';
import {KeydownWatcher} from './watchers/keydown';
import {PostDatetimeWatcher} from './watchers/postDatetime';
import {YoutubeWatcher} from './watchers/youtube';
import {PostModalPipeline} from './pipelines/postModal';
import {EmojiPipeline} from './pipelines/emoji';
import {QuotePostPipeline} from './pipelines/quotePost';
import {log} from './utils/logger';
import {PipelineManager} from './utils/pipelineManager';
const REPO_LINK = 'https://github.com/xenohunter/bluesky-overhaul';
const EXTENSION_DISABLED_CODE = 'EXTENSION_DISABLED';
const run = async (): Promise<void> => {
const settingsManager = await getSettingsManager();
if (settingsManager.get(APP_SETTINGS.BLUESKY_OVERHAUL_ENABLED) === false) {
return Promise.reject(EXTENSION_DISABLED_CODE);
}
return ultimatelyFind(document.body, ROOT_CONTAINER).then((rootContainer) => Promise.all([
Promise.resolve(rootContainer),
ultimatelyFind(rootContainer, FEED_CONTAINER),
ultimatelyFind(rootContainer, MODAL_CONTAINER)
]).then(([rootContainer, feedContainer, modalContainer]) => {
const countersConcealer = new CountersConcealer(document.body);
settingsManager.subscribe(countersConcealer);
countersConcealer.watch();
const keydownWatcher = new KeydownWatcher(rootContainer, feedContainer);
settingsManager.subscribe(keydownWatcher);
keydownWatcher.watch();
const postDatetimeWatcher = new PostDatetimeWatcher(feedContainer);
settingsManager.subscribe(postDatetimeWatcher);
postDatetimeWatcher.watch();
const youtubeWatcher = new YoutubeWatcher(feedContainer);
youtubeWatcher.watch();
const postModalPipeline = new PostModalPipeline(() => keydownWatcher.pause(), () => keydownWatcher.start());
const emojiPipeline = new EmojiPipeline(() => postModalPipeline.pause(), () => postModalPipeline.start());
const quotePostPipeline = new QuotePostPipeline();
const pipelineManager = new PipelineManager({
compose: [postModalPipeline, emojiPipeline, quotePostPipeline]
});
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.target === modalContainer) {
| const composePostModal = modalContainer.querySelector(COMPOSE_MODAL.selector) as HTMLElement | null; |
if (composePostModal !== null) {
pipelineManager.terminateExcept('compose');
pipelineManager.deploy('compose', composePostModal);
} else {
pipelineManager.terminateAll();
}
}
});
});
observer.observe(modalContainer, {childList: true, subtree: true});
}));
};
run().then(() => {
log('Launched');
}).catch(() => {
setTimeout(() => {
run().then(() => {
log('Launched after the second attempt (1000ms delay)');
}).catch((e) => {
if (e === EXTENSION_DISABLED_CODE) return;
console.error(`Failed to launch Bluesky Overhaul. Please, copy the error and report this issue: ${REPO_LINK}`);
console.error(e);
});
}, 1000);
});
| src/content/main.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " this.#pauseOuterServices = pauseCallback;\n this.#resumeOuterServices = resumeCallback;\n }\n deploy(modal: HTMLElement): void {\n if (this.#modal !== null) {\n log('PostModalPipeline is already deployed');\n return;\n }\n this.#pauseOuterServices();\n this.#modal = modal;",
"score": 0.7842129468917847
},
{
"filename": "src/content/pipelines/quotePost.ts",
"retrieved_chunk": " log('QuotePostPipeline is already deployed');\n return;\n }\n this.#modal = modal;\n ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE).then((contentEditable) => {\n this.#contentEditable = contentEditable;\n this.#eventKeeper.add(contentEditable, 'paste', this.onPaste.bind(this), {capture: true});\n });\n }\n terminate(): void {",
"score": 0.7728175520896912
},
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " this.#eventKeeper = new EventKeeper();\n this.#elems = {};\n this.#expanded = false;\n this.#pauseOuterServices = pauseCallback;\n this.#resumeOuterServices = resumeCallback;\n }\n deploy(modal: HTMLElement): void {\n if (this.#modal !== null) {\n log('EmojiPipeline already deployed');\n return;",
"score": 0.7618546485900879
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " #findSearchBar(): Promise<HTMLElement> {\n return ultimatelyFind(document.body, SEARCH_BAR);\n }\n async #loadNewPosts(): Promise<void> {\n try {\n const tab = await this.#postList.getCurrentFeedTab();\n const tabContainer = await ultimatelyFind(this.#container, tab);\n const newPostsButton = tabContainer.childNodes[1] as HTMLElement;\n if (newPostsButton && newPostsButton.nextSibling) {\n newPostsButton.click();",
"score": 0.7574253082275391
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " return this.#activeTabSelector.clone();\n } else {\n return Promise.reject('Not on main page');\n }\n });\n }\n setCurrentPost(element: HTMLElement): Promise<HTMLElement> {\n return this.#resolveList().then((posts) => {\n for (const post of posts) {\n if (post === element || post.parentElement === element || post.contains(element)) {",
"score": 0.7475563287734985
}
] | typescript | const composePostModal = modalContainer.querySelector(COMPOSE_MODAL.selector) as HTMLElement | null; |
import {IPausable} from '../../../interfaces';
import {ROOT_CONTAINER, SEARCH_BAR} from '../../dom/selectors';
import {EventKeeper} from '../../utils/eventKeeper';
import {noop} from '../../../shared/misc';
import {modal, tip} from '../../utils/notifications';
import {PostList} from './postList';
import {generateHelpMessage, VIM_ACTIONS, VIM_KEY_MAP} from './vimActions';
import {ultimatelyFind} from '../../dom/utils';
enum DIRECTION { NEXT, PREVIOUS }
const FOCUSED_POST_CLASS = 'bluesky-overhaul-focused-post';
const MISSING_POST_ERROR = 'No post is focused';
const REPLY_BUTTON_SELECTOR = '[data-testid="replyBtn"]';
const REPOST_BUTTON_SELECTOR = '[data-testid="repostBtn"]';
const LIKE_BUTTON_SELECTOR = '[data-testid="likeBtn"]';
export class VimKeybindingsHandler implements IPausable {
readonly #container: HTMLElement;
readonly #postList: PostList;
readonly #postClickEventKeeper = new EventKeeper();
readonly #searchBarEventKeeper = new EventKeeper();
#currentPost: HTMLElement | null = null;
#stashedPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#postList = new PostList(targetContainer, startPaused);
this.#isPaused = startPaused;
}
start(): void {
if (!this.#isPaused) return;
this.#postList.start();
this.#postClickEventKeeper.add(this.#container, 'click', this.#onPostAltClick.bind(this));
this.#blurSearchBar();
this.#isPaused = false;
}
pause(): void {
if (this.#isPaused) return;
this.#postList.pause();
this.#postClickEventKeeper.cancelAll();
this.#searchBarEventKeeper.cancelAll();
this.#removeHighlight();
this.#isPaused = true;
}
handle(event: KeyboardEvent): void {
if (this.#isPaused) return;
event.preventDefault();
const key = event.key;
if (!(key in VIM_KEY_MAP)) return;
const action = VIM_KEY_MAP[key as keyof typeof VIM_KEY_MAP];
switch (action) {
case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage());
break;
case VIM_ACTIONS.SEARCH:
this.#focusSearchBar();
break;
case VIM_ACTIONS.LOAD_NEW_POSTS:
this.#loadNewPosts();
break;
case VIM_ACTIONS.NEXT_POST:
this.#selectPost(DIRECTION.NEXT);
break;
case VIM_ACTIONS.PREVIOUS_POST:
this.#selectPost(DIRECTION.PREVIOUS);
break;
case VIM_ACTIONS.LIKE:
this.#likePost();
break;
case VIM_ACTIONS.CREATE_POST:
this.#newPost();
break;
case VIM_ACTIONS.EXPAND_IMAGE:
this.#expandImage();
break;
case VIM_ACTIONS.REPLY:
this.#replyToPost();
break;
case VIM_ACTIONS.REPOST:
this.#repostPost();
break;
case VIM_ACTIONS.OPEN_POST:
this.#currentPost?.click();
break;
default:
tip(`Action "${action}" is not implemented yet`);
}
}
#selectPost(direction: DIRECTION): void {
if (direction === DIRECTION.NEXT) {
this.#postList.getNextPost().then((p) => this.#highlightPost(p));
} else {
this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));
}
}
#replyToPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;
reply?.click();
}
#repostPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;
repost?.click();
}
#likePost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;
like?.click();
}
#expandImage(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const imageContainer = this.#currentPost.querySelector('div.expo-image-container') as HTMLElement;
imageContainer?.click();
}
#onPostAltClick(event: MouseEvent): void {
if (this.#isPaused || !event.altKey) return;
event.preventDefault();
this.#postList.setCurrentPost(event.target as HTMLElement).then((p) => this.#highlightPost(p)).catch(noop);
}
#highlightPost(post: HTMLElement): void {
if (post === this.#currentPost) return;
this.#removeHighlight();
this.#stashedPost = null;
this.#currentPost = post;
this.#currentPost.classList.add(FOCUSED_POST_CLASS);
this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});
}
#removeHighlight(): void {
this.#stashedPost = this.#currentPost;
this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);
this.#currentPost = null;
}
#focusSearchBar(): void {
this.#removeHighlight();
this.#findSearchBar().then((searchBar) => {
this.#searchBarEventKeeper.cancelAll();
searchBar.focus();
this.#searchBarEventKeeper.add(searchBar, 'blur', this.#blurSearchBar.bind(this));
this.#searchBarEventKeeper.add(searchBar, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') searchBar.blur();
});
}).catch(() => tip('Search bar not found'));
}
#blurSearchBar(): void {
this.#searchBarEventKeeper.cancelAll();
this.#findSearchBar().then((searchBar) => {
searchBar.blur();
this.#stashedPost && this.#highlightPost(this.#stashedPost);
this.#searchBarEventKeeper.add(searchBar, 'focus', this.#focusSearchBar.bind(this));
});
}
#findSearchBar(): Promise<HTMLElement> {
return ultimatelyFind(document.body, SEARCH_BAR);
}
async #loadNewPosts(): Promise<void> {
try {
const tab = await this.#postList.getCurrentFeedTab();
const tabContainer = await ultimatelyFind(this.#container, tab);
const newPostsButton = tabContainer.childNodes[1] as HTMLElement;
if (newPostsButton && newPostsButton.nextSibling) {
newPostsButton.click();
this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});
} else {
tip('No new posts to load');
}
} catch {
tip('You are not on the feed page');
}
}
async #newPost(): Promise<void> {
| const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER); |
const children = rootContainer.childNodes;
const menuItems = children[1].childNodes;
const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;
if (newPostButton) {
newPostButton.click();
} else {
tip('No new post button found');
}
}
}
| src/content/watchers/helpers/vimKeybindings.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " return this.#activeTabSelector.clone();\n } else {\n return Promise.reject('Not on main page');\n }\n });\n }\n setCurrentPost(element: HTMLElement): Promise<HTMLElement> {\n return this.#resolveList().then((posts) => {\n for (const post of posts) {\n if (post === element || post.parentElement === element || post.contains(element)) {",
"score": 0.8377470374107361
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " const prefixingSelectors = isMainPage ? [this.#activeTabSelector] : [];\n return this.#findElements([...prefixingSelectors, POST_ITEMS]).then((posts) => {\n if (posts.length === 0) {\n return Promise.reject('No posts found');\n } else {\n return posts;\n }\n });\n });\n }",
"score": 0.8067134022712708
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " this.#currentPost = post;\n return this.#currentPost;\n }\n }\n return Promise.reject('Element is not a post');\n });\n }\n getNextPost(): Promise<HTMLElement> {\n return this.#getNeighborPost(getNextPost);\n }",
"score": 0.7903561592102051
},
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " element.parentElement.removeChild(element);\n } else {\n element.remove();\n }\n } catch (e) {\n noop();\n }\n }\n this.#elems = {};\n }",
"score": 0.777489960193634
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": "const WHATSHOT_FEED = new Selector('[data-testid=\"whatshotFeedPage\"]');\nconst getNextPost = (post: HTMLElement): HTMLElement | null => {\n if (post.nextSibling) {\n return post.nextSibling as HTMLElement;\n } else {\n const parent = post.parentElement;\n if (parent && parent.nextSibling) {\n return parent.nextSibling.firstChild as HTMLElement;\n } else {\n return null;",
"score": 0.7744110226631165
}
] | typescript | const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER); |
import { createPopper } from '@popperjs/core';
import {TSetting, TSettings} from '../../types';
import {APP_SETTINGS} from '../../shared/appSettings';
import {ISettingsSubscriber} from '../../interfaces';
import {Watcher} from './watcher';
import {getSettingsManager} from '../browser/settingsManager';
import {getAgent, fetchPost, LoginError} from '../bsky/api';
import {alert} from '../utils/notifications';
const DEFAULT_SETTINGS: Partial<TSettings> = {
[APP_SETTINGS.SHOW_POST_DATETIME]: false,
[APP_SETTINGS.BSKY_IDENTIFIER]: '',
[APP_SETTINGS.BSKY_PASSWORD]: ''
};
type PostUrl = {
username: string;
postId: string;
};
const POST_HREF_REGEX = /profile\/(.+)\/post\/([a-zA-Z0-9]+)$/;
const DATETIME_MARKER = 'data-bluesky-overhaul-datetime';
const getCredentials = async (): Promise<[string, string]> => {
const settingsManager = await getSettingsManager();
return await Promise.all([
settingsManager.get(APP_SETTINGS.BSKY_IDENTIFIER) as string,
settingsManager.get(APP_SETTINGS.BSKY_PASSWORD) as string
]);
};
const parsePostUrl = (url: string | null): PostUrl => {
if (!url) throw new Error('Missing post URL');
const match = url.match(POST_HREF_REGEX);
if (!match) throw new Error('Invalid post URL');
return {username: match[1], postId: match[2]};
};
const parsePostDatetime = (datetime: string): string => {
const date = new Date(datetime);
return date.toLocaleString('en-US', {
month: 'long', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'
});
};
const createDatetimeTooltip = (datetime: string): HTMLElement => {
const tooltip = document.createElement('div');
tooltip.role = 'tooltip';
tooltip.className = 'bluesky-overhaul-tooltip';
tooltip.textContent = datetime;
return tooltip;
};
export class | PostDatetimeWatcher extends Watcher implements ISettingsSubscriber { |
#container: HTMLElement;
#enabled: boolean;
constructor(container: HTMLElement) {
super();
this.#container = container;
this.#enabled = DEFAULT_SETTINGS[APP_SETTINGS.SHOW_POST_DATETIME] as boolean;
}
watch(): void {
this.#container.addEventListener('mouseover', this.#handleMouseOver.bind(this));
}
onSettingChange(name: APP_SETTINGS, value: TSetting): void {
if (!this.SETTINGS.includes(name)) throw new Error(`Unknown setting name "${name}"`);
if (typeof value !== typeof DEFAULT_SETTINGS[name]) throw new Error(`Invalid value "${value}" for "${name}"`);
if (name === APP_SETTINGS.SHOW_POST_DATETIME) {
this.#enabled = value as boolean;
}
}
get SETTINGS(): APP_SETTINGS[] {
return Object.keys(DEFAULT_SETTINGS) as APP_SETTINGS[];
}
async #handleMouseOver(event: MouseEvent): Promise<void> {
if (!this.#enabled) return;
const target = event.target as HTMLElement;
if (target.tagName.toLowerCase() !== 'a') return;
let datetime = target.getAttribute(DATETIME_MARKER);
if (!datetime) {
try {
const {username, postId} = parsePostUrl(target.getAttribute('href'));
if (username && postId) {
const [identifier, password] = await getCredentials();
try {
const agent = await getAgent(identifier, password);
const post = await fetchPost(agent, username, postId);
datetime = parsePostDatetime(post.indexedAt);
target.setAttribute(DATETIME_MARKER, datetime);
} catch (error) {
if (error instanceof LoginError) alert('Login failed: wrong identifier or password');
return;
}
} else {
return;
}
} catch {
return;
}
}
const tooltip = createDatetimeTooltip(datetime);
document.body.appendChild(tooltip);
const instance = createPopper(target, tooltip, {
placement: 'top'
});
target.addEventListener('mouseleave', () => {
instance.destroy();
tooltip.remove();
}, {once: true});
}
}
| src/content/watchers/postDatetime.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": "const EMOJI_CHARACTER_LENGTH = 2;\nconst createEmojiButton = (rightmostButton: HTMLElement): HTMLElement => {\n const emojiButton = rightmostButton.cloneNode(false) as HTMLElement;\n emojiButton.innerHTML = '😀';\n return emojiButton;\n};\nconst createEmojiPopup = (modal: HTMLElement, emojiButton: HTMLElement): HTMLElement => {\n const emojiPopup = document.createElement('div');\n emojiPopup.style.position = 'absolute';\n emojiPopup.style.display = 'none';",
"score": 0.7972909808158875
},
{
"filename": "src/popup/components/Checkbox.tsx",
"retrieved_chunk": "import React, {useState} from 'react';\nimport Badge, {BADGE_LEVEL} from './Badge';\nimport Tip from './Tip';\ntype CheckboxProps = {\n value: boolean;\n text: string;\n badge?: { text: string, type: BADGE_LEVEL };\n tooltip?: string;\n callback: (value: boolean) => void;\n};",
"score": 0.7483447790145874
},
{
"filename": "src/popup/components/Tip.tsx",
"retrieved_chunk": "import React from 'react';\ntype TipProps = {\n text: string;\n};\nexport default function Tip({text}: TipProps): JSX.Element {\n return (\n <div>\n <small>{text}</small>\n </div>\n );",
"score": 0.7391770482063293
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " } else {\n return null;\n }\n }\n};\nconst isPostThreadDelimiter = (postCandidate: HTMLElement): boolean => {\n return postCandidate.getAttribute('role') === 'link' && postCandidate.getAttribute('tabindex') === '0';\n};\nexport class PostList implements IPausable {\n readonly #container: HTMLElement;",
"score": 0.7329127788543701
},
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " const modalCoords = modal.getBoundingClientRect();\n const emojiButtonCoords = emojiButton.getBoundingClientRect();\n emojiPopup.style.left = emojiButtonCoords.x - modalCoords.x + 'px';\n emojiPopup.style.top = emojiButtonCoords.y - modalCoords.y + emojiButtonCoords.height + 'px';\n return emojiPopup;\n};\nexport class EmojiPipeline extends Pipeline {\n #modal: HTMLElement | null;\n #picker: Picker | null;\n #cursor: Cursor | null;",
"score": 0.7297081351280212
}
] | typescript | PostDatetimeWatcher extends Watcher implements ISettingsSubscriber { |
import {IPausable} from '../../../interfaces';
import {ROOT_CONTAINER, SEARCH_BAR} from '../../dom/selectors';
import {EventKeeper} from '../../utils/eventKeeper';
import {noop} from '../../../shared/misc';
import {modal, tip} from '../../utils/notifications';
import {PostList} from './postList';
import {generateHelpMessage, VIM_ACTIONS, VIM_KEY_MAP} from './vimActions';
import {ultimatelyFind} from '../../dom/utils';
enum DIRECTION { NEXT, PREVIOUS }
const FOCUSED_POST_CLASS = 'bluesky-overhaul-focused-post';
const MISSING_POST_ERROR = 'No post is focused';
const REPLY_BUTTON_SELECTOR = '[data-testid="replyBtn"]';
const REPOST_BUTTON_SELECTOR = '[data-testid="repostBtn"]';
const LIKE_BUTTON_SELECTOR = '[data-testid="likeBtn"]';
export class VimKeybindingsHandler implements IPausable {
readonly #container: HTMLElement;
readonly #postList: PostList;
readonly #postClickEventKeeper = new EventKeeper();
readonly #searchBarEventKeeper = new EventKeeper();
#currentPost: HTMLElement | null = null;
#stashedPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#postList = new PostList(targetContainer, startPaused);
this.#isPaused = startPaused;
}
start(): void {
if (!this.#isPaused) return;
this.#postList.start();
this.#postClickEventKeeper.add(this.#container, 'click', this.#onPostAltClick.bind(this));
this.#blurSearchBar();
this.#isPaused = false;
}
pause(): void {
if (this.#isPaused) return;
this.#postList.pause();
this.#postClickEventKeeper.cancelAll();
this.#searchBarEventKeeper.cancelAll();
this.#removeHighlight();
this.#isPaused = true;
}
handle(event: KeyboardEvent): void {
if (this.#isPaused) return;
event.preventDefault();
const key = event.key;
if (!(key in VIM_KEY_MAP)) return;
const action = VIM_KEY_MAP[key as keyof typeof VIM_KEY_MAP];
switch (action) {
case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage());
break;
case VIM_ACTIONS.SEARCH:
this.#focusSearchBar();
break;
case VIM_ACTIONS.LOAD_NEW_POSTS:
this.#loadNewPosts();
break;
case VIM_ACTIONS.NEXT_POST:
this.#selectPost(DIRECTION.NEXT);
break;
case VIM_ACTIONS.PREVIOUS_POST:
this.#selectPost(DIRECTION.PREVIOUS);
break;
case VIM_ACTIONS.LIKE:
this.#likePost();
break;
case VIM_ACTIONS.CREATE_POST:
this.#newPost();
break;
case VIM_ACTIONS.EXPAND_IMAGE:
this.#expandImage();
break;
case VIM_ACTIONS.REPLY:
this.#replyToPost();
break;
case VIM_ACTIONS.REPOST:
this.#repostPost();
break;
case VIM_ACTIONS.OPEN_POST:
this.#currentPost?.click();
break;
default:
tip(`Action "${action}" is not implemented yet`);
}
}
#selectPost(direction: DIRECTION): void {
if (direction === DIRECTION.NEXT) {
this.#postList.getNextPost() | .then((p) => this.#highlightPost(p)); |
} else {
this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));
}
}
#replyToPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;
reply?.click();
}
#repostPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;
repost?.click();
}
#likePost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;
like?.click();
}
#expandImage(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const imageContainer = this.#currentPost.querySelector('div.expo-image-container') as HTMLElement;
imageContainer?.click();
}
#onPostAltClick(event: MouseEvent): void {
if (this.#isPaused || !event.altKey) return;
event.preventDefault();
this.#postList.setCurrentPost(event.target as HTMLElement).then((p) => this.#highlightPost(p)).catch(noop);
}
#highlightPost(post: HTMLElement): void {
if (post === this.#currentPost) return;
this.#removeHighlight();
this.#stashedPost = null;
this.#currentPost = post;
this.#currentPost.classList.add(FOCUSED_POST_CLASS);
this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});
}
#removeHighlight(): void {
this.#stashedPost = this.#currentPost;
this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);
this.#currentPost = null;
}
#focusSearchBar(): void {
this.#removeHighlight();
this.#findSearchBar().then((searchBar) => {
this.#searchBarEventKeeper.cancelAll();
searchBar.focus();
this.#searchBarEventKeeper.add(searchBar, 'blur', this.#blurSearchBar.bind(this));
this.#searchBarEventKeeper.add(searchBar, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') searchBar.blur();
});
}).catch(() => tip('Search bar not found'));
}
#blurSearchBar(): void {
this.#searchBarEventKeeper.cancelAll();
this.#findSearchBar().then((searchBar) => {
searchBar.blur();
this.#stashedPost && this.#highlightPost(this.#stashedPost);
this.#searchBarEventKeeper.add(searchBar, 'focus', this.#focusSearchBar.bind(this));
});
}
#findSearchBar(): Promise<HTMLElement> {
return ultimatelyFind(document.body, SEARCH_BAR);
}
async #loadNewPosts(): Promise<void> {
try {
const tab = await this.#postList.getCurrentFeedTab();
const tabContainer = await ultimatelyFind(this.#container, tab);
const newPostsButton = tabContainer.childNodes[1] as HTMLElement;
if (newPostsButton && newPostsButton.nextSibling) {
newPostsButton.click();
this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});
} else {
tip('No new posts to load');
}
} catch {
tip('You are not on the feed page');
}
}
async #newPost(): Promise<void> {
const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);
const children = rootContainer.childNodes;
const menuItems = children[1].childNodes;
const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;
if (newPostButton) {
newPostButton.click();
} else {
tip('No new post button found');
}
}
}
| src/content/watchers/helpers/vimKeybindings.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " return this.#activeTabSelector.clone();\n } else {\n return Promise.reject('Not on main page');\n }\n });\n }\n setCurrentPost(element: HTMLElement): Promise<HTMLElement> {\n return this.#resolveList().then((posts) => {\n for (const post of posts) {\n if (post === element || post.parentElement === element || post.contains(element)) {",
"score": 0.821479082107544
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " this.#currentPost = post;\n return this.#currentPost;\n }\n }\n return Promise.reject('Element is not a post');\n });\n }\n getNextPost(): Promise<HTMLElement> {\n return this.#getNeighborPost(getNextPost);\n }",
"score": 0.7998953461647034
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " getPreviousPost(): Promise<HTMLElement> {\n return this.#getNeighborPost(getPreviousPost);\n }\n #getNeighborPost(retrieveFn: (post: HTMLElement) => HTMLElement | null): Promise<HTMLElement> {\n if (this.#isPaused) return Promise.reject('PostList is paused');\n return this.#resolveList().then((posts) => {\n if (posts.length === 0) {\n return Promise.reject('No posts found');\n } else if (this.#currentPost) {\n const neighborPost = retrieveFn(this.#currentPost);",
"score": 0.7956687211990356
},
{
"filename": "src/content/watchers/postDatetime.ts",
"retrieved_chunk": " this.#enabled = value as boolean;\n }\n }\n get SETTINGS(): APP_SETTINGS[] {\n return Object.keys(DEFAULT_SETTINGS) as APP_SETTINGS[];\n }\n async #handleMouseOver(event: MouseEvent): Promise<void> {\n if (!this.#enabled) return;\n const target = event.target as HTMLElement;\n if (target.tagName.toLowerCase() !== 'a') return;",
"score": 0.7767153978347778
},
{
"filename": "src/content/pipelines/quotePost.ts",
"retrieved_chunk": " setTimeout(() => {\n const lastChar = contentEditable.textContent?.slice(-1) ?? '';\n if (lastChar === ' ') backspace();\n if (data.match(URL_REGEX) !== null) {\n this.#modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => {\n linkCardButton.click();\n });\n }\n }, 50);\n }",
"score": 0.7670503258705139
}
] | typescript | .then((p) => this.#highlightPost(p)); |
import {IPausable} from '../../../interfaces';
import {ROOT_CONTAINER, SEARCH_BAR} from '../../dom/selectors';
import {EventKeeper} from '../../utils/eventKeeper';
import {noop} from '../../../shared/misc';
import {modal, tip} from '../../utils/notifications';
import {PostList} from './postList';
import {generateHelpMessage, VIM_ACTIONS, VIM_KEY_MAP} from './vimActions';
import {ultimatelyFind} from '../../dom/utils';
enum DIRECTION { NEXT, PREVIOUS }
const FOCUSED_POST_CLASS = 'bluesky-overhaul-focused-post';
const MISSING_POST_ERROR = 'No post is focused';
const REPLY_BUTTON_SELECTOR = '[data-testid="replyBtn"]';
const REPOST_BUTTON_SELECTOR = '[data-testid="repostBtn"]';
const LIKE_BUTTON_SELECTOR = '[data-testid="likeBtn"]';
export class VimKeybindingsHandler implements IPausable {
readonly #container: HTMLElement;
readonly #postList: PostList;
readonly #postClickEventKeeper = new EventKeeper();
readonly #searchBarEventKeeper = new EventKeeper();
#currentPost: HTMLElement | null = null;
#stashedPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#postList = new PostList(targetContainer, startPaused);
this.#isPaused = startPaused;
}
start(): void {
if (!this.#isPaused) return;
this.#postList.start();
this.#postClickEventKeeper.add(this.#container, 'click', this.#onPostAltClick.bind(this));
this.#blurSearchBar();
this.#isPaused = false;
}
pause(): void {
if (this.#isPaused) return;
this.#postList.pause();
this.#postClickEventKeeper.cancelAll();
this.#searchBarEventKeeper.cancelAll();
this.#removeHighlight();
this.#isPaused = true;
}
handle(event: KeyboardEvent): void {
if (this.#isPaused) return;
event.preventDefault();
const key = event.key;
| if (!(key in VIM_KEY_MAP)) return; |
const action = VIM_KEY_MAP[key as keyof typeof VIM_KEY_MAP];
switch (action) {
case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage());
break;
case VIM_ACTIONS.SEARCH:
this.#focusSearchBar();
break;
case VIM_ACTIONS.LOAD_NEW_POSTS:
this.#loadNewPosts();
break;
case VIM_ACTIONS.NEXT_POST:
this.#selectPost(DIRECTION.NEXT);
break;
case VIM_ACTIONS.PREVIOUS_POST:
this.#selectPost(DIRECTION.PREVIOUS);
break;
case VIM_ACTIONS.LIKE:
this.#likePost();
break;
case VIM_ACTIONS.CREATE_POST:
this.#newPost();
break;
case VIM_ACTIONS.EXPAND_IMAGE:
this.#expandImage();
break;
case VIM_ACTIONS.REPLY:
this.#replyToPost();
break;
case VIM_ACTIONS.REPOST:
this.#repostPost();
break;
case VIM_ACTIONS.OPEN_POST:
this.#currentPost?.click();
break;
default:
tip(`Action "${action}" is not implemented yet`);
}
}
#selectPost(direction: DIRECTION): void {
if (direction === DIRECTION.NEXT) {
this.#postList.getNextPost().then((p) => this.#highlightPost(p));
} else {
this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));
}
}
#replyToPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;
reply?.click();
}
#repostPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;
repost?.click();
}
#likePost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;
like?.click();
}
#expandImage(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const imageContainer = this.#currentPost.querySelector('div.expo-image-container') as HTMLElement;
imageContainer?.click();
}
#onPostAltClick(event: MouseEvent): void {
if (this.#isPaused || !event.altKey) return;
event.preventDefault();
this.#postList.setCurrentPost(event.target as HTMLElement).then((p) => this.#highlightPost(p)).catch(noop);
}
#highlightPost(post: HTMLElement): void {
if (post === this.#currentPost) return;
this.#removeHighlight();
this.#stashedPost = null;
this.#currentPost = post;
this.#currentPost.classList.add(FOCUSED_POST_CLASS);
this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});
}
#removeHighlight(): void {
this.#stashedPost = this.#currentPost;
this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);
this.#currentPost = null;
}
#focusSearchBar(): void {
this.#removeHighlight();
this.#findSearchBar().then((searchBar) => {
this.#searchBarEventKeeper.cancelAll();
searchBar.focus();
this.#searchBarEventKeeper.add(searchBar, 'blur', this.#blurSearchBar.bind(this));
this.#searchBarEventKeeper.add(searchBar, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') searchBar.blur();
});
}).catch(() => tip('Search bar not found'));
}
#blurSearchBar(): void {
this.#searchBarEventKeeper.cancelAll();
this.#findSearchBar().then((searchBar) => {
searchBar.blur();
this.#stashedPost && this.#highlightPost(this.#stashedPost);
this.#searchBarEventKeeper.add(searchBar, 'focus', this.#focusSearchBar.bind(this));
});
}
#findSearchBar(): Promise<HTMLElement> {
return ultimatelyFind(document.body, SEARCH_BAR);
}
async #loadNewPosts(): Promise<void> {
try {
const tab = await this.#postList.getCurrentFeedTab();
const tabContainer = await ultimatelyFind(this.#container, tab);
const newPostsButton = tabContainer.childNodes[1] as HTMLElement;
if (newPostsButton && newPostsButton.nextSibling) {
newPostsButton.click();
this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});
} else {
tip('No new posts to load');
}
} catch {
tip('You are not on the feed page');
}
}
async #newPost(): Promise<void> {
const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);
const children = rootContainer.childNodes;
const menuItems = children[1].childNodes;
const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;
if (newPostButton) {
newPostButton.click();
} else {
tip('No new post button found');
}
}
}
| src/content/watchers/helpers/vimKeybindings.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/keydown.ts",
"retrieved_chunk": " this.#vimHandler = new VimKeybindingsHandler(vimContainer, true);\n }\n watch(): void {\n document.addEventListener('keydown', this.#onKeydown.bind(this));\n }\n start(): void {\n if (!this.#isPaused) return;\n this.#vimHandler.start();\n this.#isPaused = false;\n }",
"score": 0.8546032309532166
},
{
"filename": "src/content/pipelines/quotePost.ts",
"retrieved_chunk": " if (this.#modal === null) {\n log('QuotePostPipeline is not deployed');\n return;\n }\n this.#eventKeeper.cancelAll();\n this.#modal = this.#contentEditable = null;\n }\n onPaste(event: ClipboardEvent): void {\n if (!event.clipboardData || !this.#contentEditable) return;\n if (event.clipboardData.types.indexOf('text/plain') === -1) return;",
"score": 0.8208337426185608
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " }\n start(): void {\n this.#paused = false;\n }\n pause(): void {\n this.#paused = true;\n }\n #onClick(event: MouseEvent): void {\n if (this.#paused) return;\n const target = event.target as HTMLElement;",
"score": 0.816125750541687
},
{
"filename": "src/content/watchers/keydown.ts",
"retrieved_chunk": " pause(): void {\n if (this.#isPaused) return;\n this.#vimHandler.pause();\n this.#isPaused = true;\n }\n onSettingChange(name: APP_SETTINGS, value: TSetting): void {\n if (!this.SETTINGS.includes(name)) throw new Error(`Unknown setting name \"${name}\"`);\n if (typeof value !== typeof DEFAULT_SETTINGS[name]) throw new Error(`Invalid value \"${value}\" for \"${name}\"`);\n if (name === APP_SETTINGS.HANDLE_VIM_KEYBINDINGS) {\n if (value === true) {",
"score": 0.8038820028305054
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " if (target?.tagName.toLowerCase() === 'button') return;\n if (!this.#modal?.contains(event.target as Node) && event.target !== this.#exitButton) {\n this.#eventKeeper.cancelAll();\n this.#exitButton?.click();\n }\n }\n #onPresumedSelect(): void {\n if (this.#paused) return;\n this.pause();\n document.addEventListener('mouseup', () => setTimeout(this.start.bind(this), 0), {once: true});",
"score": 0.7894888520240784
}
] | typescript | if (!(key in VIM_KEY_MAP)) return; |
import {IPausable} from '../../../interfaces';
import {ROOT_CONTAINER, SEARCH_BAR} from '../../dom/selectors';
import {EventKeeper} from '../../utils/eventKeeper';
import {noop} from '../../../shared/misc';
import {modal, tip} from '../../utils/notifications';
import {PostList} from './postList';
import {generateHelpMessage, VIM_ACTIONS, VIM_KEY_MAP} from './vimActions';
import {ultimatelyFind} from '../../dom/utils';
enum DIRECTION { NEXT, PREVIOUS }
const FOCUSED_POST_CLASS = 'bluesky-overhaul-focused-post';
const MISSING_POST_ERROR = 'No post is focused';
const REPLY_BUTTON_SELECTOR = '[data-testid="replyBtn"]';
const REPOST_BUTTON_SELECTOR = '[data-testid="repostBtn"]';
const LIKE_BUTTON_SELECTOR = '[data-testid="likeBtn"]';
export class VimKeybindingsHandler implements IPausable {
readonly #container: HTMLElement;
readonly #postList: PostList;
readonly #postClickEventKeeper = new EventKeeper();
readonly #searchBarEventKeeper = new EventKeeper();
#currentPost: HTMLElement | null = null;
#stashedPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#postList = new PostList(targetContainer, startPaused);
this.#isPaused = startPaused;
}
start(): void {
if (!this.#isPaused) return;
this.#postList.start();
this.#postClickEventKeeper.add(this.#container, 'click', this.#onPostAltClick.bind(this));
this.#blurSearchBar();
this.#isPaused = false;
}
pause(): void {
if (this.#isPaused) return;
this.#postList.pause();
this.#postClickEventKeeper.cancelAll();
this.#searchBarEventKeeper.cancelAll();
this.#removeHighlight();
this.#isPaused = true;
}
handle(event: KeyboardEvent): void {
if (this.#isPaused) return;
event.preventDefault();
const key = event.key;
if (!(key in VIM_KEY_MAP)) return;
const action = VIM_KEY_MAP[key as keyof typeof VIM_KEY_MAP];
switch (action) {
case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage());
break;
case VIM_ACTIONS.SEARCH:
this.#focusSearchBar();
break;
case VIM_ACTIONS.LOAD_NEW_POSTS:
this.#loadNewPosts();
break;
case VIM_ACTIONS.NEXT_POST:
this.#selectPost(DIRECTION.NEXT);
break;
case VIM_ACTIONS.PREVIOUS_POST:
this.#selectPost(DIRECTION.PREVIOUS);
break;
case VIM_ACTIONS.LIKE:
this.#likePost();
break;
case VIM_ACTIONS.CREATE_POST:
this.#newPost();
break;
case VIM_ACTIONS.EXPAND_IMAGE:
this.#expandImage();
break;
case VIM_ACTIONS.REPLY:
this.#replyToPost();
break;
case VIM_ACTIONS.REPOST:
this.#repostPost();
break;
case VIM_ACTIONS.OPEN_POST:
this.#currentPost?.click();
break;
default:
tip(`Action "${action}" is not implemented yet`);
}
}
#selectPost(direction: DIRECTION): void {
if (direction === DIRECTION.NEXT) {
this.#postList.getNextPost().then((p) => this.#highlightPost(p));
} else {
this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));
}
}
#replyToPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;
reply?.click();
}
#repostPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;
repost?.click();
}
#likePost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;
like?.click();
}
#expandImage(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const imageContainer = this.#currentPost.querySelector('div.expo-image-container') as HTMLElement;
imageContainer?.click();
}
#onPostAltClick(event: MouseEvent): void {
if (this.#isPaused || !event.altKey) return;
event.preventDefault();
this.#postList.setCurrentPost(event.target as HTMLElement).then((p) => this.#highlightPost(p)).catch(noop);
}
#highlightPost(post: HTMLElement): void {
if (post === this.#currentPost) return;
this.#removeHighlight();
this.#stashedPost = null;
this.#currentPost = post;
this.#currentPost.classList.add(FOCUSED_POST_CLASS);
this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});
}
#removeHighlight(): void {
this.#stashedPost = this.#currentPost;
this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);
this.#currentPost = null;
}
#focusSearchBar(): void {
this.#removeHighlight();
this.#findSearchBar().then((searchBar) => {
this.#searchBarEventKeeper.cancelAll();
searchBar.focus();
this.#searchBarEventKeeper.add(searchBar, 'blur', this.#blurSearchBar.bind(this));
this.#searchBarEventKeeper.add(searchBar, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') searchBar.blur();
});
}).catch(() => tip('Search bar not found'));
}
#blurSearchBar(): void {
this.#searchBarEventKeeper.cancelAll();
this.#findSearchBar().then((searchBar) => {
searchBar.blur();
this.#stashedPost && this.#highlightPost(this.#stashedPost);
this.#searchBarEventKeeper.add(searchBar, 'focus', this.#focusSearchBar.bind(this));
});
}
#findSearchBar(): Promise<HTMLElement> {
| return ultimatelyFind(document.body, SEARCH_BAR); |
}
async #loadNewPosts(): Promise<void> {
try {
const tab = await this.#postList.getCurrentFeedTab();
const tabContainer = await ultimatelyFind(this.#container, tab);
const newPostsButton = tabContainer.childNodes[1] as HTMLElement;
if (newPostsButton && newPostsButton.nextSibling) {
newPostsButton.click();
this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});
} else {
tip('No new posts to load');
}
} catch {
tip('You are not on the feed page');
}
}
async #newPost(): Promise<void> {
const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);
const children = rootContainer.childNodes;
const menuItems = children[1].childNodes;
const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;
if (newPostButton) {
newPostButton.click();
} else {
tip('No new post button found');
}
}
}
| src/content/watchers/helpers/vimKeybindings.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " this.#focusOnPickerSearch();\n const clickOutside = (event: Event): void => {\n const target = event.target as HTMLElement;\n if (this.#elems.emojiPopup && !this.#elems.emojiPopup.contains(target) && target !== this.#elems.emojiButton) {\n this.#elems.emojiPopup.style.display = 'none';\n this.#clearPickerSearch();\n this.#expanded = false;\n this.#modal?.removeEventListener('click', clickOutside);\n document.removeEventListener('click', clickOutside);\n this.#resumeOuterServices();",
"score": 0.8297585248947144
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " Promise.all([\n ultimatelyFind(modal, COMPOSE_CANCEL_BUTTON),\n ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE)\n ]).then(([exitButton, contentEditable]) => {\n this.#exitButton = exitButton;\n this.#contentEditable = contentEditable;\n this.#eventKeeper.add(document, 'click', this.#onClick.bind(this));\n this.#eventKeeper.add(contentEditable, 'mousedown', this.#onPresumedSelect.bind(this));\n this.#eventKeeper.add(exitButton, 'click', () => this.#eventKeeper.cancelAll());\n });",
"score": 0.8269046545028687
},
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " }\n #getPickerSearch(): HTMLInputElement | null {\n const picker = this.#picker as unknown as HTMLElement;\n return picker.shadowRoot?.querySelector('input[type=\"search\"]') as HTMLInputElement;\n }\n #onButtonClick(): void {\n if (this.#expanded) return;\n this.#elems.emojiPopup.style.display = 'block';\n this.#expanded = true;\n this.#pauseOuterServices();",
"score": 0.8225964307785034
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " if (target?.tagName.toLowerCase() === 'button') return;\n if (!this.#modal?.contains(event.target as Node) && event.target !== this.#exitButton) {\n this.#eventKeeper.cancelAll();\n this.#exitButton?.click();\n }\n }\n #onPresumedSelect(): void {\n if (this.#paused) return;\n this.pause();\n document.addEventListener('mouseup', () => setTimeout(this.start.bind(this), 0), {once: true});",
"score": 0.8087381720542908
},
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " });\n }\n #focusOnPickerSearch(): void {\n if (!this.#picker) return;\n this.#getPickerSearch()?.focus();\n }\n #clearPickerSearch(): void {\n if (!this.#picker) return;\n const pickerSearch = this.#getPickerSearch();\n if (pickerSearch) pickerSearch.value = '';",
"score": 0.8014193773269653
}
] | typescript | return ultimatelyFind(document.body, SEARCH_BAR); |
import { createPopper } from '@popperjs/core';
import {TSetting, TSettings} from '../../types';
import {APP_SETTINGS} from '../../shared/appSettings';
import {ISettingsSubscriber} from '../../interfaces';
import {Watcher} from './watcher';
import {getSettingsManager} from '../browser/settingsManager';
import {getAgent, fetchPost, LoginError} from '../bsky/api';
import {alert} from '../utils/notifications';
const DEFAULT_SETTINGS: Partial<TSettings> = {
[APP_SETTINGS.SHOW_POST_DATETIME]: false,
[APP_SETTINGS.BSKY_IDENTIFIER]: '',
[APP_SETTINGS.BSKY_PASSWORD]: ''
};
type PostUrl = {
username: string;
postId: string;
};
const POST_HREF_REGEX = /profile\/(.+)\/post\/([a-zA-Z0-9]+)$/;
const DATETIME_MARKER = 'data-bluesky-overhaul-datetime';
const getCredentials = async (): Promise<[string, string]> => {
const settingsManager = await getSettingsManager();
return await Promise.all([
settingsManager.get(APP_SETTINGS.BSKY_IDENTIFIER) as string,
settingsManager.get(APP_SETTINGS.BSKY_PASSWORD) as string
]);
};
const parsePostUrl = (url: string | null): PostUrl => {
if (!url) throw new Error('Missing post URL');
const match = url.match(POST_HREF_REGEX);
if (!match) throw new Error('Invalid post URL');
return {username: match[1], postId: match[2]};
};
const parsePostDatetime = (datetime: string): string => {
const date = new Date(datetime);
return date.toLocaleString('en-US', {
month: 'long', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'
});
};
const createDatetimeTooltip = (datetime: string): HTMLElement => {
const tooltip = document.createElement('div');
tooltip.role = 'tooltip';
tooltip.className = 'bluesky-overhaul-tooltip';
tooltip.textContent = datetime;
return tooltip;
};
export class PostDatetimeWatcher extends Watcher implements ISettingsSubscriber {
#container: HTMLElement;
#enabled: boolean;
constructor(container: HTMLElement) {
super();
this.#container = container;
this.#enabled = DEFAULT_SETTINGS[APP_SETTINGS.SHOW_POST_DATETIME] as boolean;
}
watch(): void {
this.#container.addEventListener('mouseover', this.#handleMouseOver.bind(this));
}
onSettingChange(name: APP_SETTINGS, value: TSetting): void {
if (!this.SETTINGS.includes(name)) throw new Error(`Unknown setting name "${name}"`);
if (typeof value !== typeof DEFAULT_SETTINGS[name]) throw new Error(`Invalid value "${value}" for "${name}"`);
if (name === APP_SETTINGS.SHOW_POST_DATETIME) {
this.#enabled = value as boolean;
}
}
get SETTINGS(): APP_SETTINGS[] {
return Object.keys(DEFAULT_SETTINGS) as APP_SETTINGS[];
}
async #handleMouseOver(event: MouseEvent): Promise<void> {
if (!this.#enabled) return;
const target = event.target as HTMLElement;
if (target.tagName.toLowerCase() !== 'a') return;
let datetime = target.getAttribute(DATETIME_MARKER);
if (!datetime) {
try {
const {username, postId} = parsePostUrl(target.getAttribute('href'));
if (username && postId) {
const [identifier, password] = await getCredentials();
try {
const agent = await getAgent(identifier, password);
const post = | await fetchPost(agent, username, postId); |
datetime = parsePostDatetime(post.indexedAt);
target.setAttribute(DATETIME_MARKER, datetime);
} catch (error) {
if (error instanceof LoginError) alert('Login failed: wrong identifier or password');
return;
}
} else {
return;
}
} catch {
return;
}
}
const tooltip = createDatetimeTooltip(datetime);
document.body.appendChild(tooltip);
const instance = createPopper(target, tooltip, {
placement: 'top'
});
target.addEventListener('mouseleave', () => {
instance.destroy();
tooltip.remove();
}, {once: true});
}
}
| src/content/watchers/postDatetime.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": "const WHATSHOT_FEED = new Selector('[data-testid=\"whatshotFeedPage\"]');\nconst getNextPost = (post: HTMLElement): HTMLElement | null => {\n if (post.nextSibling) {\n return post.nextSibling as HTMLElement;\n } else {\n const parent = post.parentElement;\n if (parent && parent.nextSibling) {\n return parent.nextSibling.firstChild as HTMLElement;\n } else {\n return null;",
"score": 0.7617464065551758
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " }\n }\n};\nconst getPreviousPost = (post: HTMLElement): HTMLElement | null => {\n if (post.previousSibling) {\n return post.previousSibling as HTMLElement;\n } else {\n const parent = post.parentElement;\n if (parent && parent.previousSibling) {\n return parent.previousSibling.lastChild as HTMLElement;",
"score": 0.7473037242889404
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " return this.#activeTabSelector.clone();\n } else {\n return Promise.reject('Not on main page');\n }\n });\n }\n setCurrentPost(element: HTMLElement): Promise<HTMLElement> {\n return this.#resolveList().then((posts) => {\n for (const post of posts) {\n if (post === element || post.parentElement === element || post.contains(element)) {",
"score": 0.743611752986908
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " #findSearchBar(): Promise<HTMLElement> {\n return ultimatelyFind(document.body, SEARCH_BAR);\n }\n async #loadNewPosts(): Promise<void> {\n try {\n const tab = await this.#postList.getCurrentFeedTab();\n const tabContainer = await ultimatelyFind(this.#container, tab);\n const newPostsButton = tabContainer.childNodes[1] as HTMLElement;\n if (newPostsButton && newPostsButton.nextSibling) {\n newPostsButton.click();",
"score": 0.7417330741882324
},
{
"filename": "src/content/bsky/api.ts",
"retrieved_chunk": " throw new LoginError();\n }\n};\nexport const fetchPost = async (agent: BskyAgent, username: string, postId: string): Promise<Post> => {\n const did = await agent.resolveHandle({ handle: username }).then((response) => response.data.did);\n const response = await agent.getPostThread({uri: `at://${did}/app.bsky.feed.post/${postId}`});\n return response.data.thread.post as Post;\n};",
"score": 0.7339205145835876
}
] | typescript | await fetchPost(agent, username, postId); |
import { createPopper } from '@popperjs/core';
import {TSetting, TSettings} from '../../types';
import {APP_SETTINGS} from '../../shared/appSettings';
import {ISettingsSubscriber} from '../../interfaces';
import {Watcher} from './watcher';
import {getSettingsManager} from '../browser/settingsManager';
import {getAgent, fetchPost, LoginError} from '../bsky/api';
import {alert} from '../utils/notifications';
const DEFAULT_SETTINGS: Partial<TSettings> = {
[APP_SETTINGS.SHOW_POST_DATETIME]: false,
[APP_SETTINGS.BSKY_IDENTIFIER]: '',
[APP_SETTINGS.BSKY_PASSWORD]: ''
};
type PostUrl = {
username: string;
postId: string;
};
const POST_HREF_REGEX = /profile\/(.+)\/post\/([a-zA-Z0-9]+)$/;
const DATETIME_MARKER = 'data-bluesky-overhaul-datetime';
const getCredentials = async (): Promise<[string, string]> => {
const settingsManager = await getSettingsManager();
return await Promise.all([
settingsManager.get(APP_SETTINGS.BSKY_IDENTIFIER) as string,
settingsManager.get(APP_SETTINGS.BSKY_PASSWORD) as string
]);
};
const parsePostUrl = (url: string | null): PostUrl => {
if (!url) throw new Error('Missing post URL');
const match = url.match(POST_HREF_REGEX);
if (!match) throw new Error('Invalid post URL');
return {username: match[1], postId: match[2]};
};
const parsePostDatetime = (datetime: string): string => {
const date = new Date(datetime);
return date.toLocaleString('en-US', {
month: 'long', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'
});
};
const createDatetimeTooltip = (datetime: string): HTMLElement => {
const tooltip = document.createElement('div');
tooltip.role = 'tooltip';
tooltip.className = 'bluesky-overhaul-tooltip';
tooltip.textContent = datetime;
return tooltip;
};
export class PostDatetimeWatcher extends Watcher implements ISettingsSubscriber {
#container: HTMLElement;
#enabled: boolean;
constructor(container: HTMLElement) {
super();
this.#container = container;
this.#enabled = DEFAULT_SETTINGS[APP_SETTINGS.SHOW_POST_DATETIME] as boolean;
}
watch(): void {
this.#container.addEventListener('mouseover', this.#handleMouseOver.bind(this));
}
onSettingChange(name: APP_SETTINGS, value: TSetting): void {
if (!this.SETTINGS.includes(name)) throw new Error(`Unknown setting name "${name}"`);
if (typeof value !== typeof DEFAULT_SETTINGS[name]) throw new Error(`Invalid value "${value}" for "${name}"`);
if (name === APP_SETTINGS.SHOW_POST_DATETIME) {
this.#enabled = value as boolean;
}
}
get SETTINGS(): APP_SETTINGS[] {
return Object.keys(DEFAULT_SETTINGS) as APP_SETTINGS[];
}
async #handleMouseOver(event: MouseEvent): Promise<void> {
if (!this.#enabled) return;
const target = event.target as HTMLElement;
if (target.tagName.toLowerCase() !== 'a') return;
let datetime = target.getAttribute(DATETIME_MARKER);
if (!datetime) {
try {
const {username, postId} = parsePostUrl(target.getAttribute('href'));
if (username && postId) {
const [identifier, password] = await getCredentials();
try {
| const agent = await getAgent(identifier, password); |
const post = await fetchPost(agent, username, postId);
datetime = parsePostDatetime(post.indexedAt);
target.setAttribute(DATETIME_MARKER, datetime);
} catch (error) {
if (error instanceof LoginError) alert('Login failed: wrong identifier or password');
return;
}
} else {
return;
}
} catch {
return;
}
}
const tooltip = createDatetimeTooltip(datetime);
document.body.appendChild(tooltip);
const instance = createPopper(target, tooltip, {
placement: 'top'
});
target.addEventListener('mouseleave', () => {
instance.destroy();
tooltip.remove();
}, {once: true});
}
}
| src/content/watchers/postDatetime.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": "const WHATSHOT_FEED = new Selector('[data-testid=\"whatshotFeedPage\"]');\nconst getNextPost = (post: HTMLElement): HTMLElement | null => {\n if (post.nextSibling) {\n return post.nextSibling as HTMLElement;\n } else {\n const parent = post.parentElement;\n if (parent && parent.nextSibling) {\n return parent.nextSibling.firstChild as HTMLElement;\n } else {\n return null;",
"score": 0.769740104675293
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " }\n }\n};\nconst getPreviousPost = (post: HTMLElement): HTMLElement | null => {\n if (post.previousSibling) {\n return post.previousSibling as HTMLElement;\n } else {\n const parent = post.parentElement;\n if (parent && parent.previousSibling) {\n return parent.previousSibling.lastChild as HTMLElement;",
"score": 0.7509386539459229
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " #findSearchBar(): Promise<HTMLElement> {\n return ultimatelyFind(document.body, SEARCH_BAR);\n }\n async #loadNewPosts(): Promise<void> {\n try {\n const tab = await this.#postList.getCurrentFeedTab();\n const tabContainer = await ultimatelyFind(this.#container, tab);\n const newPostsButton = tabContainer.childNodes[1] as HTMLElement;\n if (newPostsButton && newPostsButton.nextSibling) {\n newPostsButton.click();",
"score": 0.7498592138290405
},
{
"filename": "src/content/pipelines/quotePost.ts",
"retrieved_chunk": " event.preventDefault();\n const contentEditable = this.#contentEditable;\n let data = event.clipboardData.getData('text/plain');\n if (data.match(STAGING_URL_REGEX) !== null) {\n data = data.replace('https://staging.bsky.app/', 'https://bsky.app/');\n }\n contentEditable.focus();\n typeText(data);\n typeText(' '); // Add a space after the link for it to resolve as one\n // Wait for the text to be inserted into the contentEditable",
"score": 0.7458010315895081
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " return this.#activeTabSelector.clone();\n } else {\n return Promise.reject('Not on main page');\n }\n });\n }\n setCurrentPost(element: HTMLElement): Promise<HTMLElement> {\n return this.#resolveList().then((posts) => {\n for (const post of posts) {\n if (post === element || post.parentElement === element || post.contains(element)) {",
"score": 0.7407971620559692
}
] | typescript | const agent = await getAgent(identifier, password); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.